diff --git a/CLAUDE.md b/CLAUDE.md index f4e0f0c..e3d4bad 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -71,6 +71,7 @@ The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/ - Dev workflow / phase branches / build → `docs/tooling/workflow.md` - Xcode project templates → `docs/tooling/xcode-templates.md` - AUv3 plugin internals (`LyrebirdAudioUnit`, `LyrebirdAUVoicePoolBinding`, `AUInput`, preset codable, parameter slots) → `Sources/Lyrebird/Lyrebird.docc/AUv3.md` +- ShoeGaze guitar-pedalboard sub-package (`Pedal`, `PedalBoard`, `ShoeGaze`, built-in pedals, `.testLoop` vs `.liveInput`, `lyrebird new --template shoegaze` workflow) → `docs/stdlib/shoegaze.md` **UI** - LyrebirdUI / parameter binding → `docs/ui/gui-system.md` @@ -324,6 +325,7 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th - `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` - `xorshift64Next(_:)` - `lyrebirdSeedXorshift64(from:mixConstant:)` / `lyrebirdSeedXorshift64(from:)` — `Math/LyrebirdConstants.swift`; init-time xorshift64 seed helper. Two-arg form decorrelates Audio/Control pairs via `mixConstant`; one-arg form is the convenience for stand-alone single-state owners (e.g. `DemandTemporalTendency` / `DemandTemporalBrownian`) +- `catmullRomCubic(_:_:_:_:t:)` — `Math/CubicInterpolation.swift`; the single shared 4-point Catmull-Rom cubic kernel. Pass `(pM1, p0, p1, p2, t:)` — the sample before the segment, the two bracketing it, the one after, and `t ∈ [0, 1]`. Use instead of inlining the `t²`/`t³` expanded form. `@inline(__always) @_spi(LyrebirdExtensions) public`. Consumers: oscillator table reads (`OscSin` / `oscillatorTableReadCubic`), `PlayBuffer`, `chaoticInterpolate`, and the fractional-delay lines (`DelayLine` / `DelayLineFeedback` / `CombFilter` / `AllpassFilter`). Full table, signatures, examples, and the per-generator exceptions (notably `MathGenerators.Control` and the non-standard ControlGenerator ramp paths) live in `docs/protocols/writing-generators.md` §13. That document is the single source of truth — when adding or removing a helper, update §13 and reference it from here. diff --git a/RELEASES.md b/RELEASES.md index 1848da3..a55f3b4 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -7,6 +7,80 @@ functionality in a backward-compatible way. --- +## 1.2.0 — Generator catalog expansion *(planned)* + +A minor release. Adds roughly forty SuperCollider-parity generators — +triggers, time-domain analysis, chaotic oscillators, resonator banks, dynamics, +waveshaping, routing/morph, and psychoacoustic metering — plus a `shoegaze` +guitar-pedalboard project template and an iOS path fix. Fully +backward-compatible; no changes to existing public API. + +### New generators + +**Trigger / timing.** `Trig` and `Trig1` (fixed-duration gate from a trigger), +`Schmidt` (hysteresis threshold), `Stepper` (trigger-advanced counter), +`PulseCount` (count triggers, reset on a second input), `TriggeredDelay` (hold +then re-emit a trigger). + +**Phasor / slew.** `Phasor` (sample-accurate sweeping ramp with wrap bounds and +trigger-reset), `Slew` (asymmetric slew-rate limiter). + +**Time-domain analysis.** `RunningMin`, `RunningMax` (running extrema, reset on +trigger), `Slope` (per-sample first difference), `ZeroCrossing` (zero-crossing +frequency estimator). + +**Routing / morph.** `Select` (index-select one of N inputs), `CrossFade` +(equal-power two-input mix), `LinearCrossFade` (linear two-input mix). + +**Waveshaping / distortion.** `Waveshaper` (transfer-function table lookup with +interpolation), `CrossoverDistortion` (dead-zone crossover), `Disintegrator` +(probabilistic sample mangling). + +**Resonant filter / LFO.** `Formlet` (FOF-style resonant formant filter), +`LFGauss` (Gaussian-bell LFO). + +**Chaotic oscillators.** `LorenzLinear`, `HenonStepped`, `QuadStepped`, +`LinCongStepped`, `GbmanStepped`, `StandardStepped`, `FBSineStepped`, +`LatoocarfianStepped`, `CuspStepped` — discrete chaotic maps, frequency-stepped +where SuperCollider steps them. + +**Resonator banks.** `Klank` (fixed bank of fixed-frequency resonators) and +`Klang` (bank of sine partials), both runtime-respecifiable. + +**Dynamics.** `Normalizer` (look-ahead peak normalizer) and `Balance` (RMS +level matcher, with `logDomain` for dB-domain gain and `smooth` for decoupled +gain lag). + +**Metering.** `BeatTrack` (FFT-based tempo / beat tracker) and `Loudness` +(Zwicker / ISO 532 B psychoacoustic loudness in sones). + +> `DFM1` (the remaining catalog candidate) is intentionally omitted: its source +> and lookup tables are GPL, incompatible with this project's MIT license. + +### Tooling + +- **`shoegaze` project template.** `lyrebird new MyRig --template shoegaze` + scaffolds a guitar-pedalboard app (macOS or iOS) that depends on the ShoeGaze + package — a set of effect "pedals" chained into boards, with knobs, bypass, + parallel routing, and recording. Ships with an Xcode "ShoeGaze Pedal" file + template for authoring custom pedals. ShoeGaze itself now lives in its own + repository rather than in-tree. + +### Fixes + +- **`LyrebirdPaths.home` on iOS** now returns the app's Documents directory + instead of `homeDirectoryForCurrentUser` (the sandbox root, which is not + writable on iOS). Unchanged on macOS. + +### Internals (no API impact) + +- The 4-point Catmull-Rom cubic interpolation duplicated across oscillator + table reads, `PlayBuffer`, and the fractional-delay lines is now a single + shared `catmullRomCubic` kernel. +- Generator tests regrouped by family. + +--- + ## 1.1.1 — Real-time performance + score-timing fixes *(planned)* A patch release: real-time CPU improvements to the synthesis engine's hot path, diff --git a/Sources/Lyrebird/Generators/Analysis/BeatTrack.swift b/Sources/Lyrebird/Generators/Analysis/BeatTrack.swift new file mode 100644 index 0000000..6d3b9bf --- /dev/null +++ b/Sources/Lyrebird/Generators/Analysis/BeatTrack.swift @@ -0,0 +1,280 @@ +// BeatTrack.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Real-time beat / tempo tracker. +/// +/// Estimates the period and phase of a musical pulse from an **onset detection +/// function** (ODF) by autocorrelation with phase locking, emitting +/// beat-synchronous triggers plus a continuous tempo estimate. The ODF source +/// is selected by ``BeatTrackODF``: +/// +/// - ``BeatTrackODF/spectralFlux(analysis:)`` — FFT-fed; the tracker computes +/// its own ODF as the spectral flux of a paired ``SpectralChain/Audio`` +/// (drop-in; equivalent to SuperCollider's `BeatTrack`). +/// - ``BeatTrackODF/feature(_:)`` — feature-fed; you supply the ODF as any +/// signal (equivalent to SuperCollider's `BeatTrack2`). +/// +/// Control-rate, 4-output: see ``BeatTrack/Control`` for the row layout. +/// +/// > This is an independent implementation of standard autocorrelation tempo +/// > induction with phase locking (see ``BeatTrackerCore``), not a port of any +/// > SuperCollider source. +public enum BeatTrack { + + /// Control-rate beat tracker. ODF source chosen at init via ``BeatTrackODF``. + /// + /// Emits four output rows: + /// - `0` — **beat** trigger (`1.0` for the block a beat fires on, else `0.0`) + /// - `1` — **eighth** trigger (2× the beat rate) + /// - `2` — **sixteenth** trigger (4× the beat rate) + /// - `3` — **tempo** in BPM (continuous) + /// + /// - Parameters: + /// - odf: Onset-detection-function source — FFT-fed or feature-fed. + /// - minBPM: Slowest detectable tempo. Read once at init. Defaults to ``beatTrackMinBPM``. + /// - maxBPM: Fastest detectable tempo. Read once at init. Defaults to ``beatTrackMaxBPM``. + /// - preferredBPM: Preference-weight centre + pre-lock default tempo. Read + /// once at init. Defaults to ``beatTrackPreferredBPM``. + /// - windowSeconds: ODF history length for autocorrelation. Read once at + /// init. Defaults to ``beatTrackMaxWindowSeconds``. + public final class Control: GeneratorBase, ControlGenerator { + + /// Internal ODF source + the input refs each mode needs. Only one mode's + /// state is live; the spectral-flux state (`_prevMag`, `_isFirstFrame`) + /// is dormant in feature mode. + private enum Source { + case spectralFlux(analysis: SpectralChain.Audio?, spectral: SpectralBuffer) + case feature(input: any ValidGeneratorInput, isGenerator: Bool) + } + + private let _source: Source + private var _prevMag: [Float] + private var _isFirstFrame: Bool = true + private let _core: BeatTrackerCore + public var previousOutputValue: Double = 0.0 + + public override var outputChannelCount: Int { beatTrackOutputRowCount } + + // MARK: - Public inits + + /// - Parameters: + /// - odf: Onset-detection-function source — FFT-fed or feature-fed. + /// - minBPM: Slowest detectable tempo. Read once at init. Defaults to ``beatTrackMinBPM``. + /// - maxBPM: Fastest detectable tempo. Read once at init. Defaults to ``beatTrackMaxBPM``. + /// - preferredBPM: Preference-weight centre + pre-lock default tempo. + /// Read once at init. Defaults to ``beatTrackPreferredBPM``. + /// - windowSeconds: ODF history length for autocorrelation. Read once + /// at init. Defaults to ``beatTrackMaxWindowSeconds``. + public convenience init( + odf: BeatTrackODF, + minBPM: Double = beatTrackMinBPM, + maxBPM: Double = beatTrackMaxBPM, + preferredBPM: Double = beatTrackPreferredBPM, + windowSeconds: Double = beatTrackMaxWindowSeconds + ) { + let source: Source + switch odf { + case .spectralFlux(let chain): + source = .spectralFlux(analysis: chain, spectral: chain.spectralBuffer) + case .feature(let signal): + let resolved: any ValidGeneratorInput = signal._resolvedInput() + source = .feature(input: resolved, isGenerator: resolved is any Generator) + } + self.init( + source: source, + minBPM: minBPM, + maxBPM: maxBPM, + preferredBPM: preferredBPM, + windowSeconds: windowSeconds + ) + } + + /// FFT-fed convenience: track the spectral flux of `analysis`. + /// + /// - Parameters: + /// - analysis: Paired ``SpectralChain/Audio`` (analyze-only). Its + /// `spectralBuffer` is read once per audio block to compute spectral flux. + /// - minBPM: Slowest detectable tempo. Defaults to ``beatTrackMinBPM``. + /// - maxBPM: Fastest detectable tempo. Defaults to ``beatTrackMaxBPM``. + /// - preferredBPM: Preference-weight centre + pre-lock default tempo. + /// Defaults to ``beatTrackPreferredBPM``. + /// - windowSeconds: ODF history length. Defaults to ``beatTrackMaxWindowSeconds``. + public convenience init( + analysis: SpectralChain.Audio, + minBPM: Double = beatTrackMinBPM, + maxBPM: Double = beatTrackMaxBPM, + preferredBPM: Double = beatTrackPreferredBPM, + windowSeconds: Double = beatTrackMaxWindowSeconds + ) { + self.init( + source: .spectralFlux(analysis: analysis, spectral: analysis.spectralBuffer), + minBPM: minBPM, + maxBPM: maxBPM, + preferredBPM: preferredBPM, + windowSeconds: windowSeconds + ) + } + + /// Feature-fed convenience: track an externally supplied ODF signal. + /// + /// - Parameters: + /// - feature: Onset detection function signal. Reduced to one ODF value + /// per audio block (block max). + /// - minBPM: Slowest detectable tempo. Defaults to ``beatTrackMinBPM``. + /// - maxBPM: Fastest detectable tempo. Defaults to ``beatTrackMaxBPM``. + /// - preferredBPM: Preference-weight centre + pre-lock default tempo. + /// Defaults to ``beatTrackPreferredBPM``. + /// - windowSeconds: ODF history length. Defaults to ``beatTrackMaxWindowSeconds``. + public convenience init( + feature: any ValidGeneratorInput, + minBPM: Double = beatTrackMinBPM, + maxBPM: Double = beatTrackMaxBPM, + preferredBPM: Double = beatTrackPreferredBPM, + windowSeconds: Double = beatTrackMaxWindowSeconds + ) { + let resolved: any ValidGeneratorInput = feature._resolvedInput() + self.init( + source: .feature(input: resolved, isGenerator: resolved is any Generator), + minBPM: minBPM, + maxBPM: maxBPM, + preferredBPM: preferredBPM, + windowSeconds: windowSeconds + ) + } + + /// Buffer-only FFT-fed convenience. For tests / advanced use; no analysis + /// auto-pull (the caller drives the chain populating `spectral`). + /// + /// - Parameters: + /// - spectral: Spectral frame buffer read each block for flux. + /// - minBPM: Slowest detectable tempo. Defaults to ``beatTrackMinBPM``. + /// - maxBPM: Fastest detectable tempo. Defaults to ``beatTrackMaxBPM``. + /// - preferredBPM: Preference-weight centre + pre-lock default tempo. + /// Defaults to ``beatTrackPreferredBPM``. + /// - windowSeconds: ODF history length. Defaults to ``beatTrackMaxWindowSeconds``. + public convenience init( + spectral: SpectralBuffer, + minBPM: Double = beatTrackMinBPM, + maxBPM: Double = beatTrackMaxBPM, + preferredBPM: Double = beatTrackPreferredBPM, + windowSeconds: Double = beatTrackMaxWindowSeconds + ) { + self.init( + source: .spectralFlux(analysis: nil, spectral: spectral), + minBPM: minBPM, + maxBPM: maxBPM, + preferredBPM: preferredBPM, + windowSeconds: windowSeconds + ) + } + + // MARK: - Designated init + + private init( + source: Source, + minBPM: Double, + maxBPM: Double, + preferredBPM: Double, + windowSeconds: Double + ) { + self._source = source + switch source { + case .spectralFlux(_, let spectral): + self._prevMag = [Float](repeating: 0, count: spectral.binCount) + case .feature: + self._prevMag = [] + } + self._core = BeatTrackerCore( + minBPM: minBPM, + maxBPM: maxBPM, + preferredBPM: preferredBPM, + windowSeconds: windowSeconds, + featureRateHz: beatTrackFeatureRateHz + ) + super.init(channels: beatTrackOutputRowCount) + _setupSubBlockBuffer(channels: beatTrackOutputRowCount) + } + + // MARK: - Compute + + // Bypass the sub-block loop: the ODF advances once per audio block (the + // spectral buffer once per FFT hop) and the tracker state must too. + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let odf: Double = computeODF(graph: graph, count: count) + + _core.processBlock( + odf: odf, + sampleCount: count, + sampleRate: graph.engine.sampleRate + ) + + previousOutputValue = fillBeatTrackerOutput( + into: &_result, core: _core, count: count) + return _result + } + + /// Per-block onset-detection-function value for the active source. + private func computeODF(graph: SynthGraph, count: Int) -> Double { + switch _source { + case .spectralFlux(let analysis, let spectral): + _ = analysis?.calculatedSamples(graph: graph, count: count) + return spectralFlux(spectral) + case .feature(let input, let isGenerator): + // Scalar feature → constant ODF (no per-block heap alloc); + // generator feature → block-max of its output row. + if isGenerator { + let row: [Double] = input.calculatedSamples( + graph: graph, count: count).first ?? [] + return blockMaxODF(row, count: count) + } + return max(0.0, input.floatValue(graph: graph)) + } + } + + /// Frame-to-frame magnitude-change flux (onset proxy). Identical measure + /// to ``SpectralFlux``: RMS of per-bin magnitude differences. Returns `0` + /// on the first block (no previous frame to compare). + private func spectralFlux(_ spectral: SpectralBuffer) -> Double { + let binCount: Int = spectral.binCount + guard binCount > 0 else { return 0.0 } + + if _isFirstFrame { + for k: Int in 0.. Double { + guard !row.isEmpty else { return 0.0 } + let n: Int = min(count, row.count) + var peak: Double = 0.0 + for i: Int in 0.. peak { peak = v } + } + return peak +} + +/// Fill the 4-row beat-tracker output buffer flat across the block from the +/// core's per-block trigger / tempo state. Returns the row-0 (beat) value for +/// `previousOutputValue`. No heap allocation — the four row values are filled +/// directly (no intermediate array). +@inline(__always) +internal func fillBeatTrackerOutput( + into result: inout [[Double]], + core: BeatTrackerCore, + count: Int +) -> Double { + let beat: Double = core.beatTriggered ? 1.0 : 0.0 + let eighth: Double = core.eighthTriggered ? 1.0 : 0.0 + let sixteenth: Double = core.sixteenthTriggered ? 1.0 : 0.0 + let tempo: Double = core.tempoBPM + fillFlatRow(&result, row: 0, value: beat, count: count) + fillFlatRow(&result, row: 1, value: eighth, count: count) + fillFlatRow(&result, row: 2, value: sixteenth, count: count) + fillFlatRow(&result, row: 3, value: tempo, count: count) + return beat +} + +/// Fill one output row with a constant value over `count` samples. +@inline(__always) +private func fillFlatRow( + _ result: inout [[Double]], + row: Int, + value: Double, + count: Int +) { + var v: Double = value + result[row].withUnsafeMutableBufferPointer { buf in + guard let base: UnsafeMutablePointer = buf.baseAddress else { return } + vDSP_vfillD(&v, base, 1, vDSP_Length(count)) + } +} diff --git a/Sources/Lyrebird/Generators/Analysis/BeatTrackODF.swift b/Sources/Lyrebird/Generators/Analysis/BeatTrackODF.swift new file mode 100644 index 0000000..8337522 --- /dev/null +++ b/Sources/Lyrebird/Generators/Analysis/BeatTrackODF.swift @@ -0,0 +1,29 @@ +// BeatTrackODF.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Selects where ``BeatTrack`` gets its onset detection function (ODF) — the +/// one-dimensional signal whose peaks the tracker locks onto. +/// +/// This is the implementation flag that folds the two SuperCollider beat-tracker +/// flavours into a single ``BeatTrack`` generator. The cases carry different +/// inputs (an FFT chain vs an arbitrary signal), so the selector is an enum +/// rather than a `Bool`. +public enum BeatTrackODF { + + /// FFT-fed: compute the ODF internally as the spectral flux of `analysis` + /// (the same frame-to-frame magnitude-change measure as ``SpectralFlux``). + /// Drop-in — wire an analyze-only ``SpectralChain/Audio`` on the source you + /// want to track. Equivalent to SuperCollider's `BeatTrack`. + case spectralFlux(analysis: SpectralChain.Audio) + + /// Feature-fed: take an externally supplied ODF — any signal whose peaks + /// coincide with onsets (``SpectralFlux``, ``OnsetDetector``, an + /// amplitude-difference feature, …). Reduced to one ODF value per audio + /// block (block max). Equivalent to SuperCollider's `BeatTrack2`. + case feature(any ValidGeneratorInput) +} diff --git a/Sources/Lyrebird/Generators/Analysis/BeatTrackerCore.swift b/Sources/Lyrebird/Generators/Analysis/BeatTrackerCore.swift new file mode 100644 index 0000000..50a67f2 --- /dev/null +++ b/Sources/Lyrebird/Generators/Analysis/BeatTrackerCore.swift @@ -0,0 +1,330 @@ +// BeatTrackerCore.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Shared autocorrelation tempo + beat-phase tracker backing ``BeatTrack`` (both +/// the FFT-fed and feature-fed ODF sources). Independent of the `Generator` +/// machinery: it consumes one per-audio-block onset-detection-function (ODF) +/// value at a time and produces beat / eighth / sixteenth triggers plus a +/// continuous tempo estimate. +/// +/// All buffers are allocated once at `init`; ``processBlock(odf:sampleCount:)`` +/// performs no allocation and is safe to call from the render thread (the +/// front-end generators call it from `_computeSamples`). +/// +/// ## Pipeline +/// 1. **Decimation** — per-block ODF values are combined by max over a feature +/// hop of `round(sampleRate / featureRateHz)` samples; each completed hop +/// emits one ODF feature. +/// 2. **Whitening** — a running mean is subtracted and the result half-wave +/// rectified, removing DC / drift bias. +/// 3. **History** — features are pushed into a power-of-two ring buffer. +/// 4. **Tempo induction** — every ``analysisHop`` features the windowed ODF is +/// autocorrelated over the lag range for `[minBPM, maxBPM]`, weighted by a +/// log-Gaussian preference curve; the peak lag is the smoothed beat period. +/// 5. **Phase locking** — a phase accumulator advances at the current tempo; +/// each analysis re-aligns it to the recent ODF peaks. +/// +/// Algorithm is an independent implementation of standard autocorrelation tempo +/// induction with phase locking — not a port of any SuperCollider source. +final class BeatTrackerCore { + + // MARK: - Configuration (fixed at init) + + /// Samples per emitted feature. Sample-rate dependent, so resolved lazily on + /// the first ``processBlock(odf:sampleCount:sampleRate:)`` (the only piece of + /// state that needs the engine sample rate — ring size and lag range derive + /// from the nominal feature rate alone). `0` until resolved. + private var featureHop: Int = 0 + private let ringMask: Int + private let windowLen: Int + private let lagMin: Int + private let lagMax: Int + private let analysisHop: Int + private let preferredLag: Double + private let preferenceWidth: Double + private let tempoSmoothing: Double + private let meanAdaptCoeff: Double + private let featureRate: Double + private let minPeriod: Double + private let maxPeriod: Double + + // MARK: - Buffers (allocated once) + + private var ring: [Double] + + // MARK: - Decimation state + + private var sampleAccum: Int = 0 + private var odfAccum: Double = 0.0 + + // MARK: - History state + + private var writeIndex: Int = 0 + private var featureCount: Int = 0 + private var meanODF: Double = 0.0 + + // MARK: - Tempo / phase state + + private var period: Double + private var phase: Double = 0.0 + private var analysisCountdown: Int + + // MARK: - Per-block outputs + + /// `true` when a beat fired during the most recent ``processBlock(odf:sampleCount:)``. + private(set) var beatTriggered: Bool = false + /// `true` when an eighth-note subdivision fired (2× the beat rate). + private(set) var eighthTriggered: Bool = false + /// `true` when a sixteenth-note subdivision fired (4× the beat rate). + private(set) var sixteenthTriggered: Bool = false + /// Current tempo estimate in BPM. + private(set) var tempoBPM: Double + + // MARK: - Init + + /// - Parameters: + /// - minBPM: Slowest detectable tempo. + /// - maxBPM: Fastest detectable tempo. + /// - preferredBPM: Preference-weight centre + pre-lock default tempo. + /// - windowSeconds: ODF history length for autocorrelation. + /// - featureRateHz: ODF decimation target rate. + init( + minBPM: Double, + maxBPM: Double, + preferredBPM: Double, + windowSeconds: Double, + featureRateHz: Double + ) { + let safeFeatureRate: Double = max(1.0, featureRateHz) + let safeMinBPM: Double = max(1.0, min(minBPM, maxBPM)) + let safeMaxBPM: Double = max(safeMinBPM + 1.0, max(minBPM, maxBPM)) + + self.featureRate = safeFeatureRate + + // Lag range from the tempo bounds: lag (features) = featureRate · 60 / BPM. + let minLagD: Double = safeFeatureRate * beatTrackSecondsPerMinute / safeMaxBPM + let maxLagD: Double = safeFeatureRate * beatTrackSecondsPerMinute / safeMinBPM + self.lagMin = max(1, Int(minLagD.rounded(.down))) + self.lagMax = max(self.lagMin + 1, Int(maxLagD.rounded(.up))) + self.minPeriod = minLagD + self.maxPeriod = maxLagD + + // History window: at least a few of the longest periods. + let requestedFeatures: Int = max( + self.lagMax * 2, + Int((max(0.1, windowSeconds) * safeFeatureRate).rounded(.up)) + ) + let ringSize: Int = lyrebirdNextPowerOfTwo(max(2, requestedFeatures)) + self.ring = [Double](repeating: 0.0, count: ringSize) + self.ringMask = ringSize - 1 + // Cap the analysis window so the oldest (sample, lag) pair never wraps + // past the ring onto just-written features: even when `requestedFeatures` + // is an exact power of two (then `ringSize == requestedFeatures`), keep + // `windowLen + lagMax ≤ ringSize`. + self.windowLen = max(self.lagMin + 1, min(requestedFeatures, ringSize - self.lagMax)) + + self.analysisHop = max(1, beatTrackAnalysisHopFeatures) + self.preferredLag = safeFeatureRate * beatTrackSecondsPerMinute / max(1.0, preferredBPM) + self.preferenceWidth = max(0.05, beatTrackPreferenceWidthOctaves) + self.tempoSmoothing = min(0.999, max(0.0, beatTrackTempoSmoothing)) + + // Per-feature one-pole coefficient for the running-mean subtraction. + let meanTimeFeatures: Double = max(1.0, beatTrackMeanAdaptSeconds * safeFeatureRate) + self.meanAdaptCoeff = 1.0 - Foundation.exp(-1.0 / meanTimeFeatures) + + self.period = self.preferredLag + self.tempoBPM = max(safeMinBPM, min(safeMaxBPM, preferredBPM)) + self.analysisCountdown = self.analysisHop + } + + // MARK: - Per-block entry point + + /// Feed one audio block's ODF value. Updates the decimation accumulator and, + /// for every completed feature hop, advances the tracker. The trigger / + /// tempo outputs reflect the state after this block. + /// + /// - Parameters: + /// - odf: This block's onset-detection-function value (≥ 0). + /// - sampleCount: Number of audio samples in this block. + /// - sampleRate: Engine sample rate (Hz); resolves the feature hop on first call. + func processBlock(odf: Double, sampleCount: Int, sampleRate: Double) { + beatTriggered = false + eighthTriggered = false + sixteenthTriggered = false + + if featureHop == 0 { + let safeSampleRate: Double = max(1.0, sampleRate) + featureHop = max(1, Int((safeSampleRate / featureRate).rounded())) + } + + let safeODF: Double = odf.isFinite ? max(0.0, odf) : 0.0 + odfAccum = max(odfAccum, safeODF) + sampleAccum += max(0, sampleCount) + + // Emit as many features as the accumulated sample count allows (handles + // blocks longer than one feature hop). Triggers OR across features. + while sampleAccum >= featureHop { + sampleAccum -= featureHop + emitFeature(odfAccum) + odfAccum = 0.0 + } + } + + // MARK: - Feature processing + + private func emitFeature(_ raw: Double) { + // Whiten: subtract a slow running mean, half-wave rectify. + meanODF += (raw - meanODF) * meanAdaptCoeff + var value: Double = raw - meanODF + if value < 0.0 { value = 0.0 } + value = denormalsToZero(value) + + ring[writeIndex & ringMask] = value + writeIndex += 1 + featureCount += 1 + + advancePhase() + + analysisCountdown -= 1 + // Need at least the longest lag plus one beat of history before the ACF + // is meaningful. + if analysisCountdown <= 0 && featureCount >= lagMax + lagMin { + analysisCountdown = analysisHop + runAnalysis() + } + } + + /// Advance the beat-phase accumulator by one feature at the current tempo, + /// firing nested subdivision triggers on grid crossings. + private func advancePhase() { + let safePeriod: Double = max(1.0, period) + let increment: Double = 1.0 / safePeriod + let raw: Double = phase + increment + + // Nested crossings: beat = integer, eighth = ½, sixteenth = ¼. A beat + // boundary (raw ≥ 1) also crosses an eighth and sixteenth boundary, so + // counts accumulate as beats:N, eighths:2N, sixteenths:4N. + if raw >= 1.0 { beatTriggered = true } + if Foundation.floor(raw * beatTrackEighthsPerBeat) + > Foundation.floor(phase * beatTrackEighthsPerBeat) { eighthTriggered = true } + if Foundation.floor(raw * beatTrackSixteenthsPerBeat) + > Foundation.floor(phase * beatTrackSixteenthsPerBeat) { sixteenthTriggered = true } + + var wrapped: Double = raw.truncatingRemainder(dividingBy: 1.0) + if wrapped < 0.0 { wrapped += 1.0 } + phase = wrapped + } + + // MARK: - Tempo induction + + private func runAnalysis() { + let available: Int = min(featureCount, windowLen) + guard available > lagMax else { return } + + var bestLag: Int = 0 + var bestScore: Double = 0.0 + var bestRawPeak: Double = 0.0 + + // Weighted, length-normalised autocorrelation over the candidate lags. + for lag: Int in lagMin...lagMax { + let terms: Int = available - lag + if terms <= 0 { continue } + var sum: Double = 0.0 + for j: Int in 0.. bestScore { + bestScore = score + bestLag = lag + bestRawPeak = acf + } + } + + // No clear pulse → hold the current period and let the phase free-run. + guard bestLag > 0, bestRawPeak > beatTrackMinPeakStrength else { return } + + let refinedLag: Double = parabolicPeak(around: bestLag, available: available) + let clampedLag: Double = min(maxPeriod, max(minPeriod, refinedLag)) + + period = tempoSmoothing * period + (1.0 - tempoSmoothing) * clampedLag + period = max(1.0, period) + tempoBPM = beatTrackSecondsPerMinute * featureRate / period + + realignPhase(periodLag: clampedLag) + } + + /// Log-Gaussian preference weight centred on ``preferredLag``. + private func preferenceWeight(forLag lag: Double) -> Double { + let octaves: Double = Foundation.log2(lag / preferredLag) + let z: Double = octaves / preferenceWidth + return Foundation.exp(-beatTrackGaussianExponentCoeff * z * z) + } + + /// Sub-feature peak location via parabolic interpolation of the + /// length-normalised ACF at `lag-1, lag, lag+1`. + private func parabolicPeak(around lag: Int, available: Int) -> Double { + let lagD: Double = Double(lag) + guard lag - 1 >= lagMin, lag + 1 <= lagMax else { return lagD } + let ym: Double = normalisedACF(lag: lag - 1, available: available) + let y0: Double = normalisedACF(lag: lag, available: available) + let yp: Double = normalisedACF(lag: lag + 1, available: available) + let denom: Double = ym - 2.0 * y0 + yp + if abs(denom) < beatTrackParabolicEpsilon { return lagD } + let delta: Double = beatTrackParabolicCoeff * (ym - yp) / denom + if delta < -1.0 || delta > 1.0 { return lagD } + return lagD + delta + } + + private func normalisedACF(lag: Int, available: Int) -> Double { + let terms: Int = available - lag + if terms <= 0 { return 0.0 } + var sum: Double = 0.0 + for j: Int in 0..= p else { return } + + var bestOffset: Int = 0 + var bestEnergy: Double = -1.0 + for offset: Int in 0..

bestEnergy { + bestEnergy = energy + bestOffset = offset + } + } + + // The most recent feature (offset 0) sits `bestOffset` features after the + // last on-grid beat, so its beat fraction is bestOffset / period. + var newPhase: Double = Double(bestOffset) / max(1.0, period) + newPhase = newPhase.truncatingRemainder(dividingBy: 1.0) + if newPhase < 0.0 { newPhase += 1.0 } + phase = newPhase + } +} diff --git a/Sources/Lyrebird/Generators/Analysis/Loudness.swift b/Sources/Lyrebird/Generators/Analysis/Loudness.swift new file mode 100644 index 0000000..2a95978 --- /dev/null +++ b/Sources/Lyrebird/Generators/Analysis/Loudness.swift @@ -0,0 +1,172 @@ +// Loudness.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Psychoacoustic loudness meter — perceived loudness in **sones** from the +/// magnitude spectrum of a paired analyze-only ``SpectralChain/Audio``. +/// +/// Three fidelity models are folded into the one generator behind a +/// ``LoudnessModel`` flag (mirroring the `Balance` `logDomain:` and `BeatTrack` +/// `BeatTrackODF` folds): +/// +/// - ``LoudnessModel/barkEstimate`` — cheap Stevens power-law band estimate. +/// - ``LoudnessModel/realtimeZwicker(smask:tmask:)`` — SC `Loudness`-style +/// critical-band Zwicker loudness with spectral + temporal masking. +/// - ``LoudnessModel/iso532b(field:)`` — full ISO 532 B / DIN 45631 stationary +/// Zwicker loudness. +/// +/// Control-rate, single-row output (sones). See ``Loudness/Control``. +/// +/// > **Clean-room note.** SuperCollider's `Loudness` (Nick Collins) is GPL. This +/// > is an independent implementation from the published Zwicker model and the +/// > ISO 532 B / DIN 45631 standard; output is in sones, not bit-exact with SC. +public enum Loudness { + + /// Control-rate loudness meter. Model selected at init via ``LoudnessModel``. + /// + /// - Parameters: + /// - model: Loudness model + its parameters. Defaults to + /// ``LoudnessModel/realtimeZwicker(smask:tmask:)`` with the standard + /// `smask`/`tmask`. + /// - analysis: Paired ``SpectralChain/Audio`` (analyze-only). Its + /// `spectralBuffer` is read once per audio block. + /// - sampleRate: Sample rate in Hz (bin→frequency mapping + block timing). + /// - calibrationDB: dBFS→SPL offset. Defaults to ``loudnessDefaultCalibrationDB``. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset (sones). Defaults to `0.0`. + public final class Control: GeneratorBase, ControlGenerator { + + private let _analysis: SpectralChain.Audio? + private let _spectral: SpectralBuffer + private let _model: LoudnessModel + private let _core: LoudnessBandCore + private let _sampleRate: Double + private var _mulAdd: MulAddSpec + public var previousOutputValue: Double = 0.0 + private var _rampTarget: Double = 0.0 + + /// - Parameters: + /// - model: Loudness model + parameters. Defaults to + /// ``LoudnessModel/realtimeZwicker(smask:tmask:)``. + /// - analysis: Paired ``SpectralChain/Audio`` (analyze-only). + /// - sampleRate: Sample rate in Hz. + /// - calibrationDB: dBFS→SPL offset. Defaults to ``loudnessDefaultCalibrationDB``. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset (sones). Defaults to `0.0`. + public convenience init( + model: LoudnessModel = .realtimeZwicker( + smask: loudnessDefaultSMask, tmask: loudnessDefaultTMask), + analysis: SpectralChain.Audio, + sampleRate: Double, + calibrationDB: Double = loudnessDefaultCalibrationDB, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + self.init( + model: model, + analysis: analysis, + spectral: analysis.spectralBuffer, + sampleRate: sampleRate, + calibrationDB: calibrationDB, + mul: mul, + add: add + ) + } + + /// Buffer-only init. For tests / advanced use; no analysis auto-pull. + /// + /// - Parameters: + /// - model: Loudness model + parameters. + /// - spectral: Spectral frame buffer read each block. + /// - sampleRate: Sample rate in Hz. + /// - calibrationDB: dBFS→SPL offset. Defaults to ``loudnessDefaultCalibrationDB``. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset (sones). Defaults to `0.0`. + public convenience init( + model: LoudnessModel = .realtimeZwicker( + smask: loudnessDefaultSMask, tmask: loudnessDefaultTMask), + spectral: SpectralBuffer, + sampleRate: Double, + calibrationDB: Double = loudnessDefaultCalibrationDB, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + self.init( + model: model, + analysis: nil, + spectral: spectral, + sampleRate: sampleRate, + calibrationDB: calibrationDB, + mul: mul, + add: add + ) + } + + private init( + model: LoudnessModel, + analysis: SpectralChain.Audio?, + spectral: SpectralBuffer, + sampleRate: Double, + calibrationDB: Double, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + self._analysis = analysis + self._spectral = spectral + self._model = model + self._sampleRate = max(1.0, sampleRate) + self._core = LoudnessBandCore( + fftSize: spectral.fftSize, + sampleRate: sampleRate, + calibrationDB: calibrationDB, + binCount: spectral.binCount + ) + self._mulAdd = MulAddSpec(mul: mul, add: add) + super.init() + _setupSubBlockBuffer() + } + + // Bypass the sub-block loop: the spectral buffer advances once per FFT + // hop and the loudness state (temporal mask) advances once per block. + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + _ = _analysis?.calculatedSamples(graph: graph, count: count) + + let blockSeconds: Double = Double(count) / _sampleRate + let sones: Double = _core.loudness( + spectral: _spectral, model: _model, blockSeconds: blockSeconds) + + let target: Double = sones + let rampStart: Double = _rampTarget + _rampTarget = target + guard count > 0 else { return _result } + previousOutputValue = fillRampedResult( + into: &_result, + from: rampStart, + to: target, + mulAdd: _mulAdd, + graph: graph, + count: count + ) + return _result + } + } +} + +// MARK: - GeneratorEnum +// GeneratorEnum conformance omitted: Loudness is Control-rate only. diff --git a/Sources/Lyrebird/Generators/Analysis/LoudnessBandCore.swift b/Sources/Lyrebird/Generators/Analysis/LoudnessBandCore.swift new file mode 100644 index 0000000..d22f667 --- /dev/null +++ b/Sources/Lyrebird/Generators/Analysis/LoudnessBandCore.swift @@ -0,0 +1,315 @@ +// LoudnessBandCore.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Shared loudness back-end for ``Loudness``: bins a `SpectralBuffer` into +/// third-octave band levels (dB SPL via the calibration offset), then computes +/// total loudness in sones under one of the three ``LoudnessModel`` algorithms. +/// +/// All buffers are allocated once at `init`; the per-block methods perform no +/// allocation (RT-safe). The ISO 532 B path is an independent implementation of +/// the published DIN 45631 / Zwicker stationary algorithm. +final class LoudnessBandCore { + + // MARK: - Fixed at init + + private let calibrationDB: Double + /// `binBand[k]` = third-octave band index for FFT bin `k`, or `-1` if the + /// bin falls outside the 25 Hz … 12.5 kHz grid. + private let binBand: [Int] + private let binCount: Int + + // MARK: - Scratch (allocated once) + + private var bandPower: [Double] // 28 third-octave band powers (linear) + private var bandLevel: [Double] // 28 third-octave band levels (dB SPL) + private var coreLoudness: [Double] // 21 critical-band core loudnesses + private var critLevel: [Double] // 20 critical-band levels (dB, ear-corrected) + private var ti: [Double] // low-band intensities (ISO core path) + private var logic: [Bool] // RAP-range comparison flags (ISO core path) + + // MARK: - Temporal-mask state (realtimeZwicker only) + + private var tmaskState: Double = 0.0 + + // MARK: - Init + + /// - Parameters: + /// - fftSize: FFT size of the paired analysis chain. + /// - sampleRate: Engine sample rate (Hz), for bin→Hz mapping. + /// - calibrationDB: dBFS→SPL offset added to each band power level. + /// - binCount: Number of spectral bins (`fftSize/2 + 1`). + init(fftSize: Int, sampleRate: Double, calibrationDB: Double, binCount: Int) { + self.calibrationDB = calibrationDB + self.binCount = max(0, binCount) + + let safeSampleRate: Double = max(1.0, sampleRate) + let binHz: Double = safeSampleRate / Double(max(1, fftSize)) + let ratio: Double = Foundation.pow(2.0, loudnessThirdOctaveHalfBandwidthExponent) + + var map: [Int] = [Int](repeating: -1, count: self.binCount) + for k: Int in 0..= lo && freq < hi { + band = j + break + } + } + map[k] = band + } + self.binBand = map + + self.bandPower = [Double](repeating: 0.0, count: loudnessISOThirdOctaveCount) + self.bandLevel = [Double](repeating: 0.0, count: loudnessISOThirdOctaveCount) + self.coreLoudness = [Double](repeating: 0.0, count: loudnessCriticalBandCount + 1) + self.critLevel = [Double](repeating: 0.0, count: loudnessCriticalBandCount) + self.ti = [Double](repeating: 0.0, count: loudnessISOLowBandCount) + self.logic = [Bool](repeating: false, count: loudnessISORAP.count) + } + + // MARK: - Critical-band levels (shared by the Zwicker models) + + /// Fill `critLevel[0..19]` with ear-corrected critical-band levels. The first + /// three bands are the combined low third-octave bands (`computeLCB`); the + /// rest map one-to-one onto third-octave bands 315 Hz … 12.5 kHz. + /// + /// - Parameters: + /// - lowFreqCorrected: apply the `RAP`/`DLL` equal-loudness correction to + /// the low bands (ISO 532 B) vs a plain power sum (real-time). + /// - field: free/diffuse field selector. + private func fillCriticalLevels(lowFreqCorrected: Bool, field: LoudnessField) { + let lcb: (Double, Double, Double) = computeLCB(corrected: lowFreqCorrected) + let offset: Int = loudnessISOThirdOctaveCount - loudnessCriticalBandCount + for z: Int in 0.. (Double, Double, Double) { + for i: Int in 0.. (loudnessISORAP[j] - loudnessISODLL[j][i]) + } + corr = loudnessISODLL[0][i] + if logic[0] { corr = 0.0 } + for j: Int in 1..<(loudnessISORAP.count - 1) { + if logic[j - 1] != logic[j] { corr = loudnessISODLL[j][i] } + } + } + let xp: Double = level + corr + ti[i] = Foundation.pow(loudnessDBDecadeFactor, xp / loudnessDBDecadeFactor) + } + let gi0: Double = ti[0] + ti[1] + ti[2] + ti[3] + ti[4] + ti[5] + let gi1: Double = ti[6] + ti[7] + ti[8] + let gi2: Double = ti[9] + ti[10] + let lcb0: Double = gi0 > 0.0 ? loudnessDBDecadeFactor * Foundation.log10(gi0) : 0.0 + let lcb1: Double = gi1 > 0.0 ? loudnessDBDecadeFactor * Foundation.log10(gi1) : 0.0 + let lcb2: Double = gi2 > 0.0 ? loudnessDBDecadeFactor * Foundation.log10(gi2) : 0.0 + return (lcb0, lcb1, lcb2) + } + + // MARK: - Band binning + + /// Fill `bandLevel` (dB SPL) from the spectral buffer's bin magnitudes. + private func updateBandLevels(_ spectral: SpectralBuffer) { + for j: Int in 0.. loudnessMaxBandLevelDB { bandLevel[j] = loudnessMaxBandLevelDB } + } + } + + // MARK: - Model dispatch + + /// Total loudness in sones for `model` from the current spectral frame. + /// `blockSeconds` is the audio-block duration (for the temporal mask). + func loudness( + spectral: SpectralBuffer, + model: LoudnessModel, + blockSeconds: Double + ) -> Double { + updateBandLevels(spectral) + switch model { + case .barkEstimate: + return barkEstimateLoudness() + case .realtimeZwicker(let smask, let tmask): + return realtimeZwickerLoudness(smask: smask, tmask: tmask, blockSeconds: blockSeconds) + case .iso532b(let field): + return iso532bLoudness(field: field) + } + } + + // MARK: - Model 1: Bark/third-octave Stevens estimate + + private func barkEstimateLoudness() -> Double { + var total: Double = 0.0 + let calibrationFactor: Double = Foundation.pow( + loudnessDBDecadeFactor, calibrationDB / loudnessDBDecadeFactor) + for j: Int in 0.. Double { + // Simplified core loudness: the same critical-band levels as ISO 532 B + // (low bands combined into LCB, but without the RAP/DLL/DCB/korry + // refinement), with the spectral-masking constant exposed as `smask`. + // Then the shared upper-slope integration, followed by the temporal mask. + let s: Double = min(1.0, max(0.0, smask)) + fillCriticalLevels(lowFreqCorrected: false, field: .free) + for z: Int in 0.. ltq { + let mp1: Double = loudnessZwickerConst + * Foundation.pow(loudnessDBDecadeFactor, loudnessZwickerThresholdCoeff * ltq) + let inner: Double = 1.0 - s + + s * Foundation.pow(loudnessDBDecadeFactor, loudnessLevelToPowerCoeff * (le - ltq)) + let mp2: Double = Foundation.pow(inner, loudnessZwickerExponent) - 1.0 + coreLoudness[z] = max(0.0, mp1 * mp2) + } else { + coreLoudness[z] = 0.0 + } + } + coreLoudness[loudnessCriticalBandCount] = 0.0 + + let base: Double = integrateUpperSlopes() + + // Temporal mask: instant attack, exponential release toward 0. + let safeTMask: Double = max(loudnessTinyPower, tmask) + let coeff: Double = Foundation.exp(-max(0.0, blockSeconds) / safeTMask) + let released: Double = tmaskState * coeff + let out: Double = max(base, released) + tmaskState = denormalsToZero(out) + return out.isFinite ? max(0.0, out) : 0.0 + } + + // MARK: - Model 3: ISO 532 B / DIN 45631 stationary Zwicker + + private func iso532bLoudness(field: LoudnessField) -> Double { + computeCoreLoudness(field: field) + return integrateUpperSlopes() + } + + /// Fill `coreLoudness[0..20]` (main loudness per critical band) per DIN 45631. + private func computeCoreLoudness(field: LoudnessField) { + // Ear-corrected critical-band levels with the RAP/DLL low-frequency + // correction (the full standard). + fillCriticalLevels(lowFreqCorrected: true, field: field) + + for z: Int in 0.. ltq { le -= loudnessISODCB[z] } + + if le > ltq { + let mp1: Double = loudnessZwickerConst + * Foundation.pow(loudnessDBDecadeFactor, loudnessZwickerThresholdCoeff * ltq) + let inner: Double = 1.0 - loudnessISOCoreS + + loudnessISOCoreS * Foundation.pow( + loudnessDBDecadeFactor, loudnessLevelToPowerCoeff * (le - ltq)) + let mp2: Double = Foundation.pow(inner, loudnessZwickerExponent) - 1.0 + coreLoudness[z] = max(0.0, mp1 * mp2) + } else { + coreLoudness[z] = 0.0 + } + } + coreLoudness[loudnessCriticalBandCount] = 0.0 // appended sentinel band + + // Lowest-band threshold-dependence correction. + let korry: Double = loudnessKorryBase + + loudnessKorryScale * Foundation.pow(coreLoudness[0], loudnessKorryExponent) + if korry <= 1.0 { coreLoudness[0] *= korry } + } + + /// Integrate the specific-loudness function with the Zwicker upper slopes → + /// total loudness (sones). Walks each critical band's flat top plus the + /// upper-slope tail spilling into higher bands. + private func integrateUpperSlopes() -> Double { + var total: Double = 0.0 + var z1: Double = 0.0 + var n1: Double = 0.0 + let maxColumn: Int = loudnessISOUSL[0].count - 1 // USL has 8 critical-band columns + + for i: Int in 0..<(loudnessCriticalBandCount + 1) { + let zupI: Double = loudnessISOZUP[i] + var ig: Int = i - 1 + if ig > maxColumn { ig = maxColumn } + if ig < 0 { ig = 0 } + let nmI: Double = coreLoudness[i] + + while true { + if n1 <= nmI { + // Rising / flat: plateau at nmI across the band. + total += nmI * (zupI - z1) + z1 = zupI + n1 = nmI + break + } + // Decreasing: upper slope from (z1, n1) down through rns ranges. + var j: Int = 0 + while j < (loudnessISORNS.count - 1) && loudnessISORNS[j] >= n1 { j += 1 } + let n2: Double = max(loudnessISORNS[j], nmI) + let slope: Double = loudnessISOUSL[j][ig] + let dz: Double = slope > 0.0 ? (n1 - n2) / slope : (zupI - z1) + var z2: Double = z1 + dz + + if z2 >= zupI { + z2 = zupI + let nEdge: Double = n1 - slope * (z2 - z1) + total += loudnessTrapezoidalFactor * (n1 + nEdge) * (z2 - z1) + z1 = zupI + n1 = nEdge + break + } + total += loudnessTrapezoidalFactor * (n1 + n2) * (z2 - z1) + z1 = z2 + n1 = n2 + // Loop continues for the next rns range within the same band. + } + } + return total.isFinite ? max(0.0, total) : 0.0 + } +} diff --git a/Sources/Lyrebird/Generators/Analysis/LoudnessConstants.swift b/Sources/Lyrebird/Generators/Analysis/LoudnessConstants.swift new file mode 100644 index 0000000..5c04d3c --- /dev/null +++ b/Sources/Lyrebird/Generators/Analysis/LoudnessConstants.swift @@ -0,0 +1,169 @@ +// LoudnessConstants.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +// MARK: - General + +/// Default dBFS→SPL calibration offset (dB) added to each bin's power level. +/// Chosen so a full-scale sinusoid lands near the top of the musical SPL range. +public let loudnessDefaultCalibrationDB: Double = 90.0 + +/// Floor added inside `log10` to guard the silence case (`log10(0)`). +public let loudnessTinyPower: Double = 1.0e-30 + +/// Decade factor for dB ↔ power/intensity conversions (`L = 10·log10(P)`, +/// `P = 10^(L/10)`). +public let loudnessDBDecadeFactor: Double = 10.0 + +/// Trapezoidal-rule factor (`½`) for the upper-slope area integration. +public let loudnessTrapezoidalFactor: Double = 0.5 + +/// Exponent for the third-octave half-bandwidth ratio `2^(1/6)`. +public let loudnessThirdOctaveHalfBandwidthExponent: Double = 1.0 / 6.0 + +/// Stevens' power-law exponent on intensity for the `.barkEstimate` model +/// (`N ∝ I^0.3` → +10 dB ≈ 2×). +public let loudnessStevensExponent: Double = 0.3 + +/// Output scaling for `.barkEstimate` so a 1 kHz tone near 40 dB SPL lands near +/// 1 sone (the model has no equal-loudness contour, so this is an anchor fit: +/// `(10^(40/10))^0.3 ≈ 15.85`, so the scale is `≈ 1/15.85`). +public let loudnessBarkEstimateScale: Double = 0.0631 + +/// Zwicker specific-loudness constant (`0.0635 = 0.0635`). Specific loudness +/// `N' = const · 10^(0.025·LTQ) · ((1 − s + s·10^(0.1·(L−LTQ)))^0.25 − 1)`. +public let loudnessZwickerConst: Double = 0.0635 + +/// Exponent in the Zwicker specific-loudness law (`^0.25`). +public let loudnessZwickerExponent: Double = 0.25 + +/// `10^(0.025·LTQ)` coefficient exponent factor. +public let loudnessZwickerThresholdCoeff: Double = 0.025 + +/// `10^(0.1·(L−LTQ))` level-to-power exponent factor (dB → power decade). +public let loudnessLevelToPowerCoeff: Double = 0.1 + +/// Default Zwicker spectral-masking constant `s` for `.realtimeZwicker` (the +/// standard's fixed value). SC `Loudness` `smask` default. +public let loudnessDefaultSMask: Double = 0.25 + +/// Default temporal-mask release time (seconds) for `.realtimeZwicker`. +public let loudnessDefaultTMask: Double = 1.0 + +// MARK: - Third-octave band layout (ISO 532 B input grid) + +/// Number of third-octave bands (25 Hz … 12.5 kHz). +public let loudnessISOThirdOctaveCount: Int = 28 + +/// Third-octave band centre frequencies (Hz). +public let loudnessISOCenterFreqsHz: [Double] = [ + 25, 31.5, 40, 50, 63, 80, 100, 125, 160, 200, 250, 315, + 400, 500, 630, 800, 1000, 1250, 1600, 2000, 2500, 3150, + 4000, 5000, 6300, 8000, 10000, 12500 +] + +/// Number of Zwicker critical bands used by the core-loudness stage (the upper +/// 20 third-octave bands, with the lowest three formed from sub-band sums). +public let loudnessCriticalBandCount: Int = 20 + +/// Number of low third-octave bands (25 … 250 Hz) that get the `RAP`/`DLL` +/// equal-loudness correction before being combined into the first three +/// critical bands. +public let loudnessISOLowBandCount: Int = 11 + +// MARK: - ISO 532 B core-loudness tables +// Transcribed from the published DIN 45631 / Zwicker (1991) algorithm via the +// Apache-2.0 MoSQITo implementation. Data only — facts of the standard. + +/// Ranges of 1/3-octave band levels for low-frequency correction (dB). +public let loudnessISORAP: [Double] = [45, 55, 65, 71, 80, 90, 100, 120] + +/// Reduction of the lowest 11 1/3-octave band levels within the eight `RAP` +/// ranges (8 rows × 11 columns), per the equal-loudness contours. +public let loudnessISODLL: [[Double]] = [ + [-32, -24, -16, -10, -5, 0, -7, -3, 0, -2, 0], + [-29, -22, -15, -10, -4, 0, -7, -2, 0, -2, 0], + [-27, -19, -14, -9, -4, 0, -6, -2, 0, -2, 0], + [-25, -17, -12, -9, -3, 0, -5, -2, 0, -2, 0], + [-23, -16, -11, -7, -3, 0, -4, -1, 0, -1, 0], + [-20, -14, -10, -6, -3, 0, -4, -1, 0, -1, 0], + [-18, -12, -9, -6, -2, 0, -3, -1, 0, -1, 0], + [-15, -10, -8, -4, -2, 0, -3, -1, 0, -1, 0] +] + +/// Critical-band level at absolute threshold without the ear transfer (dB), per +/// the 20 critical bands. +public let loudnessISOLTQ: [Double] = [ + 30, 18, 12, 8, 7, 6, 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 +] + +/// Ear-transmission level correction (dB), per critical band. +public let loudnessISOA0: [Double] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.5, -1.6, -3.2, -5.4, -5.6, -4, -1.5, 2, 5, 12 +] + +/// Free-field → diffuse-field level difference (dB), per critical band. +public let loudnessISODDF: [Double] = [ + 0, 0, 0.5, 0.9, 1.2, 1.6, 2.3, 2.8, 3, 2, + 0, -1.4, -2, -1.9, -1, 0.5, 3, 4, 4.3, 4 +] + +/// Adaptation of 1/3-octave band levels to the critical-band level (dB). +public let loudnessISODCB: [Double] = [ + -0.25, -0.6, -0.8, -0.8, -0.5, 0, 0.5, 1.1, 1.5, 1.7, + 1.8, 1.8, 1.7, 1.6, 1.4, 1.2, 0.8, 0.5, 0, -0.5 +] + +/// Core-loudness correction `s` in the specific-loudness law. +public let loudnessISOCoreS: Double = 0.25 + +// MARK: - ISO 532 B upper-slope / integration tables + +/// Upper limits of the approximated critical bands in Bark (21 values). +public let loudnessISOZUP: [Double] = [ + 0.9, 1.8, 2.8, 3.5, 4.4, 5.4, 6.6, 7.9, 9.2, 10.6, 12.3, + 13.8, 15.2, 16.7, 18.1, 19.3, 20.6, 21.8, 22.7, 23.6, 24 +] + +/// Specific-loudness range thresholds for upper-slope steepness selection (18, +/// descending). +public let loudnessISORNS: [Double] = [ + 21.5, 18, 15.1, 11.5, 9, 6.1, 4.4, 3.1, 2.13, 1.36, + 0.82, 0.42, 0.30, 0.22, 0.15, 0.10, 0.035, 0 +] + +/// Steepness of the upper slopes (18 ranges × 8 critical-band columns). +public let loudnessISOUSL: [[Double]] = [ + [13, 8.2, 6.3, 5.5, 5.5, 5.5, 5.5, 5.5], + [9, 7.5, 6, 5.1, 4.5, 4.5, 4.5, 4.5], + [7.8, 6.7, 5.6, 4.9, 4.4, 3.9, 3.9, 3.9], + [6.2, 5.4, 4.6, 4.0, 3.5, 3.2, 3.2, 3.2], + [4.5, 3.8, 3.6, 3.2, 2.9, 2.7, 2.7, 2.7], + [3.7, 3.0, 2.8, 2.35, 2.2, 2.2, 2.2, 2.2], + [2.9, 2.3, 2.1, 1.9, 1.8, 1.7, 1.7, 1.7], + [2.4, 1.7, 1.5, 1.35, 1.3, 1.3, 1.3, 1.3], + [1.95, 1.45, 1.3, 1.15, 1.1, 1.1, 1.1, 1.1], + [1.5, 1.2, 0.94, 0.86, 0.82, 0.82, 0.82, 0.82], + [0.72, 0.67, 0.64, 0.63, 0.62, 0.62, 0.62, 0.62], + [0.59, 0.53, 0.51, 0.50, 0.42, 0.42, 0.42, 0.42], + [0.40, 0.33, 0.26, 0.24, 0.24, 0.22, 0.22, 0.22], + [0.27, 0.21, 0.20, 0.18, 0.17, 0.17, 0.17, 0.17], + [0.16, 0.15, 0.14, 0.12, 0.11, 0.11, 0.11, 0.11], + [0.12, 0.11, 0.10, 0.08, 0.08, 0.08, 0.08, 0.08], + [0.09, 0.08, 0.07, 0.06, 0.06, 0.06, 0.06, 0.05], + [0.06, 0.05, 0.03, 0.02, 0.02, 0.02, 0.02, 0.02] +] + +/// `korry` low-band threshold-dependence correction constants +/// (`0.4 + 0.32·N^0.2`). +public let loudnessKorryBase: Double = 0.4 +public let loudnessKorryScale: Double = 0.32 +public let loudnessKorryExponent: Double = 0.2 + +/// Maximum third-octave band level (dB) above which the Zwicker method is +/// undefined for the low bands; input is clamped to this. +public let loudnessMaxBandLevelDB: Double = 120.0 diff --git a/Sources/Lyrebird/Generators/Analysis/LoudnessField.swift b/Sources/Lyrebird/Generators/Analysis/LoudnessField.swift new file mode 100644 index 0000000..4f47175 --- /dev/null +++ b/Sources/Lyrebird/Generators/Analysis/LoudnessField.swift @@ -0,0 +1,16 @@ +// LoudnessField.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Sound-field assumption for the ISO 532 B loudness model +/// (``LoudnessModel/iso532b(field:)``). +public enum LoudnessField { + /// Free field (frontal incidence). Default. + case free + /// Diffuse field (applies the `DDF` free→diffuse corrections). + case diffuse +} diff --git a/Sources/Lyrebird/Generators/Analysis/LoudnessModel.swift b/Sources/Lyrebird/Generators/Analysis/LoudnessModel.swift new file mode 100644 index 0000000..900a1f9 --- /dev/null +++ b/Sources/Lyrebird/Generators/Analysis/LoudnessModel.swift @@ -0,0 +1,38 @@ +// LoudnessModel.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Selects the loudness-estimation model for ``Loudness`` (the implementation +/// flag, mirroring the `Balance` `logDomain:` and `BeatTrack` `BeatTrackODF` +/// folds). The cases carry different parameters, so the selector is an enum. +/// +/// All models output total loudness in **sones** from the same third-octave band +/// powers; they differ in how specific loudness is derived. +public enum LoudnessModel { + + /// Cheapest: third-octave band intensity → Stevens power law + /// (`N ∝ I^0.3`) → sum. No equal-loudness contour or masking. Rough but + /// stable; no SC parity claim. + case barkEstimate + + /// SC `Loudness` ergonomics: critical-band specific loudness via the Zwicker + /// law with a spectral-masking constant, summed, then temporally masked. + /// + /// - Parameters: + /// - smask: Spectral-masking constant `s` (`[0, 1]`); `0.25` is the + /// standard value. Higher widens masking. + /// - tmask: Temporal-mask release time (seconds); larger = slower decay, + /// more masking of transients. + case realtimeZwicker(smask: Double, tmask: Double) + + /// Full ISO 532 B / DIN 45631 stationary Zwicker loudness: third-octave core + /// loudness → upper-slope spreading → integrate the specific-loudness + /// function. + /// + /// - Parameter field: Sound-field assumption (`.free` default, `.diffuse`). + case iso532b(field: LoudnessField) +} diff --git a/Sources/Lyrebird/Generators/Analysis/RunningMax.swift b/Sources/Lyrebird/Generators/Analysis/RunningMax.swift new file mode 100644 index 0000000..f726974 --- /dev/null +++ b/Sources/Lyrebird/Generators/Analysis/RunningMax.swift @@ -0,0 +1,228 @@ +// RunningMax.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Accelerate + +/// File-scope zero-fill block for RunningMax — fallback when upstream returns no channel. +private let runningMaxZeroBlock: [Double] = [Double]( + repeating: 0, + count: lyrebirdDefaultResultBufferSize +) + +/// Running maximum with trigger reset. Equivalent to SuperCollider `RunningMax`. +/// +/// Tracks the running maximum of `input` since the last trigger. On a ≤0 → >0 rising +/// edge of `trig`, the extreme is reset to the current `input` value at that frame. +/// On the very first sample/block, the extreme is initialised to the first input value. +/// +/// ```swift +/// let peak = RunningMax.Audio(input: signal) +/// RunningMax.Audio(input: sig, trig: resetClock) // reset every clock pulse +/// RunningMax.Control(input: $cv, trig: gate) // block-rate maximum tracking +/// ``` +/// +/// - Parameters: +/// - input: Signal to track. Any `ValidGeneratorInput`. +/// - trig: Reset trigger. ≤0 → >0 rising edges reset the running maximum. Defaults to `0.0`. +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum RunningMax { + + // MARK: - Shared base + + /// Shared stored properties for `RunningMax.Audio` and `RunningMax.Control`. + public class _Base: GeneratorBase { + let _input: any ValidGeneratorInput + let _trigInput: any ValidGeneratorInput + let _mulAdd: MulAddSpec + + /// Running maximum. Initialised to the first input sample (lazy init via `_initialized`). + var _extreme: Double = 0.0 + /// Previous trigger value for edge detection. + var _prevTrig: Double = 0.0 + /// `false` until the first sample is processed; prevents a false start at `0.0`. + var _initialized: Bool = false + + init( + input: any ValidGeneratorInput, + trig: any ValidGeneratorInput, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + let resolvedTrig: any ValidGeneratorInput = trig._resolvedInput() + _input = resolvedInput + _trigInput = resolvedTrig + _mulAdd = MulAddSpec(mul: mul, add: add) + super.init() + } + } + + // MARK: - Audio rate + + /// Audio-rate running maximum with trigger reset. + /// + /// Evaluates per sample: lazy-initialises on the first sample; resets on rising trig + /// edge; otherwise tracks `max(_extreme, x)`. + /// + /// - Parameters: + /// - input: Signal to track. + /// - trig: Reset trigger. ≤0 → >0 rising edges reset to the current `input` value. + /// Defaults to `0.0` (no reset). + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - input: Signal to track. + /// - trig: Reset trigger. ≤0 → >0 edges reset the running maximum. Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + trig: any ValidGeneratorInput = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, trig: trig, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples( + graph: graph, count: count).first ?? runningMaxZeroBlock + let trigSamples: [Double] = _trigInput.calculatedSamples( + graph: graph, count: count).first ?? runningMaxZeroBlock + + var extreme: Double = _extreme + var prevTrig: Double = _prevTrig + var initialized: Bool = _initialized + + for i: Int in 0.. 0 && prevTrig <= 0 { + extreme = x + } else { + extreme = Swift.max(extreme, x) + } + prevTrig = t + _result[0][i] = extreme + } + + _extreme = extreme + _prevTrig = prevTrig + _initialized = initialized + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + return _result + } + } + + // MARK: - Control rate + + /// Block-rate running maximum with trigger reset. + /// + /// Scans the full audio-rate input block, applying the same state machine as `Audio` + /// (lazy init; trig-edge reset; `max` tracking). Outputs the block-final extreme as + /// a flat block (all samples equal). Bypasses the sub-block loop — the state machine + /// must scan the full audio block exactly once per audio cycle. + /// + /// - Parameters: + /// - input: Signal to track. + /// - trig: Reset trigger. ≤0 → >0 rising edges reset the running maximum. Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Control: _Base, ControlGenerator { + public var previousOutputValue: Double = 0.0 + + /// - Parameters: + /// - input: Signal to track. + /// - trig: Reset trigger. ≤0 → >0 edges reset the running maximum. Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + trig: any ValidGeneratorInput = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, trig: trig, mul: mul, add: add) + _setupSubBlockBuffer() + } + + /// Bypass sub-block loop: the running-maximum state machine must scan the full + /// audio-rate input block exactly once per audio block. + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples( + graph: graph, count: count).first ?? runningMaxZeroBlock + let trigSamples: [Double] = _trigInput.calculatedSamples( + graph: graph, count: count).first ?? runningMaxZeroBlock + + var extreme: Double = _extreme + var prevTrig: Double = _prevTrig + var initialized: Bool = _initialized + + for i: Int in 0.. 0 && prevTrig <= 0 { + extreme = x + } else { + extreme = Swift.max(extreme, x) + } + prevTrig = t + } + + _extreme = extreme + _prevTrig = prevTrig + _initialized = initialized + + var fillValue: Double = extreme + _result[0].withUnsafeMutableBufferPointer { buf in + guard let base: UnsafeMutablePointer = buf.baseAddress else { return } + vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count)) + } + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + + guard count > 0 else { return _result } + previousOutputValue = _result[0][count - 1] + return _result + } + + public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } + } +} + +// MARK: - GeneratorEnum + +extension RunningMax: GeneratorEnum { + public typealias AudioType = RunningMax.Audio + public typealias ControlType = RunningMax.Control +} diff --git a/Sources/Lyrebird/Generators/Analysis/RunningMin.swift b/Sources/Lyrebird/Generators/Analysis/RunningMin.swift new file mode 100644 index 0000000..f85bd02 --- /dev/null +++ b/Sources/Lyrebird/Generators/Analysis/RunningMin.swift @@ -0,0 +1,228 @@ +// RunningMin.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Accelerate + +/// File-scope zero-fill block for RunningMin — fallback when upstream returns no channel. +private let runningMinZeroBlock: [Double] = [Double]( + repeating: 0, + count: lyrebirdDefaultResultBufferSize +) + +/// Running minimum with trigger reset. Equivalent to SuperCollider `RunningMin`. +/// +/// Tracks the running minimum of `input` since the last trigger. On a ≤0 → >0 rising +/// edge of `trig`, the extreme is reset to the current `input` value at that frame. +/// On the very first sample/block, the extreme is initialised to the first input value. +/// +/// ```swift +/// let peak = RunningMin.Audio(input: signal) +/// RunningMin.Audio(input: sig, trig: resetClock) // reset every clock pulse +/// RunningMin.Control(input: $cv, trig: gate) // block-rate minimum tracking +/// ``` +/// +/// - Parameters: +/// - input: Signal to track. Any `ValidGeneratorInput`. +/// - trig: Reset trigger. ≤0 → >0 rising edges reset the running minimum. Defaults to `0.0`. +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum RunningMin { + + // MARK: - Shared base + + /// Shared stored properties for `RunningMin.Audio` and `RunningMin.Control`. + public class _Base: GeneratorBase { + let _input: any ValidGeneratorInput + let _trigInput: any ValidGeneratorInput + let _mulAdd: MulAddSpec + + /// Running minimum. Initialised to the first input sample (lazy init via `_initialized`). + var _extreme: Double = 0.0 + /// Previous trigger value for edge detection. + var _prevTrig: Double = 0.0 + /// `false` until the first sample is processed; prevents a false start at `0.0`. + var _initialized: Bool = false + + init( + input: any ValidGeneratorInput, + trig: any ValidGeneratorInput, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + let resolvedTrig: any ValidGeneratorInput = trig._resolvedInput() + _input = resolvedInput + _trigInput = resolvedTrig + _mulAdd = MulAddSpec(mul: mul, add: add) + super.init() + } + } + + // MARK: - Audio rate + + /// Audio-rate running minimum with trigger reset. + /// + /// Evaluates per sample: lazy-initialises on the first sample; resets on rising trig + /// edge; otherwise tracks `min(_extreme, x)`. + /// + /// - Parameters: + /// - input: Signal to track. + /// - trig: Reset trigger. ≤0 → >0 rising edges reset to the current `input` value. + /// Defaults to `0.0` (no reset). + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - input: Signal to track. + /// - trig: Reset trigger. ≤0 → >0 edges reset the running minimum. Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + trig: any ValidGeneratorInput = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, trig: trig, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples( + graph: graph, count: count).first ?? runningMinZeroBlock + let trigSamples: [Double] = _trigInput.calculatedSamples( + graph: graph, count: count).first ?? runningMinZeroBlock + + var extreme: Double = _extreme + var prevTrig: Double = _prevTrig + var initialized: Bool = _initialized + + for i: Int in 0.. 0 && prevTrig <= 0 { + extreme = x + } else { + extreme = Swift.min(extreme, x) + } + prevTrig = t + _result[0][i] = extreme + } + + _extreme = extreme + _prevTrig = prevTrig + _initialized = initialized + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + return _result + } + } + + // MARK: - Control rate + + /// Block-rate running minimum with trigger reset. + /// + /// Scans the full audio-rate input block, applying the same state machine as `Audio` + /// (lazy init; trig-edge reset; `min` tracking). Outputs the block-final extreme as + /// a flat block (all samples equal). Bypasses the sub-block loop — the state machine + /// must scan the full audio block exactly once per audio cycle. + /// + /// - Parameters: + /// - input: Signal to track. + /// - trig: Reset trigger. ≤0 → >0 rising edges reset the running minimum. Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Control: _Base, ControlGenerator { + public var previousOutputValue: Double = 0.0 + + /// - Parameters: + /// - input: Signal to track. + /// - trig: Reset trigger. ≤0 → >0 edges reset the running minimum. Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + trig: any ValidGeneratorInput = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, trig: trig, mul: mul, add: add) + _setupSubBlockBuffer() + } + + /// Bypass sub-block loop: the running-minimum state machine must scan the full + /// audio-rate input block exactly once per audio block. + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples( + graph: graph, count: count).first ?? runningMinZeroBlock + let trigSamples: [Double] = _trigInput.calculatedSamples( + graph: graph, count: count).first ?? runningMinZeroBlock + + var extreme: Double = _extreme + var prevTrig: Double = _prevTrig + var initialized: Bool = _initialized + + for i: Int in 0.. 0 && prevTrig <= 0 { + extreme = x + } else { + extreme = Swift.min(extreme, x) + } + prevTrig = t + } + + _extreme = extreme + _prevTrig = prevTrig + _initialized = initialized + + var fillValue: Double = extreme + _result[0].withUnsafeMutableBufferPointer { buf in + guard let base: UnsafeMutablePointer = buf.baseAddress else { return } + vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count)) + } + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + + guard count > 0 else { return _result } + previousOutputValue = _result[0][count - 1] + return _result + } + + public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } + } +} + +// MARK: - GeneratorEnum + +extension RunningMin: GeneratorEnum { + public typealias AudioType = RunningMin.Audio + public typealias ControlType = RunningMin.Control +} diff --git a/Sources/Lyrebird/Generators/Analysis/Slope.swift b/Sources/Lyrebird/Generators/Analysis/Slope.swift new file mode 100644 index 0000000..d1f677a --- /dev/null +++ b/Sources/Lyrebird/Generators/Analysis/Slope.swift @@ -0,0 +1,203 @@ +// Slope.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Accelerate + +/// File-scope zero-fill block for Slope — fallback when upstream returns no channel. +private let slopeZeroBlock: [Double] = [Double]( + repeating: 0, + count: lyrebirdDefaultResultBufferSize +) + +/// Per-second rate-of-change estimator. Equivalent to SuperCollider `Slope`. +/// +/// Computes `out[n] = (input[n] − input[n−1]) × sampleRate` (audio rate) or +/// `out = (input − prevInput) × controlRate` (control rate). On the very first +/// sample/block, the output is `0.0` and `prevInput` is initialised to the first input +/// value — this prevents the startup spike that would occur if `prevInput` were `0`. +/// +/// ```swift +/// let rate = Slope.Audio(input: envelope) // audio-rate differentiation +/// let rate = Slope.Control(input: $cv) // block-rate differentiation +/// ``` +/// +/// - Parameters: +/// - input: Signal to differentiate. +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum Slope { + + // MARK: - Shared base + + /// Shared stored properties for `Slope.Audio` and `Slope.Control`. + public class _Base: GeneratorBase { + let _input: any ValidGeneratorInput + let _inputIsGenerator: Bool + let _mulAdd: MulAddSpec + + /// Previous sample value. Initialised on the first call (lazy init). + var _prevSample: Double = 0.0 + /// `false` until the first sample/block is processed; avoids the startup spike. + var _initialized: Bool = false + + init( + input: any ValidGeneratorInput, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + _input = resolvedInput + _inputIsGenerator = resolvedInput is any Generator + _mulAdd = MulAddSpec(mul: mul, add: add) + super.init() + } + } + + // MARK: - Audio rate + + /// Audio-rate per-second rate-of-change estimator. + /// + /// On the first sample, the output is `0.0` and `prevSample` is set to that sample's + /// value. From the second sample onward, `out[n] = (x[n] − x[n−1]) × sampleRate`. + /// + /// - Parameters: + /// - input: Signal to differentiate. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - input: Signal to differentiate. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples( + graph: graph, count: count).first ?? slopeZeroBlock + let sr: Double = graph.engine.sampleRate + + var prev: Double = _prevSample + var initialized: Bool = _initialized + + for i: Int in 0.. [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let controlRate: Double = graph.engine.sampleRate / Double(graph.engine.blockSize) + // Sample the input at block end (captures ParameterNode ramp endpoints), + // matching the block-constant-input convention of other control-rate generators. + let x: Double = lastGeneratorSampleOrFloat( + _input, isGenerator: _inputIsGenerator, graph: graph, count: count) + + let slope: Double + if !_initialized { + _prevSample = x + _initialized = true + slope = 0.0 + } else { + slope = (x - _prevSample) * controlRate + _prevSample = x + } + + var fillValue: Double = slope + _result[0].withUnsafeMutableBufferPointer { buf in + guard let base: UnsafeMutablePointer = buf.baseAddress else { return } + vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count)) + } + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + + guard count > 0 else { return _result } + previousOutputValue = _result[0][count - 1] + return _result + } + + public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } + } +} + +// MARK: - GeneratorEnum + +extension Slope: GeneratorEnum { + public typealias AudioType = Slope.Audio + public typealias ControlType = Slope.Control +} diff --git a/Sources/Lyrebird/Generators/Analysis/ZeroCrossing.swift b/Sources/Lyrebird/Generators/Analysis/ZeroCrossing.swift new file mode 100644 index 0000000..bc66b6b --- /dev/null +++ b/Sources/Lyrebird/Generators/Analysis/ZeroCrossing.swift @@ -0,0 +1,241 @@ +// ZeroCrossing.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Accelerate + +/// File-scope zero-fill block for ZeroCrossing — fallback when upstream returns no channel. +private let zeroCrossingZeroBlock: [Double] = [Double]( + repeating: 0, + count: lyrebirdDefaultResultBufferSize +) + +/// Minimum sample count between crossings required before a zero crossing is recognised. +/// Mirrors SuperCollider `ZeroCrossing_Ctor` guard (`counter > 4`) — rejects spurious +/// high-frequency noise crossings. A crossing is only recorded when the inter-crossing +/// sample count exceeds this threshold. +private let zeroCrossingMinCount: Int = 4 + +/// Zero-crossing frequency estimator. Equivalent to SuperCollider `ZeroCrossing`. +/// +/// Counts samples between successive rising zero crossings (≤0 → >0 edges) and computes a +/// frequency estimate as `sampleRate / sampleCount`. The estimate is held between crossings +/// and starts at `0.0` until the first full period is measured. +/// +/// `_prevSample` is lazy-initialised to the first input sample on the very first call, +/// matching SuperCollider's `ZeroCrossing_Ctor` (`m_previn = ZIN0(0)`). As a result, +/// a constant positive (DC) input produces no crossing and the output remains `0.0`. +/// Crossings require more than `zeroCrossingMinCount` (4) samples of inter-crossing +/// spacing — spurious noise crossings are rejected. +/// +/// ```swift +/// // Estimate the frequency of an input signal. +/// let freq = ZeroCrossing.Audio(input: OscSin.Audio(freq: 440.0)) +/// ZeroCrossing.Control(input: audioRateInput) // block-rate measurement +/// ``` +/// +/// - Parameters: +/// - input: Signal to analyse. Can be any `ValidGeneratorInput`. +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum ZeroCrossing { + + // MARK: - Shared base + + /// Shared stored properties for `ZeroCrossing.Audio` and `ZeroCrossing.Control`. + public class _Base: GeneratorBase { + let _input: any ValidGeneratorInput + let _mulAdd: MulAddSpec + + /// Sample value from the previous `_computeSamples` call. Lazy-initialised to the + /// first input sample on first use; not meaningful before that point. + var _prevSample: Double = 0.0 + /// Samples elapsed since the last rising zero crossing. + var _count: Int = 0 + /// Most recently measured frequency estimate, held until the next crossing. + var _freq: Double = 0.0 + /// `false` until the very first sample is processed; guards lazy-init of `_prevSample`. + var _initialized: Bool = false + + init( + input: any ValidGeneratorInput, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + _input = resolvedInput + _mulAdd = MulAddSpec(mul: mul, add: add) + super.init() + } + } + + // MARK: - Audio rate + + /// Audio-rate zero-crossing frequency estimator. + /// + /// Computes a per-sample frequency estimate from rising zero-crossing spacing. + /// The estimate is held between crossings. `_prevSample` is lazy-initialised to + /// the first input sample; constant DC input yields `0.0`. Crossings require more + /// than `zeroCrossingMinCount` (4) samples of spacing. + /// + /// - Parameters: + /// - input: Signal to analyse. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - input: Signal to analyse. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples( + graph: graph, count: count).first ?? zeroCrossingZeroBlock + let sr: Double = graph.engine.sampleRate + + var prevSample: Double = _prevSample + var xingCount: Int = _count + var freq: Double = _freq + var initialized: Bool = _initialized + + for i: Int in 0.. zeroCrossingMinCount && prevSample <= 0 && x > 0 { + freq = sr / Double(xingCount) + xingCount = 0 + } + prevSample = x + _result[0][i] = freq + } + + _prevSample = prevSample + _count = xingCount + _freq = freq + _initialized = initialized + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + return _result + } + } + + // MARK: - Control rate + + /// Block-rate zero-crossing frequency estimator. + /// + /// Scans the full audio-rate input block running the same state machine as `Audio`; + /// outputs the block-final frequency estimate as a flat block. The estimate is held + /// between crossings and starts at `0.0` until the first period is measured. + /// + /// `_prevSample` is lazy-initialised to the first input sample; constant DC input + /// yields `0.0`. Crossings require more than `zeroCrossingMinCount` (4) samples of + /// spacing, matching SuperCollider behaviour. + /// + /// Bypasses the sub-block loop — the state machine must scan the full audio block + /// exactly once per audio cycle to avoid double-advancing the crossing counter. + /// + /// - Parameters: + /// - input: Signal to analyse. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Control: _Base, ControlGenerator { + public var previousOutputValue: Double = 0.0 + + /// - Parameters: + /// - input: Signal to analyse. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, mul: mul, add: add) + _setupSubBlockBuffer() + } + + /// Bypass sub-block loop: the zero-crossing state machine must scan the full + /// audio-rate input block exactly once per audio block. + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples( + graph: graph, count: count).first ?? zeroCrossingZeroBlock + let sr: Double = graph.engine.sampleRate + + var prevSample: Double = _prevSample + var xingCount: Int = _count + var freq: Double = _freq + var initialized: Bool = _initialized + + for i: Int in 0.. zeroCrossingMinCount && prevSample <= 0 && x > 0 { + freq = sr / Double(xingCount) + xingCount = 0 + } + prevSample = x + } + + _prevSample = prevSample + _count = xingCount + _freq = freq + _initialized = initialized + + var fillValue: Double = freq + _result[0].withUnsafeMutableBufferPointer { buf in + guard let base: UnsafeMutablePointer = buf.baseAddress else { return } + vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count)) + } + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + + guard count > 0 else { return _result } + previousOutputValue = _result[0][count - 1] + return _result + } + + public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } + } +} + +// MARK: - GeneratorEnum + +extension ZeroCrossing: GeneratorEnum { + public typealias AudioType = ZeroCrossing.Audio + public typealias ControlType = ZeroCrossing.Control +} diff --git a/Sources/Lyrebird/Generators/BufferIO/PlayBuffer.swift b/Sources/Lyrebird/Generators/BufferIO/PlayBuffer.swift index 6e10fe5..acd3799 100644 --- a/Sources/Lyrebird/Generators/BufferIO/PlayBuffer.swift +++ b/Sources/Lyrebird/Generators/BufferIO/PlayBuffer.swift @@ -59,17 +59,11 @@ internal func lyrebirdBufferRead( case .cubic: let intPhase: Int = Int(phase.rounded(.down)) let t: Double = phase - Double(intPhase) - let t2: Double = t * t - let t3: Double = t2 * t let pM1: Double = frame(intPhase - 1) let p0: Double = frame(intPhase) let p1: Double = frame(intPhase + 1) let p2: Double = frame(intPhase + 2) - let catmullRomHalf: Double = 0.5 - return catmullRomHalf * ((2 * p0) - + (-pM1 + p1) * t - + (2 * pM1 - 5 * p0 + 4 * p1 - p2) * t2 - + (-pM1 + 3 * p0 - 3 * p1 + p2) * t3) + return catmullRomCubic(pM1, p0, p1, p2, t: t) } } diff --git a/Sources/Lyrebird/Generators/Chaotic/ChaoticBase.swift b/Sources/Lyrebird/Generators/Chaotic/ChaoticBase.swift new file mode 100644 index 0000000..2bfb9c4 --- /dev/null +++ b/Sources/Lyrebird/Generators/Chaotic/ChaoticBase.swift @@ -0,0 +1,105 @@ +// ChaoticBase.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Shared base for strange-attractor / chaotic-map oscillators. +/// +/// A chaotic oscillator iterates a discrete map (Lorenz, Hénon, …) at a chosen +/// `freq` (iterations per second), **not** once per audio sample. Between +/// successive iterations the audio output bridges the two map values according to +/// `interpolation`: +/// +/// - `.none` — hold the current iteration value until the next (hard, aliased). +/// - `.linear` — straight-line ramp between successive iterations. +/// - `.cubic` — 4-point cubic across the surrounding iterations (smoothest). +/// +/// Same shape as `NoiseBase`: the base owns the cross-rate shared state +/// (`_freqInput`, `_mulAdd`, `_interpolation`, the 4-value history ring, and the +/// sub-iteration phase accumulator). Concrete per-map `_Base` subclasses add the +/// map's own variables and the `iterate()` recurrence; `Audio` / `Control` +/// variants inherit that subclass. +/// +/// `freq` and the map parameters are read once per block (`floatValue`) — chaotic +/// oscillators do not support per-sample audio-rate parameter modulation. +public class ChaoticBase: GeneratorBase { + let _freqInput: any ValidGeneratorInput + var _mulAdd: MulAddSpec + let _interpolation: TableInterpolation + + /// History ring around the current `[_h0, _h1]` segment: + /// `_hM1` = one iteration before the segment start, `_h2` = one after the end. + /// `.none` reads `_h0`, `.linear` lerps `_h0…_h1`, `.cubic` uses all four. + var _hM1: Double = 0.0 + var _h0: Double = 0.0 + var _h1: Double = 0.0 + var _h2: Double = 0.0 + + /// Fraction `[0, 1)` through the current iteration segment. + var _phase: Double = 0.0 + + /// Lazy one-shot history priming guard (the concrete map seeds its variables + /// at `init`, then the first `_computeSamples` fills the ring via `iterate()`). + var _seeded: Bool = false + + init( + freq: any ValidGeneratorInput, + interpolation: TableInterpolation, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput() + self._freqInput = resolvedFreq + self._interpolation = interpolation + self._mulAdd = MulAddSpec(mul: mul, add: add) + super.init() + } + + /// Advance the map one iteration and return its new output value. + /// + /// Overridden by every concrete map `_Base`. The base implementation returns + /// `0` — a missing override would silence the oscillator rather than trap on + /// the RT thread. + func iterate() -> Double { 0.0 } + + /// Fill the history ring on first use: four warm-up iterations seed + /// `_hM1, _h0, _h1, _h2` so the cubic kernel has real neighbours and the + /// transient settles onto the attractor before audio is taken. + @inline(__always) + func primeIfNeeded() { + if _seeded { return } + _hM1 = iterate() + _h0 = iterate() + _h1 = iterate() + _h2 = iterate() + _phase = 0.0 + _seeded = true + } + + /// Per-sample phase increment for `freq`, clamped to `[0, chaoticMaxStepRate]`. + /// + /// Negative `freq` holds (returns `0`) rather than driving `_phase` negative — + /// the map has no backward iteration. The upper clamp bounds the `advancePhase` + /// loop so an extreme `freq` cannot stall the RT thread. + @inline(__always) + func stepRate(freq: Double, sampleRate: Double) -> Double { + let raw: Double = freq / sampleRate + if raw <= 0 { return 0.0 } + return min(raw, chaoticMaxStepRate) + } + + /// Advance the sub-iteration phase by `dphase`, performing as many `iterate()` + /// steps as the phase crosses (shifting the history ring forward each time). + @inline(__always) + func advancePhase(by dphase: Double) { + _phase += dphase + while _phase >= 1.0 { + _phase -= 1.0 + _hM1 = _h0 + _h0 = _h1 + _h1 = _h2 + _h2 = iterate() + } + } +} diff --git a/Sources/Lyrebird/Generators/Chaotic/ChaoticHelpers.swift b/Sources/Lyrebird/Generators/Chaotic/ChaoticHelpers.swift new file mode 100644 index 0000000..3021f0b --- /dev/null +++ b/Sources/Lyrebird/Generators/Chaotic/ChaoticHelpers.swift @@ -0,0 +1,46 @@ +// ChaoticHelpers.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Default iteration frequency (Hz) for the chaotic oscillators — one iteration +/// every other sample at 44.1 kHz, matching the SuperCollider chaotic-UGen +/// defaults. `@usableFromInline` so it can back the public `init` default args. +@usableFromInline +internal let chaoticDefaultFrequency: Double = 22050.0 + +/// Upper bound on map iterations per output sample. Caps the `advancePhase` +/// `while` loop so a pathological caller-supplied `freq` (e.g. `freq ≫ sampleRate`) +/// cannot do unbounded work on the RT thread. +internal let chaoticMaxStepRate: Double = 64.0 + +/// Wrap a phase/angle into `[0, 2π)`. Used by the angle-state chaotic maps +/// (`StandardN`, `FBSineN`) to keep their unbounded accumulators bounded. +@inline(__always) +internal func chaoticWrapTwoPi(_ v: Double) -> Double { + v - lyrebirdTwoPi * (v / lyrebirdTwoPi).rounded(.down) +} + +// MARK: - Interpolation kernel + +/// Bridge between successive chaotic-map iterations for the current segment. +/// +/// `t ∈ [0, 1)` is the fraction through the `[h0, h1]` segment; `hM1` / `h2` are +/// the surrounding iterations used only by the cubic kernel, which delegates to +/// the shared `catmullRomCubic` spline. +@inline(__always) +internal func chaoticInterpolate( + _ interpolation: TableInterpolation, + phase t: Double, + hM1: Double, h0: Double, h1: Double, h2: Double +) -> Double { + switch interpolation { + case .none: + return h0 + case .linear: + return h0 + t * (h1 - h0) + case .cubic: + return catmullRomCubic(hM1, h0, h1, h2, t: t) + } +} diff --git a/Sources/Lyrebird/Generators/Chaotic/CuspStepped.swift b/Sources/Lyrebird/Generators/Chaotic/CuspStepped.swift new file mode 100644 index 0000000..83d71f5 --- /dev/null +++ b/Sources/Lyrebird/Generators/Chaotic/CuspStepped.swift @@ -0,0 +1,192 @@ +// CuspStepped.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Cusp-map oscillator (non-interpolated by default). +/// +/// Iterates the cusp map at `freq` Hz: +/// ``` +/// x[n+1] = a − b · √|x[n]| +/// ``` +/// and outputs `x`. With the canonical `a = 1`, `b = 1.9` the orbit is chaotic and +/// bounded to roughly `[-0.9, 1.0]`. Iterations bridge per `interpolation` +/// (default `.none`). +/// +/// `freq`, `a`, and `b` are read once per block. See ``ChaoticBase`` for the +/// iteration / interpolation model. +public enum CuspStepped { + + // MARK: - _Base + + /// Shared cusp-map state + parameters for `Audio` and `Control`. + public class _Base: ChaoticBase { + let aInput: any ValidGeneratorInput + let bInput: any ValidGeneratorInput + + // Map state. + var x: Double + + // Per-block parameter snapshot read by `iterate()`. + var _a: Double = 0.0 + var _b: Double = 0.0 + + init( + freq: any ValidGeneratorInput, + a: any ValidGeneratorInput, + b: any ValidGeneratorInput, + xi: Double, + interpolation: TableInterpolation, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + self.aInput = a._resolvedInput() + self.bInput = b._resolvedInput() + self.x = xi + super.init(freq: freq, interpolation: interpolation, mul: mul, add: add) + } + + override func iterate() -> Double { + let xNew: Double = _a - _b * (abs(x)).squareRoot() + x = xNew + return xNew + } + + /// Snapshot the per-block parameters into the fields `iterate()` reads. + @inline(__always) + func readParams(graph: SynthGraph) { + _a = aInput.floatValue(graph: graph) + _b = bInput.floatValue(graph: graph) + } + } + + // MARK: - Audio + + /// Audio-rate cusp-map oscillator. + /// + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: Offset term. Defaults to `1`. No clamping; some `(a,b)` pairs diverge. + /// - b: Square-root coefficient. Defaults to `1.9`. + /// - xi: Initial `x`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: Offset term. Defaults to `1`. No clamping; some `(a,b)` pairs diverge. + /// - b: Square-root coefficient. Defaults to `1.9`. + /// - xi: Initial `x`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + a: any ValidGeneratorInput = 1.0, + b: any ValidGeneratorInput = 1.9, + xi: Double = 0.0, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, a: a, b: b, xi: xi, + interpolation: interpolation, mul: mul, add: add) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + + for i: Int in 0.. Double { previousOutputValue } + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: Offset term. Defaults to `1`. No clamping; some `(a,b)` pairs diverge. + /// - b: Square-root coefficient. Defaults to `1.9`. + /// - xi: Initial `x`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + a: any ValidGeneratorInput = 1.0, + b: any ValidGeneratorInput = 1.9, + xi: Double = 0.0, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, a: a, b: b, xi: xi, + interpolation: interpolation, mul: mul, add: add) + _setupSubBlockBuffer() + } + + // Bypass sub-block loop: the map advances exactly one audio block per call. + public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + advancePhase(by: dphase * Double(count)) + let target: Double = chaoticInterpolate(_interpolation, phase: _phase, + hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) + + let rampStart: Double = _rampTarget + _rampTarget = target + previousOutputValue = fillRampedResult( + into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) + return _result + } + } +} + +// MARK: - GeneratorEnum + +extension CuspStepped: GeneratorEnum { + public typealias AudioType = CuspStepped.Audio + public typealias ControlType = CuspStepped.Control +} diff --git a/Sources/Lyrebird/Generators/Chaotic/FBSineStepped.swift b/Sources/Lyrebird/Generators/Chaotic/FBSineStepped.swift new file mode 100644 index 0000000..1b45372 --- /dev/null +++ b/Sources/Lyrebird/Generators/Chaotic/FBSineStepped.swift @@ -0,0 +1,226 @@ +// FBSineStepped.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Feedback-sine-map oscillator (non-interpolated by default). +/// +/// Iterates a feedback sine map at `freq` Hz, with the phase accumulator `y` +/// wrapped into `[0, 2π)`: +/// ``` +/// x[n+1] = sin(im · y[n] + fb · x[n]) +/// y[n+1] = (a · y[n] + c) mod 2π +/// ``` +/// and outputs `x` (range `[-1, 1]` — the output is a sine). With the canonical +/// `im = 1`, `fb = 0.1`, `a = 1.1`, `c = 0.5` the orbit is chaotic. Iterations +/// bridge per `interpolation` (default `.none`). +/// +/// `freq`, `im`, `fb`, `a`, and `c` are read once per block. See ``ChaoticBase`` +/// for the iteration / interpolation model. +public enum FBSineStepped { + + // MARK: - _Base + + /// Shared feedback-sine state + parameters for `Audio` and `Control`. + public class _Base: ChaoticBase { + let imInput: any ValidGeneratorInput + let fbInput: any ValidGeneratorInput + let aInput: any ValidGeneratorInput + let cInput: any ValidGeneratorInput + + // Map state. + var x: Double + var y: Double + + // Per-block parameter snapshot read by `iterate()`. + var _im: Double = 0.0 + var _fb: Double = 0.0 + var _a: Double = 0.0 + var _c: Double = 0.0 + + init( + freq: any ValidGeneratorInput, + im: any ValidGeneratorInput, + fb: any ValidGeneratorInput, + a: any ValidGeneratorInput, + c: any ValidGeneratorInput, + xi: Double, + yi: Double, + interpolation: TableInterpolation, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + self.imInput = im._resolvedInput() + self.fbInput = fb._resolvedInput() + self.aInput = a._resolvedInput() + self.cInput = c._resolvedInput() + self.x = xi + self.y = yi + super.init(freq: freq, interpolation: interpolation, mul: mul, add: add) + } + + override func iterate() -> Double { + let xNew: Double = sin(_im * y + _fb * x) + y = chaoticWrapTwoPi(_a * y + _c) + x = xNew + return xNew + } + + /// Snapshot the per-block parameters into the fields `iterate()` reads. + @inline(__always) + func readParams(graph: SynthGraph) { + _im = imInput.floatValue(graph: graph) + _fb = fbInput.floatValue(graph: graph) + _a = aInput.floatValue(graph: graph) + _c = cInput.floatValue(graph: graph) + } + } + + // MARK: - Audio + + /// Audio-rate feedback-sine oscillator. + /// + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - im: Phase index multiplier. Defaults to `1`. + /// - fb: Feedback amount. Defaults to `0.1`. + /// - a: Phase-accumulator multiplier. Defaults to `1.1`. + /// - c: Phase-accumulator increment. Defaults to `0.5`. + /// - xi: Initial `x`. Defaults to `0.1`. + /// - yi: Initial `y` (phase). Defaults to `0.1`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - im: Phase index multiplier. Defaults to `1`. + /// - fb: Feedback amount. Defaults to `0.1`. + /// - a: Phase-accumulator multiplier. Defaults to `1.1`. + /// - c: Phase-accumulator increment. Defaults to `0.5`. + /// - xi: Initial `x`. Defaults to `0.1`. + /// - yi: Initial `y` (phase). Defaults to `0.1`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + im: any ValidGeneratorInput = 1.0, + fb: any ValidGeneratorInput = 0.1, + a: any ValidGeneratorInput = 1.1, + c: any ValidGeneratorInput = 0.5, + xi: Double = 0.1, + yi: Double = 0.1, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, im: im, fb: fb, a: a, c: c, xi: xi, yi: yi, + interpolation: interpolation, mul: mul, add: add) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + + for i: Int in 0.. Double { previousOutputValue } + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - im: Phase index multiplier. Defaults to `1`. + /// - fb: Feedback amount. Defaults to `0.1`. + /// - a: Phase-accumulator multiplier. Defaults to `1.1`. + /// - c: Phase-accumulator increment. Defaults to `0.5`. + /// - xi: Initial `x`. Defaults to `0.1`. + /// - yi: Initial `y` (phase). Defaults to `0.1`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + im: any ValidGeneratorInput = 1.0, + fb: any ValidGeneratorInput = 0.1, + a: any ValidGeneratorInput = 1.1, + c: any ValidGeneratorInput = 0.5, + xi: Double = 0.1, + yi: Double = 0.1, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, im: im, fb: fb, a: a, c: c, xi: xi, yi: yi, + interpolation: interpolation, mul: mul, add: add) + _setupSubBlockBuffer() + } + + // Bypass sub-block loop: the map advances exactly one audio block per call. + public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + advancePhase(by: dphase * Double(count)) + let target: Double = chaoticInterpolate(_interpolation, phase: _phase, + hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) + + let rampStart: Double = _rampTarget + _rampTarget = target + previousOutputValue = fillRampedResult( + into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) + return _result + } + } +} + +// MARK: - GeneratorEnum + +extension FBSineStepped: GeneratorEnum { + public typealias AudioType = FBSineStepped.Audio + public typealias ControlType = FBSineStepped.Control +} diff --git a/Sources/Lyrebird/Generators/Chaotic/GbmanStepped.swift b/Sources/Lyrebird/Generators/Chaotic/GbmanStepped.swift new file mode 100644 index 0000000..beeab09 --- /dev/null +++ b/Sources/Lyrebird/Generators/Chaotic/GbmanStepped.swift @@ -0,0 +1,170 @@ +// GbmanStepped.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Gingerbreadman-map oscillator (non-interpolated / stepped by default). +/// +/// Iterates the Gingerbreadman recurrence at `freq` Hz: +/// ``` +/// x[n+1] = 1 − y[n] + |x[n]| +/// y[n+1] = x[n] +/// ``` +/// and outputs `x`. The orbit is chaotic and bounded (roughly `|x| < 8`). It has +/// no shape parameters — only the initial conditions `xi` / `yi`. Iterations bridge +/// per `interpolation` (default `.none` — held / stepped, the aliased SC `GbmanN` +/// character). +/// +/// `freq` is read once per block (no per-sample audio-rate modulation). See +/// ``ChaoticBase`` for the iteration / interpolation model. +public enum GbmanStepped { + + // MARK: - _Base + + /// Shared Gingerbreadman state for `Audio` and `Control`. + public class _Base: ChaoticBase { + // Map state: x[n] and y[n]. + var x: Double + var y: Double + + init( + freq: any ValidGeneratorInput, + xi: Double, + yi: Double, + interpolation: TableInterpolation, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + self.x = xi + self.y = yi + super.init(freq: freq, interpolation: interpolation, mul: mul, add: add) + } + + override func iterate() -> Double { + let xNew: Double = 1.0 - y + abs(x) + y = x + x = xNew + return xNew + } + } + + // MARK: - Audio + + /// Audio-rate Gingerbreadman oscillator. + /// + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - xi: Initial `x`. Defaults to `1.2`. + /// - yi: Initial `y`. Defaults to `2.1`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - xi: Initial `x`. Defaults to `1.2`. + /// - yi: Initial `y`. Defaults to `2.1`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + xi: Double = 1.2, + yi: Double = 2.1, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, xi: xi, yi: yi, + interpolation: interpolation, mul: mul, add: add) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + + for i: Int in 0.. Double { previousOutputValue } + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - xi: Initial `x`. Defaults to `1.2`. + /// - yi: Initial `y`. Defaults to `2.1`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + xi: Double = 1.2, + yi: Double = 2.1, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, xi: xi, yi: yi, + interpolation: interpolation, mul: mul, add: add) + _setupSubBlockBuffer() + } + + // Bypass sub-block loop: the map advances exactly one audio block per call. + public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + advancePhase(by: dphase * Double(count)) + let target: Double = chaoticInterpolate(_interpolation, phase: _phase, + hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) + + let rampStart: Double = _rampTarget + _rampTarget = target + previousOutputValue = fillRampedResult( + into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) + return _result + } + } +} + +// MARK: - GeneratorEnum + +extension GbmanStepped: GeneratorEnum { + public typealias AudioType = GbmanStepped.Audio + public typealias ControlType = GbmanStepped.Control +} diff --git a/Sources/Lyrebird/Generators/Chaotic/HenonStepped.swift b/Sources/Lyrebird/Generators/Chaotic/HenonStepped.swift new file mode 100644 index 0000000..ca23922 --- /dev/null +++ b/Sources/Lyrebird/Generators/Chaotic/HenonStepped.swift @@ -0,0 +1,200 @@ +// HenonStepped.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Hénon-map oscillator (non-interpolated / stepped by default). +/// +/// Iterates the Hénon recurrence at `freq` Hz: +/// ``` +/// x[n+1] = 1 − a · x[n]² + b · x[n−1] +/// ``` +/// and outputs `x`. With the canonical `a = 1.4`, `b = 0.3` the orbit is chaotic +/// and bounded to roughly `[-1.5, 1.5]`. Iterations bridge per `interpolation` +/// (default `.none` — held / stepped, the aliased SC `HenonN` character). +/// +/// `freq`, `a`, and `b` are read once per block (no per-sample audio-rate +/// modulation). See ``ChaoticBase`` for the iteration / interpolation model. +public enum HenonStepped { + + // MARK: - _Base + + /// Shared Hénon state + parameters for `Audio` and `Control`. + public class _Base: ChaoticBase { + let aInput: any ValidGeneratorInput + let bInput: any ValidGeneratorInput + + // Map state: x[n] and x[n-1]. + var xn: Double + var xnm1: Double + + // Per-block parameter snapshot read by `iterate()`. + var _a: Double = 0.0 + var _b: Double = 0.0 + + init( + freq: any ValidGeneratorInput, + a: any ValidGeneratorInput, + b: any ValidGeneratorInput, + x0: Double, + x1: Double, + interpolation: TableInterpolation, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + self.aInput = a._resolvedInput() + self.bInput = b._resolvedInput() + self.xnm1 = x0 + self.xn = x1 + super.init(freq: freq, interpolation: interpolation, mul: mul, add: add) + } + + override func iterate() -> Double { + let xNew: Double = 1.0 - _a * xn * xn + _b * xnm1 + xnm1 = xn + xn = xNew + return xNew + } + + /// Snapshot the per-block parameters into the fields `iterate()` reads. + @inline(__always) + func readParams(graph: SynthGraph) { + _a = aInput.floatValue(graph: graph) + _b = bInput.floatValue(graph: graph) + } + } + + // MARK: - Audio + + /// Audio-rate Hénon oscillator. + /// + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: Quadratic coefficient. Defaults to `1.4` (canonical chaotic value). No clamping; the orbit diverges for `a ≳ 1.42`. + /// - b: Linear feedback coefficient. Defaults to `0.3`. No clamping; bounded near `|b| < 1`, classic value `0.3`. + /// - x0: Initial `x[n−1]`. Defaults to `0`. + /// - x1: Initial `x[n]`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: Quadratic coefficient. Defaults to `1.4`. No clamping; the orbit diverges for `a ≳ 1.42`. + /// - b: Linear feedback coefficient. Defaults to `0.3`. No clamping; bounded near `|b| < 1`, classic value `0.3`. + /// - x0: Initial `x[n−1]`. Defaults to `0`. + /// - x1: Initial `x[n]`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + a: any ValidGeneratorInput = 1.4, + b: any ValidGeneratorInput = 0.3, + x0: Double = 0.0, + x1: Double = 0.0, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, a: a, b: b, x0: x0, x1: x1, + interpolation: interpolation, mul: mul, add: add) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + + for i: Int in 0.. Double { previousOutputValue } + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: Quadratic coefficient. Defaults to `1.4`. No clamping; the orbit diverges for `a ≳ 1.42`. + /// - b: Linear feedback coefficient. Defaults to `0.3`. No clamping; bounded near `|b| < 1`, classic value `0.3`. + /// - x0: Initial `x[n−1]`. Defaults to `0`. + /// - x1: Initial `x[n]`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + a: any ValidGeneratorInput = 1.4, + b: any ValidGeneratorInput = 0.3, + x0: Double = 0.0, + x1: Double = 0.0, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, a: a, b: b, x0: x0, x1: x1, + interpolation: interpolation, mul: mul, add: add) + _setupSubBlockBuffer() + } + + // Bypass sub-block loop: the map advances exactly one audio block per call. + public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + advancePhase(by: dphase * Double(count)) + let target: Double = chaoticInterpolate(_interpolation, phase: _phase, + hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) + + let rampStart: Double = _rampTarget + _rampTarget = target + previousOutputValue = fillRampedResult( + into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) + return _result + } + } +} + +// MARK: - GeneratorEnum + +extension HenonStepped: GeneratorEnum { + public typealias AudioType = HenonStepped.Audio + public typealias ControlType = HenonStepped.Control +} diff --git a/Sources/Lyrebird/Generators/Chaotic/LatoocarfianStepped.swift b/Sources/Lyrebird/Generators/Chaotic/LatoocarfianStepped.swift new file mode 100644 index 0000000..2cf35a4 --- /dev/null +++ b/Sources/Lyrebird/Generators/Chaotic/LatoocarfianStepped.swift @@ -0,0 +1,227 @@ +// LatoocarfianStepped.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Latoocarfian-map (Pickover) oscillator (non-interpolated by default). +/// +/// Iterates the Latoocarfian map at `freq` Hz: +/// ``` +/// x[n+1] = sin(b · y[n]) + c · sin(b · x[n]) +/// y[n+1] = sin(a · x[n]) + d · sin(a · y[n]) +/// ``` +/// and outputs `x`. With the canonical `a = 1`, `b = 3`, `c = 0.5`, `d = 0.5` the +/// orbit is chaotic and bounded to roughly `[-1.5, 1.5]`. Chaos generally requires +/// `|a|, |b|` in about `[0.5, 3]`. Iterations bridge per `interpolation` +/// (default `.none`). +/// +/// `freq`, `a`, `b`, `c`, and `d` are read once per block. See ``ChaoticBase`` for +/// the iteration / interpolation model. +public enum LatoocarfianStepped { + + // MARK: - _Base + + /// Shared Latoocarfian state + parameters for `Audio` and `Control`. + public class _Base: ChaoticBase { + let aInput: any ValidGeneratorInput + let bInput: any ValidGeneratorInput + let cInput: any ValidGeneratorInput + let dInput: any ValidGeneratorInput + + // Map state. + var x: Double + var y: Double + + // Per-block parameter snapshot read by `iterate()`. + var _a: Double = 0.0 + var _b: Double = 0.0 + var _c: Double = 0.0 + var _d: Double = 0.0 + + init( + freq: any ValidGeneratorInput, + a: any ValidGeneratorInput, + b: any ValidGeneratorInput, + c: any ValidGeneratorInput, + d: any ValidGeneratorInput, + xi: Double, + yi: Double, + interpolation: TableInterpolation, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + self.aInput = a._resolvedInput() + self.bInput = b._resolvedInput() + self.cInput = c._resolvedInput() + self.dInput = d._resolvedInput() + self.x = xi + self.y = yi + super.init(freq: freq, interpolation: interpolation, mul: mul, add: add) + } + + override func iterate() -> Double { + let xNew: Double = sin(_b * y) + _c * sin(_b * x) + let yNew: Double = sin(_a * x) + _d * sin(_a * y) + x = xNew + y = yNew + return xNew + } + + /// Snapshot the per-block parameters into the fields `iterate()` reads. + @inline(__always) + func readParams(graph: SynthGraph) { + _a = aInput.floatValue(graph: graph) + _b = bInput.floatValue(graph: graph) + _c = cInput.floatValue(graph: graph) + _d = dInput.floatValue(graph: graph) + } + } + + // MARK: - Audio + + /// Audio-rate Latoocarfian oscillator. + /// + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: First angular factor. Defaults to `1`. Chaos generally needs `|a| ≤ 3`. + /// - b: Second angular factor. Defaults to `3`. Chaos generally needs `|b| ≤ 3`. + /// - c: `x` self-coupling. Defaults to `0.5`. + /// - d: `y` self-coupling. Defaults to `0.5`. + /// - xi: Initial `x`. Defaults to `0.5`. + /// - yi: Initial `y`. Defaults to `0.5`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: First angular factor. Defaults to `1`. Chaos generally needs `|a| ≤ 3`. + /// - b: Second angular factor. Defaults to `3`. Chaos generally needs `|b| ≤ 3`. + /// - c: `x` self-coupling. Defaults to `0.5`. + /// - d: `y` self-coupling. Defaults to `0.5`. + /// - xi: Initial `x`. Defaults to `0.5`. + /// - yi: Initial `y`. Defaults to `0.5`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + a: any ValidGeneratorInput = 1.0, + b: any ValidGeneratorInput = 3.0, + c: any ValidGeneratorInput = 0.5, + d: any ValidGeneratorInput = 0.5, + xi: Double = 0.5, + yi: Double = 0.5, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, a: a, b: b, c: c, d: d, xi: xi, yi: yi, + interpolation: interpolation, mul: mul, add: add) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + + for i: Int in 0.. Double { previousOutputValue } + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: First angular factor. Defaults to `1`. Chaos generally needs `|a| ≤ 3`. + /// - b: Second angular factor. Defaults to `3`. Chaos generally needs `|b| ≤ 3`. + /// - c: `x` self-coupling. Defaults to `0.5`. + /// - d: `y` self-coupling. Defaults to `0.5`. + /// - xi: Initial `x`. Defaults to `0.5`. + /// - yi: Initial `y`. Defaults to `0.5`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + a: any ValidGeneratorInput = 1.0, + b: any ValidGeneratorInput = 3.0, + c: any ValidGeneratorInput = 0.5, + d: any ValidGeneratorInput = 0.5, + xi: Double = 0.5, + yi: Double = 0.5, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, a: a, b: b, c: c, d: d, xi: xi, yi: yi, + interpolation: interpolation, mul: mul, add: add) + _setupSubBlockBuffer() + } + + // Bypass sub-block loop: the map advances exactly one audio block per call. + public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + advancePhase(by: dphase * Double(count)) + let target: Double = chaoticInterpolate(_interpolation, phase: _phase, + hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) + + let rampStart: Double = _rampTarget + _rampTarget = target + previousOutputValue = fillRampedResult( + into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) + return _result + } + } +} + +// MARK: - GeneratorEnum + +extension LatoocarfianStepped: GeneratorEnum { + public typealias AudioType = LatoocarfianStepped.Audio + public typealias ControlType = LatoocarfianStepped.Control +} diff --git a/Sources/Lyrebird/Generators/Chaotic/LinCongStepped.swift b/Sources/Lyrebird/Generators/Chaotic/LinCongStepped.swift new file mode 100644 index 0000000..6deffb4 --- /dev/null +++ b/Sources/Lyrebird/Generators/Chaotic/LinCongStepped.swift @@ -0,0 +1,204 @@ +// LinCongStepped.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Linear-congruential-map oscillator (non-interpolated / stepped by default). +/// +/// Iterates the linear-congruential recurrence at `freq` Hz: +/// ``` +/// x[n+1] = (a · x[n] + c) mod m +/// ``` +/// and outputs `x`, which stays in `[0, m)` by construction. With the canonical +/// `a = 1.1`, `c = 0.13`, `m = 1` the orbit fills `[0, 1)` chaotically. Iterations +/// bridge per `interpolation` (default `.none` — held / stepped, the aliased SC +/// `LinCongN` character). +/// +/// `freq`, `a`, `c`, and `m` are read once per block (no per-sample audio-rate +/// modulation). See ``ChaoticBase`` for the iteration / interpolation model. +public enum LinCongStepped { + + // MARK: - _Base + + /// Shared LCG state + parameters for `Audio` and `Control`. + public class _Base: ChaoticBase { + let aInput: any ValidGeneratorInput + let cInput: any ValidGeneratorInput + let mInput: any ValidGeneratorInput + + // Map state. + var x: Double + + // Per-block parameter snapshot read by `iterate()`. + var _a: Double = 0.0 + var _c: Double = 0.0 + var _m: Double = 1.0 + + init( + freq: any ValidGeneratorInput, + a: any ValidGeneratorInput, + c: any ValidGeneratorInput, + m: any ValidGeneratorInput, + xi: Double, + interpolation: TableInterpolation, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + self.aInput = a._resolvedInput() + self.cInput = c._resolvedInput() + self.mInput = m._resolvedInput() + self.x = xi + super.init(freq: freq, interpolation: interpolation, mul: mul, add: add) + } + + override func iterate() -> Double { + let raw: Double = _a * x + _c + // Reduce modulo m into [0, m). Guard m <= 0 to avoid a divide-by-zero. + let xNew: Double = _m > 0 ? raw - _m * (raw / _m).rounded(.down) : raw + x = xNew + return xNew + } + + /// Snapshot the per-block parameters into the fields `iterate()` reads. + @inline(__always) + func readParams(graph: SynthGraph) { + _a = aInput.floatValue(graph: graph) + _c = cInput.floatValue(graph: graph) + _m = mInput.floatValue(graph: graph) + } + } + + // MARK: - Audio + + /// Audio-rate linear-congruential oscillator. + /// + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: Multiplier. Defaults to `1.1`. + /// - c: Increment. Defaults to `0.13`. + /// - m: Modulus; output stays in `[0, m)`. Defaults to `1`. `m <= 0` disables the reduction. + /// - xi: Initial `x`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: Multiplier. Defaults to `1.1`. + /// - c: Increment. Defaults to `0.13`. + /// - m: Modulus; output stays in `[0, m)`. Defaults to `1`. `m <= 0` disables the reduction. + /// - xi: Initial `x`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + a: any ValidGeneratorInput = 1.1, + c: any ValidGeneratorInput = 0.13, + m: any ValidGeneratorInput = 1.0, + xi: Double = 0.0, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, a: a, c: c, m: m, xi: xi, + interpolation: interpolation, mul: mul, add: add) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + + for i: Int in 0.. Double { previousOutputValue } + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: Multiplier. Defaults to `1.1`. + /// - c: Increment. Defaults to `0.13`. + /// - m: Modulus; output stays in `[0, m)`. Defaults to `1`. `m <= 0` disables the reduction. + /// - xi: Initial `x`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + a: any ValidGeneratorInput = 1.1, + c: any ValidGeneratorInput = 0.13, + m: any ValidGeneratorInput = 1.0, + xi: Double = 0.0, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, a: a, c: c, m: m, xi: xi, + interpolation: interpolation, mul: mul, add: add) + _setupSubBlockBuffer() + } + + // Bypass sub-block loop: the map advances exactly one audio block per call. + public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + advancePhase(by: dphase * Double(count)) + let target: Double = chaoticInterpolate(_interpolation, phase: _phase, + hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) + + let rampStart: Double = _rampTarget + _rampTarget = target + previousOutputValue = fillRampedResult( + into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) + return _result + } + } +} + +// MARK: - GeneratorEnum + +extension LinCongStepped: GeneratorEnum { + public typealias AudioType = LinCongStepped.Audio + public typealias ControlType = LinCongStepped.Control +} diff --git a/Sources/Lyrebird/Generators/Chaotic/LorenzLinear.swift b/Sources/Lyrebird/Generators/Chaotic/LorenzLinear.swift new file mode 100644 index 0000000..e4228eb --- /dev/null +++ b/Sources/Lyrebird/Generators/Chaotic/LorenzLinear.swift @@ -0,0 +1,238 @@ +// LorenzLinear.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Lorenz strange-attractor oscillator (linear-interpolated by default). +/// +/// Integrates the Lorenz system by forward Euler at each iteration: +/// ``` +/// x' = x + h · s · (y − x) +/// y' = y + h · (x · (r − z) − y) +/// z' = z + h · (x · y − b · z) +/// ``` +/// and outputs the `x` coordinate. Iterations advance at `freq` Hz; the audio +/// signal bridges successive `x` values per `interpolation` (default `.linear`). +/// +/// Output is the **raw** `x` coordinate — on the canonical attractor `|x|` runs to +/// roughly `20`. Scale with `mul` (e.g. `mul: 0.05`) for a `[-1, 1]`-ish signal. +/// +/// `freq`, `s`, `r`, `b`, and `h` are read once per block (no per-sample audio-rate +/// modulation). See ``ChaoticBase`` for the iteration / interpolation model. +public enum LorenzLinear { + + // MARK: - _Base + + /// Shared Lorenz state + parameters for `Audio` and `Control`. + public class _Base: ChaoticBase { + let sInput: any ValidGeneratorInput + let rInput: any ValidGeneratorInput + let bInput: any ValidGeneratorInput + let hInput: any ValidGeneratorInput + + // Map state. + var x: Double + var y: Double + var z: Double + + // Per-block parameter snapshot read by `iterate()`. + var _s: Double = 0.0 + var _r: Double = 0.0 + var _b: Double = 0.0 + var _h: Double = 0.0 + + init( + freq: any ValidGeneratorInput, + s: any ValidGeneratorInput, + r: any ValidGeneratorInput, + b: any ValidGeneratorInput, + h: any ValidGeneratorInput, + xi: Double, + yi: Double, + zi: Double, + interpolation: TableInterpolation, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + self.sInput = s._resolvedInput() + self.rInput = r._resolvedInput() + self.bInput = b._resolvedInput() + self.hInput = h._resolvedInput() + self.x = xi + self.y = yi + self.z = zi + super.init(freq: freq, interpolation: interpolation, mul: mul, add: add) + } + + override func iterate() -> Double { + let x1: Double = x + _h * _s * (y - x) + let y1: Double = y + _h * (x * (_r - z) - y) + let z1: Double = z + _h * (x * y - _b * z) + x = x1 + y = y1 + z = z1 + return x + } + + /// Snapshot the per-block parameters into the fields `iterate()` reads. + @inline(__always) + func readParams(graph: SynthGraph) { + _s = sInput.floatValue(graph: graph) + _r = rInput.floatValue(graph: graph) + _b = bInput.floatValue(graph: graph) + _h = hInput.floatValue(graph: graph) + } + } + + // MARK: - Audio + + /// Audio-rate Lorenz oscillator. + /// + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - s: Prandtl number (σ). Defaults to `10`. No clamping; the canonical chaotic regime is `s ≈ 10`. + /// - r: Rayleigh number (ρ). Defaults to `28`. No clamping; chaos onsets near `r ≈ 24.74` — small/large values plus a big `h` can diverge. + /// - b: Geometric factor (β). Defaults to `2.667`. + /// - h: Euler integration step. Defaults to `0.02`. Above ~0.03 the forward-Euler orbit diverges (SC's nominal `0.05` is unstable here), so keep it small. + /// - xi: Initial `x`. Defaults to `0.1`. + /// - yi: Initial `y`. Defaults to `0`. + /// - zi: Initial `z`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.linear`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - s: Prandtl number (σ). Defaults to `10`. No clamping; the canonical chaotic regime is `s ≈ 10`. + /// - r: Rayleigh number (ρ). Defaults to `28`. No clamping; chaos onsets near `r ≈ 24.74` — small/large values plus a big `h` can diverge. + /// - b: Geometric factor (β). Defaults to `2.667`. + /// - h: Euler integration step. Defaults to `0.02`. Keep below ~0.03 (forward Euler diverges above). + /// - xi: Initial `x`. Defaults to `0.1`. + /// - yi: Initial `y`. Defaults to `0`. + /// - zi: Initial `z`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.linear`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + s: any ValidGeneratorInput = 10.0, + r: any ValidGeneratorInput = 28.0, + b: any ValidGeneratorInput = 2.667, + h: any ValidGeneratorInput = 0.02, + xi: Double = 0.1, + yi: Double = 0.0, + zi: Double = 0.0, + interpolation: TableInterpolation = .linear, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, s: s, r: r, b: b, h: h, xi: xi, yi: yi, zi: zi, + interpolation: interpolation, mul: mul, add: add) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + + for i: Int in 0.. Double { previousOutputValue } + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - s: Prandtl number (σ). Defaults to `10`. No clamping; the canonical chaotic regime is `s ≈ 10`. + /// - r: Rayleigh number (ρ). Defaults to `28`. No clamping; chaos onsets near `r ≈ 24.74` — small/large values plus a big `h` can diverge. + /// - b: Geometric factor (β). Defaults to `2.667`. + /// - h: Euler integration step. Defaults to `0.02`. Keep below ~0.03 (forward Euler diverges above). + /// - xi: Initial `x`. Defaults to `0.1`. + /// - yi: Initial `y`. Defaults to `0`. + /// - zi: Initial `z`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.linear`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + s: any ValidGeneratorInput = 10.0, + r: any ValidGeneratorInput = 28.0, + b: any ValidGeneratorInput = 2.667, + h: any ValidGeneratorInput = 0.02, + xi: Double = 0.1, + yi: Double = 0.0, + zi: Double = 0.0, + interpolation: TableInterpolation = .linear, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, s: s, r: r, b: b, h: h, xi: xi, yi: yi, zi: zi, + interpolation: interpolation, mul: mul, add: add) + _setupSubBlockBuffer() + } + + // Bypass sub-block loop: the map advances exactly one audio block per call. + public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + advancePhase(by: dphase * Double(count)) + let target: Double = chaoticInterpolate(_interpolation, phase: _phase, + hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) + + let rampStart: Double = _rampTarget + _rampTarget = target + previousOutputValue = fillRampedResult( + into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) + return _result + } + } +} + +// MARK: - GeneratorEnum + +extension LorenzLinear: GeneratorEnum { + public typealias AudioType = LorenzLinear.Audio + public typealias ControlType = LorenzLinear.Control +} diff --git a/Sources/Lyrebird/Generators/Chaotic/QuadStepped.swift b/Sources/Lyrebird/Generators/Chaotic/QuadStepped.swift new file mode 100644 index 0000000..d6b425f --- /dev/null +++ b/Sources/Lyrebird/Generators/Chaotic/QuadStepped.swift @@ -0,0 +1,202 @@ +// QuadStepped.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// General quadratic-map oscillator (non-interpolated / stepped by default). +/// +/// Iterates the quadratic recurrence at `freq` Hz: +/// ``` +/// x[n+1] = a · x[n]² + b · x[n] + c +/// ``` +/// and outputs `x`. With the canonical `a = 1`, `b = −1`, `c = −0.75` the orbit is +/// chaotic and bounded to roughly `[-1.25, 1.25]` (this family is conjugate to the +/// logistic map). Iterations bridge per `interpolation` (default `.none` — held / +/// stepped, the aliased SC `QuadN` character). +/// +/// `freq`, `a`, `b`, and `c` are read once per block (no per-sample audio-rate +/// modulation). See ``ChaoticBase`` for the iteration / interpolation model. +public enum QuadStepped { + + // MARK: - _Base + + /// Shared quadratic-map state + parameters for `Audio` and `Control`. + public class _Base: ChaoticBase { + let aInput: any ValidGeneratorInput + let bInput: any ValidGeneratorInput + let cInput: any ValidGeneratorInput + + // Map state. + var x: Double + + // Per-block parameter snapshot read by `iterate()`. + var _a: Double = 0.0 + var _b: Double = 0.0 + var _c: Double = 0.0 + + init( + freq: any ValidGeneratorInput, + a: any ValidGeneratorInput, + b: any ValidGeneratorInput, + c: any ValidGeneratorInput, + xi: Double, + interpolation: TableInterpolation, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + self.aInput = a._resolvedInput() + self.bInput = b._resolvedInput() + self.cInput = c._resolvedInput() + self.x = xi + super.init(freq: freq, interpolation: interpolation, mul: mul, add: add) + } + + override func iterate() -> Double { + let xNew: Double = _a * x * x + _b * x + _c + x = xNew + return xNew + } + + /// Snapshot the per-block parameters into the fields `iterate()` reads. + @inline(__always) + func readParams(graph: SynthGraph) { + _a = aInput.floatValue(graph: graph) + _b = bInput.floatValue(graph: graph) + _c = cInput.floatValue(graph: graph) + } + } + + // MARK: - Audio + + /// Audio-rate quadratic-map oscillator. + /// + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: Quadratic coefficient. Defaults to `1`. No clamping; some `(a,b,c)` triples diverge. + /// - b: Linear coefficient. Defaults to `-1`. + /// - c: Constant term. Defaults to `-0.75`. + /// - xi: Initial `x`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: Quadratic coefficient. Defaults to `1`. No clamping; some `(a,b,c)` triples diverge. + /// - b: Linear coefficient. Defaults to `-1`. + /// - c: Constant term. Defaults to `-0.75`. + /// - xi: Initial `x`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + a: any ValidGeneratorInput = 1.0, + b: any ValidGeneratorInput = -1.0, + c: any ValidGeneratorInput = -0.75, + xi: Double = 0.0, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, a: a, b: b, c: c, xi: xi, + interpolation: interpolation, mul: mul, add: add) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + + for i: Int in 0.. Double { previousOutputValue } + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - a: Quadratic coefficient. Defaults to `1`. No clamping; some `(a,b,c)` triples diverge. + /// - b: Linear coefficient. Defaults to `-1`. + /// - c: Constant term. Defaults to `-0.75`. + /// - xi: Initial `x`. Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + a: any ValidGeneratorInput = 1.0, + b: any ValidGeneratorInput = -1.0, + c: any ValidGeneratorInput = -0.75, + xi: Double = 0.0, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, a: a, b: b, c: c, xi: xi, + interpolation: interpolation, mul: mul, add: add) + _setupSubBlockBuffer() + } + + // Bypass sub-block loop: the map advances exactly one audio block per call. + public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + advancePhase(by: dphase * Double(count)) + let target: Double = chaoticInterpolate(_interpolation, phase: _phase, + hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) + + let rampStart: Double = _rampTarget + _rampTarget = target + previousOutputValue = fillRampedResult( + into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) + return _result + } + } +} + +// MARK: - GeneratorEnum + +extension QuadStepped: GeneratorEnum { + public typealias AudioType = QuadStepped.Audio + public typealias ControlType = QuadStepped.Control +} diff --git a/Sources/Lyrebird/Generators/Chaotic/StandardStepped.swift b/Sources/Lyrebird/Generators/Chaotic/StandardStepped.swift new file mode 100644 index 0000000..31f26bf --- /dev/null +++ b/Sources/Lyrebird/Generators/Chaotic/StandardStepped.swift @@ -0,0 +1,191 @@ +// StandardStepped.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Standard-map (Chirikov kicked-rotor) oscillator (non-interpolated by default). +/// +/// Iterates the standard map at `freq` Hz, both variables wrapped into `[0, 2π)`: +/// ``` +/// y[n+1] = (y[n] + k · sin(x[n])) mod 2π +/// x[n+1] = (x[n] + y[n+1]) mod 2π +/// ``` +/// and outputs `x` (range `[0, 2π)` — scale with `mul`, e.g. `mul: 1/π, add: -1` +/// for `[-1, 1)`). Larger `k` → stronger chaos. Iterations bridge per +/// `interpolation` (default `.none`). +/// +/// `freq` and `k` are read once per block. See ``ChaoticBase`` for the iteration / +/// interpolation model. +public enum StandardStepped { + + // MARK: - _Base + + /// Shared standard-map state + parameter for `Audio` and `Control`. + public class _Base: ChaoticBase { + let kInput: any ValidGeneratorInput + + // Map state (angles in [0, 2π)). + var x: Double + var y: Double + + // Per-block parameter snapshot read by `iterate()`. + var _k: Double = 0.0 + + init( + freq: any ValidGeneratorInput, + k: any ValidGeneratorInput, + xi: Double, + yi: Double, + interpolation: TableInterpolation, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + self.kInput = k._resolvedInput() + self.x = xi + self.y = yi + super.init(freq: freq, interpolation: interpolation, mul: mul, add: add) + } + + override func iterate() -> Double { + y = chaoticWrapTwoPi(y + _k * sin(x)) + x = chaoticWrapTwoPi(x + y) + return x + } + + /// Snapshot the per-block parameter into the field `iterate()` reads. + @inline(__always) + func readParams(graph: SynthGraph) { + _k = kInput.floatValue(graph: graph) + } + } + + // MARK: - Audio + + /// Audio-rate standard-map oscillator. + /// + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - k: Kick strength. Defaults to `1`. Larger → stronger chaos. No clamping. + /// - xi: Initial `x` (angle). Defaults to `0.5`. + /// - yi: Initial `y` (momentum). Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - k: Kick strength. Defaults to `1`. Larger → stronger chaos. No clamping. + /// - xi: Initial `x` (angle). Defaults to `0.5`. + /// - yi: Initial `y` (momentum). Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + k: any ValidGeneratorInput = 1.0, + xi: Double = 0.5, + yi: Double = 0.0, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, k: k, xi: xi, yi: yi, + interpolation: interpolation, mul: mul, add: add) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + + for i: Int in 0.. Double { previousOutputValue } + + /// - Parameters: + /// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`. + /// - k: Kick strength. Defaults to `1`. Larger → stronger chaos. No clamping. + /// - xi: Initial `x` (angle). Defaults to `0.5`. + /// - yi: Initial `y` (momentum). Defaults to `0`. + /// - interpolation: Bridging between iterations. Defaults to `.none`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + freq: any ValidGeneratorInput = chaoticDefaultFrequency, + k: any ValidGeneratorInput = 1.0, + xi: Double = 0.5, + yi: Double = 0.0, + interpolation: TableInterpolation = .none, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(freq: freq, k: k, xi: xi, yi: yi, + interpolation: interpolation, mul: mul, add: add) + _setupSubBlockBuffer() + } + + // Bypass sub-block loop: the map advances exactly one audio block per call. + public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + advancePhase(by: dphase * Double(count)) + let target: Double = chaoticInterpolate(_interpolation, phase: _phase, + hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) + + let rampStart: Double = _rampTarget + _rampTarget = target + previousOutputValue = fillRampedResult( + into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) + return _result + } + } +} + +// MARK: - GeneratorEnum + +extension StandardStepped: GeneratorEnum { + public typealias AudioType = StandardStepped.Audio + public typealias ControlType = StandardStepped.Control +} diff --git a/Sources/Lyrebird/Generators/Delays/DelayLine.swift b/Sources/Lyrebird/Generators/Delays/DelayLine.swift index 9f61c76..bca822f 100644 --- a/Sources/Lyrebird/Generators/Delays/DelayLine.swift +++ b/Sources/Lyrebird/Generators/Delays/DelayLine.swift @@ -199,26 +199,16 @@ public final class DelayLine: GeneratorBase, AudioGenerator { // MARK: - Private - /// Catmull-Rom cubic interpolation — static so the per-sample inner loop can call it - /// without a method-dispatch frame on `self`. + /// Catmull-Rom cubic interpolation (delegates to the shared `catmullRomCubic`) + /// — static so the per-sample inner loop can call it without a method-dispatch + /// frame on `self`. @inline(__always) fileprivate static func cubicInterpStatic( frac: Double, y0: Double, y1: Double, y2: Double, y3: Double ) -> Double { - // Catmull-Rom polynomial coefficients: - // p(t) = ((-0.5y0 + 1.5y1 - 1.5y2 + 0.5y3)t³ + (y0 - 2.5y1 + 2y2 - 0.5y3)t² - // + (-0.5y0 + 0.5y2)t + y1) - let catmullHalf: Double = 0.5 - let catmullA3coeff: Double = 1.5 - let catmullB2coeff: Double = 2.5 - let catmullC2coeff: Double = 2.0 - let a: Double = -catmullHalf * y0 + catmullA3coeff * y1 - catmullA3coeff * y2 + catmullHalf * y3 - let b: Double = y0 - catmullB2coeff * y1 + catmullC2coeff * y2 - catmullHalf * y3 - let c: Double = -catmullHalf * y0 + catmullHalf * y2 - let d: Double = y1 - return ((a * frac + b) * frac + c) * frac + d + catmullRomCubic(y0, y1, y2, y3, t: frac) } } diff --git a/Sources/Lyrebird/Generators/Delays/DelayLineFeedback.swift b/Sources/Lyrebird/Generators/Delays/DelayLineFeedback.swift index 1eaf47e..f934bec 100644 --- a/Sources/Lyrebird/Generators/Delays/DelayLineFeedback.swift +++ b/Sources/Lyrebird/Generators/Delays/DelayLineFeedback.swift @@ -300,24 +300,16 @@ public final class DelayLineFeedback: GeneratorBase, AudioGenerator { // MARK: - Private - /// Catmull-Rom cubic interpolation — static so the per-sample inner loop can call it - /// without a method-dispatch frame on `self`. + /// Catmull-Rom cubic interpolation (delegates to the shared `catmullRomCubic`) + /// — static so the per-sample inner loop can call it without a method-dispatch + /// frame on `self`. @inline(__always) fileprivate static func cubicInterpStatic( frac: Double, y0: Double, y1: Double, y2: Double, y3: Double ) -> Double { - // Catmull-Rom polynomial coefficients. - let catmullHalf: Double = 0.5 - let catmullA3coeff: Double = 1.5 - let catmullB2coeff: Double = 2.5 - let catmullC2coeff: Double = 2.0 - let a: Double = -catmullHalf * y0 + catmullA3coeff * y1 - catmullA3coeff * y2 + catmullHalf * y3 - let b: Double = y0 - catmullB2coeff * y1 + catmullC2coeff * y2 - catmullHalf * y3 - let c: Double = -catmullHalf * y0 + catmullHalf * y2 - let d: Double = y1 - return ((a * frac + b) * frac + c) * frac + d + catmullRomCubic(y0, y1, y2, y3, t: frac) } } diff --git a/Sources/Lyrebird/Generators/Dynamics/Balance.swift b/Sources/Lyrebird/Generators/Dynamics/Balance.swift new file mode 100644 index 0000000..eb4878f --- /dev/null +++ b/Sources/Lyrebird/Generators/Dynamics/Balance.swift @@ -0,0 +1,212 @@ +// Balance.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Darwin + +/// Smallest positive `hp` cutoff allowed. Below this the one-pole integrator coefficient +/// would round to `1.0` (comp → 0), freezing the mean-square estimate. Clamps `hp` here. +private let balanceMinHp: Double = 1.0e-3 + +/// Epsilon added to the input mean-square before the linear-domain divide, guarding +/// `sqrt(ms_test / 0)` when `in` is silent. Small enough not to perturb the gain for any +/// audible level. +private let balanceTinyDenominator: Double = 1.0e-10 + +/// Power floor added to each mean-square before the log in `logDomain` mode, so `log10` never +/// sees zero on silence and the log-ratio stays finite. +private let balancePowerFloor: Double = 1.0e-20 + +/// `0.5 · ln(10)`. Converts a base-10 *power*-ratio log into a linear *amplitude* gain: +/// `gain = exp(L · halfLn10)` is `10^(L/2) = (powerRatio)^(1/2)`. +private let balanceHalfLn10: Double = 0.5 * log(10.0) + +/// RMS level matcher. Scales `in` so its running RMS tracks the running RMS of a reference +/// signal `test`. The canonical use is bringing a filtered signal back up to the level of the +/// unfiltered source (SC sc3-plugins `Balance`, JoshUGens). +/// +/// ## Algorithm +/// The running mean-square of each signal is tracked with a one-pole lowpass on the squared +/// samples, then the input is scaled by the square-root of their ratio: +/// ``` +/// b1 = exp(-2π · hp / sr) // integrator pole from the hp cutoff (Hz) +/// comp = 1 − b1 +/// msIn = b1·msIn + comp·in² +/// msTest = b1·msTest + comp·test² +/// rawGain = sqrt(msTest / (msIn + tiny)) +/// gain = lag(rawGain, smooth) // optional decoupled gain lag (see `smooth`) +/// out = in · gain +/// ``` +/// Because the gain is a *ratio* of two identically-normalised mean-squares, the `comp` +/// normalisation cancels — only the `hp` window length affects the result. This matches SC's +/// unnormalised running-sum form (`y = x² + b1·y`) while staying bounded and denormal-safe. +/// +/// ## `hp` vs `smooth` — two decoupled time constants +/// A single one-pole on `x²` ripples at twice the signal frequency, so a high `hp` (fast +/// detection) lets that ripple modulate the gain — audible amplitude-modulation sidebands, +/// worst on low-frequency material. `smooth` adds a **second** one-pole on the computed gain, +/// letting you choose detection responsiveness (`hp`) and gain-change rate (`smooth`) +/// independently: raise `hp` to track level changes quickly, then raise `smooth` to suppress +/// the resulting ripple. `smooth == 0` (default) bypasses the lag, reproducing the classic +/// single-pole behaviour exactly. +/// +/// ## `logDomain` — linear vs decibel gain glide +/// `logDomain == false` (default) smooths the **linear** gain. `logDomain == true` smooths the +/// level difference in the **decibel (log) domain** instead — it lags `log10(ms_test / ms_in)` +/// and exps back, so a `+6 dB` correction and a `−6 dB` correction glide with the same shape +/// and time (symmetric, perceptually even — the way an analogue auto-leveller behaves), versus +/// the linear lag which is faster on boosts than on cuts. Both modes converge to the same +/// steady-state level. The log path costs one extra `log10` + `exp` per sample and floors the +/// power before the log so silence yields a finite gain (`0 · gain = 0`, never `NaN`). +/// +/// ## Edge behaviour +/// - Silent `in` stays silent: `out = 0 · gain = 0` (a zero signal has no RMS to raise). +/// - Silent `test` drives `in` toward zero: `msTest → 0`, so the gain collapses. +/// +/// ## Usage +/// ```swift +/// let filtered = RBJLowPass.Audio(input: source, freq: 800.0, q: 0.707) +/// let matched = Balance(in: filtered, test: source) // classic +/// let matched = Balance(in: filtered, test: source, hp: 40.0, smooth: 0.05) // fast + de-rippled +/// let matched = Balance(in: filtered, test: source, smooth: 0.1, logDomain: true) // dB glide +/// ``` +/// +/// - Parameters: +/// - input: Signal whose level is adjusted (scaled to match `test`). +/// - test: Reference signal whose running RMS sets the target level. +/// - hp: Integration cutoff in Hz. Sets the mean-square window length. Clamped to +/// `≥ 0.001`. Snapshotted once per audio block. Default `10.0`. +/// - smooth: Gain-lag time in seconds. A second one-pole applied to the gain, decoupled from +/// `hp`. `0` bypasses it (classic behaviour). Default `0.0`. +/// - logDomain: When `true`, smooth the gain in the decibel (log) domain for a symmetric, +/// perceptually even glide. Default `false` (linear-gain smoothing). +/// - mul: Output multiplier. Default `1.0`. +/// - add: Output offset. Default `0.0`. +public final class Balance: GeneratorBase, AudioGenerator { + + // MARK: - Inputs + + private let _input: any ValidGeneratorInput + private let _testInput: any ValidGeneratorInput + private let _hpInput: any ValidGeneratorInput + private let _hpIsGenerator: Bool + private let _smooth: Double + private let _logDomain: Bool + private let _mulAdd: MulAddSpec + + // MARK: - State (running mean-square estimates + lagged gain) + + private var _msIn: Double = 0.0 + private var _msTest: Double = 0.0 + /// Linear-domain lagged gain. Used when `logDomain == false`. Neutral start `1.0`. + private var _gain: Double = 1.0 + /// Log-domain smoothed level difference (`log10` power ratio). Used when + /// `logDomain == true`. Neutral start `0.0` (`exp(0) = 1` → unity gain). + private var _logState: Double = 0.0 + + // MARK: - Init + + /// - Parameters: + /// - input: Signal whose level is adjusted (scaled to match `test`). + /// - test: Reference signal whose running RMS sets the target level. + /// - hp: Integration cutoff in Hz. Sets the mean-square window length. Clamped to + /// `≥ 0.001`. Snapshotted once per audio block. Default `10.0`. + /// - smooth: Gain-lag time in seconds. A second one-pole applied to the gain, decoupled + /// from `hp`. `0` bypasses it (classic behaviour). Default `0.0`. + /// - logDomain: When `true`, smooth the gain in the decibel (log) domain for a symmetric, + /// perceptually even glide. Default `false` (linear-gain smoothing). + /// - mul: Output multiplier. Default `1.0`. + /// - add: Output offset. Default `0.0`. + public init( + in input: any ValidGeneratorInput, + test: any ValidGeneratorInput, + hp: any ValidGeneratorInput = 10.0, + smooth: Double = 0.0, + logDomain: Bool = false, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + precondition(smooth >= 0, "Balance: smooth must be ≥ 0") + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + let resolvedTest: any ValidGeneratorInput = test._resolvedInput() + let resolvedHp: any ValidGeneratorInput = hp._resolvedInput() + _input = resolvedInput + _testInput = resolvedTest + _hpInput = resolvedHp + _hpIsGenerator = resolvedHp is any Generator + _smooth = smooth + _logDomain = logDomain + _mulAdd = MulAddSpec(mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inSamples: [Double] = _input.calculatedSamples(graph: graph, count: count).first ?? [] + let testSamples: [Double] = _testInput.calculatedSamples(graph: graph, count: count).first ?? [] + let hp: Double = max(balanceMinHp, + lastGeneratorSampleOrFloat(_hpInput, isGenerator: _hpIsGenerator, + graph: graph, count: count)) + let sr: Double = graph.engine.sampleRate + + // One-pole integrator pole + complement from the hp cutoff. Recomputed once per block. + let b1: Double = exp(-lyrebirdTwoPi * hp / sr) + let comp: Double = 1.0 - b1 + + // Decoupled gain-lag coefficients (shared by both domains). `smooth == 0` → lagB1 0, + // lagComp 1 → pass-through (instant gain, classic behaviour). + let lagB1: Double = _smooth > 0 ? exp(-1.0 / (_smooth * sr)) : 0.0 + let lagComp: Double = 1.0 - lagB1 + + var msIn: Double = _msIn + var msTest: Double = _msTest + let nIn: Int = inSamples.count + let nTest: Int = testSamples.count + + // Branch on the domain once (not per sample). Index form (not raw pointers) so an empty + // `in`/`test` block — either input may independently return zero rows — pads with zeros + // instead of leaving `_result` stale. + if _logDomain { + var logState: Double = _logState + for i: Int in 0.. 0 ? level / windowPeak : currentGain // hold gain when silent +/// gain = requiredGain < gain ? requiredGain // instant attack +/// : releaseCoeff·gain + attackComp·requiredGain // smoothed release +/// y[n] = delayed(x)[n] · gain +/// ``` +/// `windowPeak == 0` (true silence in the window) holds the current gain rather than dividing +/// by zero. A near-silent (but non-zero) window amplifies its noise floor toward `level` — the +/// defining behaviour of a normalizer; gate upstream if that is undesirable. +/// +/// ## Latency +/// Output is delayed by exactly `delaySamples = Int(dur × sampleRate)`. `dur` is fixed at init +/// (it sizes the ring buffer and sets the release time constant). +/// +/// ## RT-allocation model +/// `_delayRing` is pre-allocated at `init` to `delaySamples + lyrebirdDefaultResultBufferSize +/// + 1`. The monotonic sliding-window-max deque (payload `(peak, expireAtPos)`) is +/// pre-allocated to `delaySamples + 2`. No heap allocation in `_computeSamples`. +/// +/// ## Sliding-window max +/// Window peak is O(1) amortised per sample via a monotonic deque of `(peakValue, expireAtPos)` +/// entries kept in descending peak order; the front always holds the maximum in the current +/// look-ahead window. Identical infrastructure to ``LookAheadLimiter``. +/// +/// ## Usage +/// ```swift +/// let norm = Normalizer(in: signal, sampleRate: engine.sampleRate) +/// let norm = Normalizer(in: signal, level: 0.8, dur: 0.01, sampleRate: engine.sampleRate) +/// ``` +/// +/// - Parameters: +/// - input: Signal to normalize. +/// - level: Target peak amplitude (absolute value). Output peak tracks this value once the +/// look-ahead window has filled. Default `1.0`. +/// - dur: Look-ahead and output delay in seconds. Fixed at init — sizes the ring buffer and +/// sets the release time constant. Range `[0, ∞)`; values above ~50 ms waste memory. +/// Default `0.01` (10 ms). +/// - sampleRate: Engine sample rate in Hz. **Must match `SynthesisEngine.sampleRate`.** +/// Required — no default. Ring buffer size and release coefficient are computed +/// at init from this value and cannot be updated at runtime. +public final class Normalizer: GeneratorBase, AudioGenerator { + + // MARK: - Parameters + + private let _input: any ValidGeneratorInput + private let _levelInput: any ValidGeneratorInput + private let _delaySamples: Int + + // MARK: - Pre-allocated delay ring + + private var _delayRing: [Double] + private let _ringSize: Int + private var _writeIdx: Int = 0 + private var _readIdx: Int + + // MARK: - Sliding-window max (monotonic deque) + // Front of deque always holds the maximum in the current look-ahead window. + + private struct DequeEntry { + var peak: Double + var expireAtPos: Int + } + private var _deque: [DequeEntry] + private let _dequeCapacity: Int + private var _dequeHeadIdx: Int = 0 + private var _dequeTailIdx: Int = 0 + private var _dequeCount: Int = 0 + + // MARK: - State + + private var _writePos: Int = 0 + private var _gain: Double = 1.0 + private let _releaseCoeff: Double + private let _attackComp: Double + + // MARK: - Init + + /// - Parameters: + /// - input: Signal to normalize. + /// - level: Target peak amplitude (absolute value). Output peak tracks this value once the + /// look-ahead window has filled. Default `1.0`. + /// - dur: Look-ahead and output delay in seconds. Fixed at init — sizes the ring buffer and + /// sets the release time constant. Range `[0, ∞)`. Default `0.01` (10 ms). + /// - sampleRate: Engine sample rate in Hz. **Must match `SynthesisEngine.sampleRate`.** + /// Required — no default. Ring buffer size and release coefficient are + /// computed at init from this value and cannot be updated at runtime. + public init( + in input: any ValidGeneratorInput, + level: any ValidGeneratorInput = 1.0, + dur: Double = 0.01, + sampleRate: Double + ) { + precondition(dur >= 0, "Normalizer: dur must be ≥ 0") + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + let resolvedLevel: any ValidGeneratorInput = level._resolvedInput() + _input = resolvedInput + _levelInput = resolvedLevel + _delaySamples = Int(dur * sampleRate) + let bufferSize: Int = _delaySamples + lyrebirdDefaultResultBufferSize + 1 + _ringSize = bufferSize + _delayRing = makeSampleBuffer(bufferSize) + _releaseCoeff = dur > 0 + ? exp(-1.0 / (sampleRate * dur)) + : 0.0 + _attackComp = 1.0 - _releaseCoeff + // Deque capacity = max-live (_delaySamples + 1) + 1 slot of slack so a + // push-before-front-pop on a wraparound step does not collide. + _dequeCapacity = max(2, _delaySamples + 2) + _deque = [DequeEntry]( + repeating: DequeEntry(peak: 0.0, expireAtPos: 0), + count: _dequeCapacity + ) + // Read trails write by _delaySamples. With writeIdx == 0: + // readIdx = (0 - _delaySamples + _ringSize) % _ringSize + // _delaySamples == 0 → readIdx == 0; otherwise == _ringSize - _delaySamples. + _readIdx = _delaySamples == 0 ? 0 : _ringSize - _delaySamples + } + + /// Gain the upcoming sample requires to map `windowPeak` onto `level`. Holds the current + /// gain when the window is exactly silent (avoids `level / 0`). + @inline(__always) + private func requiredGain(windowPeak: Double, level: Double, currentGain: Double) -> Double { + windowPeak > 0.0 ? level / windowPeak : currentGain + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let level: Double = max(0.0, _levelInput.floatValue(graph: graph)) + let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count) + + let ringSize: Int = _ringSize + let releaseCoeff: Double = _releaseCoeff + let attackComp: Double = _attackComp + + guard let ins: [Double] = inputSamples.first else { + // Pathological branch: upstream returned a 0-row matrix. Advance ring + deque + // maintenance per-sample so any peaks still inside the look-ahead window from a + // prior block keep tracking the delay-line output. + var gain: Double = _gain + var writeIdx: Int = _writeIdx + var readIdx: Int = _readIdx + var writePos: Int = _writePos + let dequeCap: Int = _dequeCapacity + let lookAhead: Int = _delaySamples + var headIdx: Int = _dequeHeadIdx + var tailIdx: Int = _dequeTailIdx + var dequeCount: Int = _dequeCount + + for i: Int in 0..= ringSize { writeIdx -= ringSize } + + if lookAhead > 0 { + while dequeCount > 0 { + let backIdx: Int = tailIdx == 0 ? dequeCap - 1 : tailIdx - 1 + if _deque[backIdx].peak <= 0.0 { + tailIdx = backIdx + dequeCount -= 1 + } else { + break + } + } + _deque[tailIdx] = DequeEntry(peak: 0.0, expireAtPos: writePos + lookAhead) + tailIdx += 1 + if tailIdx >= dequeCap { tailIdx -= dequeCap } + dequeCount += 1 + while dequeCount > 0 && _deque[headIdx].expireAtPos < writePos { + headIdx += 1 + if headIdx >= dequeCap { headIdx -= dequeCap } + dequeCount -= 1 + } + let windowPeak: Double = _deque[headIdx].peak + let needed: Double = requiredGain(windowPeak: windowPeak, level: level, currentGain: gain) + gain = needed < gain ? needed : releaseCoeff * gain + attackComp * needed + } else { + gain = releaseCoeff * gain + attackComp + } + + _result[0][i] = _delayRing[readIdx] * gain + readIdx += 1 + if readIdx >= ringSize { readIdx -= ringSize } + writePos &+= 1 + } + gain = denormalsToZero(gain) + _gain = gain + _writeIdx = writeIdx + _readIdx = readIdx + _writePos = writePos + _dequeHeadIdx = headIdx + _dequeTailIdx = tailIdx + _dequeCount = dequeCount + return _result + } + + var gain: Double = _gain + var writeIdx: Int = _writeIdx + var readIdx: Int = _readIdx + + if _delaySamples == 0 { + // Fast path: peak follower only — no ring, no deque. `_writePos` / `_writeIdx` / + // `_readIdx` are intentionally not advanced; none are read while `_delaySamples == 0`. + for i: Int in 0..= ringSize { writeIdx -= ringSize } + + // Pop from back while back peak ≤ new peak. + while dequeCount > 0 { + let backIdx: Int = tailIdx == 0 ? dequeCap - 1 : tailIdx - 1 + if _deque[backIdx].peak <= absSample { + tailIdx = backIdx + dequeCount -= 1 + } else { + break + } + } + // Push new entry at back. + _deque[tailIdx] = DequeEntry(peak: absSample, expireAtPos: writePos + lookAhead) + tailIdx += 1 + if tailIdx >= dequeCap { tailIdx -= dequeCap } + dequeCount += 1 + // Pop from front while expired (storedPos < writePos - lookAhead → expireAtPos < writePos). + while dequeCount > 0 && _deque[headIdx].expireAtPos < writePos { + headIdx += 1 + if headIdx >= dequeCap { headIdx -= dequeCap } + dequeCount -= 1 + } + let windowPeak: Double = _deque[headIdx].peak + + // Normalize: scale up or down so the windowed peak maps to `level`. + let needed: Double = requiredGain(windowPeak: windowPeak, level: level, currentGain: gain) + + // Instantaneous attack (prevents overshoot above level), smoothed release. + gain = needed < gain ? needed : releaseCoeff * gain + attackComp * needed + + _result[0][i] = _delayRing[readIdx] * gain + readIdx += 1 + if readIdx >= ringSize { readIdx -= ringSize } + writePos &+= 1 + } + + // Denormal flush once per block. + gain = denormalsToZero(gain) + + _gain = gain + _writeIdx = writeIdx + _readIdx = readIdx + _writePos = writePos + _dequeHeadIdx = headIdx + _dequeTailIdx = tailIdx + _dequeCount = dequeCount + + return _result + } +} + +// MARK: - GeneratorEnum + +// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only generator +// with no paired `Control` variant. diff --git a/Sources/Lyrebird/Generators/Filters/AllpassFilter.swift b/Sources/Lyrebird/Generators/Filters/AllpassFilter.swift index 9b15d0d..b9c87c5 100644 --- a/Sources/Lyrebird/Generators/Filters/AllpassFilter.swift +++ b/Sources/Lyrebird/Generators/Filters/AllpassFilter.swift @@ -260,22 +260,14 @@ public final class AllpassFilter: GeneratorBase, AudioGenerator { } } -// MARK: - Local cubic interpolation +// MARK: - Catmull-Rom cubic interpolation (delegates to shared catmullRomCubic) private func apCubicInterp( frac: Double, y0: Double, y1: Double, y2: Double, y3: Double ) -> Double { - let half: Double = 0.5 - let a3: Double = 1.5 - let b2: Double = 2.5 - let c2: Double = 2.0 - let a: Double = -half * y0 + a3 * y1 - a3 * y2 + half * y3 - let b: Double = y0 - b2 * y1 + c2 * y2 - half * y3 - let c: Double = -half * y0 + half * y2 - let d: Double = y1 - return ((a * frac + b) * frac + c) * frac + d + catmullRomCubic(y0, y1, y2, y3, t: frac) } // MARK: - GeneratorEnum diff --git a/Sources/Lyrebird/Generators/Filters/CombFilter.swift b/Sources/Lyrebird/Generators/Filters/CombFilter.swift index 5d18de1..d6bde4e 100644 --- a/Sources/Lyrebird/Generators/Filters/CombFilter.swift +++ b/Sources/Lyrebird/Generators/Filters/CombFilter.swift @@ -233,22 +233,14 @@ public final class CombFilter: GeneratorBase, AudioGenerator { } } -// MARK: - Catmull-Rom cubic interpolation (local copy, avoids cross-file dependency) +// MARK: - Catmull-Rom cubic interpolation (delegates to shared catmullRomCubic) private func cubicInterp( frac: Double, y0: Double, y1: Double, y2: Double, y3: Double ) -> Double { - let half: Double = 0.5 - let a3: Double = 1.5 - let b2: Double = 2.5 - let c2: Double = 2.0 - let a: Double = -half * y0 + a3 * y1 - a3 * y2 + half * y3 - let b: Double = y0 - b2 * y1 + c2 * y2 - half * y3 - let c: Double = -half * y0 + half * y2 - let d: Double = y1 - return ((a * frac + b) * frac + c) * frac + d + catmullRomCubic(y0, y1, y2, y3, t: frac) } // `combFeedbackCoeff` and the underlying `lyrebirdLog60dBLn` constant live in diff --git a/Sources/Lyrebird/Generators/Filters/Formlet.swift b/Sources/Lyrebird/Generators/Filters/Formlet.swift new file mode 100644 index 0000000..a37a71d --- /dev/null +++ b/Sources/Lyrebird/Generators/Filters/Formlet.swift @@ -0,0 +1,276 @@ +// Formlet.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Accelerate + +/// FOF-like resonant filter parameterised by attack and decay times. +/// +/// The impulse response is a sine wave at `freq` enveloped by a rise-then-fall +/// (Decay2-style) shape — short `attackTime` followed by longer `decayTime`. +/// Equivalent to the difference of two `ResonatingFilter` (Ringz) outputs sharing +/// the same `freq`: +/// +/// ``` +/// Formlet(in, freq, attack, decay) +/// == ResonatingFilter(in, freq, decay) − ResonatingFilter(in, freq, attack) +/// ``` +/// +/// Each Ringz uses the frequency-independent decay coefficient +/// `R = exp(log(0.001) / (time · sr))` (−60 dB after `time` seconds) and the +/// Direct Form I recurrence `y[n] = (1 − R)·x[n] − na1·y[n−1] − na2·y[n−2]`. +/// Subtracting the short-time (attack) response from the long-time (decay) +/// response yields the characteristic formant grain. Classic vowel / formant +/// synthesis when several Formlets at different `freq` excite a common source. +/// +/// `freq`, `attackTime`, and `decayTime` all accept generator inputs. In `Audio`, +/// when any is a generator, block-boundary coefficient interpolation is applied +/// across both resonator coefficient sets (same scheme as `ResonatingFilter`); +/// `Control` reads each input once per block (no interpolation). +/// `denormalsToZero()` is applied to all four feedback state variables each block. +/// +/// ## Usage +/// ```swift +/// Formlet.Audio(input: impulse, freq: 880.0, attackTime: 0.001, decayTime: 0.1) +/// Formlet.Control(input: trig, freq: 220.0, attackTime: 0.01, decayTime: 0.5) +/// ``` +public enum Formlet { + + // MARK: - _Base + + /// Shared stored state for `Formlet.Audio` and `Formlet.Control`. + public class _Base: GeneratorBase { + let inputSource: any ValidGeneratorInput + let freqInput: any ValidGeneratorInput + let attackTimeInput: any ValidGeneratorInput + let decayTimeInput: any ValidGeneratorInput + let freqIsGenerator: Bool + let attackTimeIsGenerator: Bool + let decayTimeIsGenerator: Bool + let anyCoeffIsGenerator: Bool + var _mulAdd: MulAddSpec + + // Decay (long-time) resonator state. + var yDecay1: Double = 0.0 + var yDecay2: Double = 0.0 + // Attack (short-time) resonator state. + var yAttack1: Double = 0.0 + var yAttack2: Double = 0.0 + + init( + input: any ValidGeneratorInput, + freq: any ValidGeneratorInput, + attackTime: any ValidGeneratorInput, + decayTime: any ValidGeneratorInput, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput() + let resolvedAttackTime: any ValidGeneratorInput = attackTime._resolvedInput() + let resolvedDecayTime: any ValidGeneratorInput = decayTime._resolvedInput() + self.inputSource = resolvedInput + self.freqInput = resolvedFreq + self.attackTimeInput = resolvedAttackTime + self.decayTimeInput = resolvedDecayTime + let freqGen: Bool = resolvedFreq is any Generator + let attackGen: Bool = resolvedAttackTime is any Generator + let decayGen: Bool = resolvedDecayTime is any Generator + self.freqIsGenerator = freqGen + self.attackTimeIsGenerator = attackGen + self.decayTimeIsGenerator = decayGen + self.anyCoeffIsGenerator = freqGen || attackGen || decayGen + self._mulAdd = MulAddSpec(mul: mul, add: add) + } + } + + // MARK: - Audio + + /// Audio-rate FOF-like resonant filter. + /// + /// - Parameters: + /// - input: Signal to excite the resonators. + /// - freq: Resonant (formant) frequency in Hz. A 0.1 Hz floor is applied internally. + /// - attackTime: Rise time in seconds (60 dB time of the short resonator). Shorter than `decayTime`. + /// - decayTime: Fall time in seconds (60 dB time of the long resonator). + /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. + /// - add: Offset added after multiplier. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + private var scratch: [Double] = makeSampleBuffer() + + /// - Parameters: + /// - input: Signal to excite the resonators. + /// - freq: Resonant (formant) frequency in Hz. A 0.1 Hz floor is applied internally. + /// - attackTime: Rise time in seconds (60 dB time of the short resonator). Shorter than `decayTime`. + /// - decayTime: Fall time in seconds (60 dB time of the long resonator). + /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. + /// - add: Offset added after multiplier. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + freq: any ValidGeneratorInput, + attackTime: any ValidGeneratorInput, + decayTime: any ValidGeneratorInput, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, freq: freq, attackTime: attackTime, + decayTime: decayTime, mul: mul, add: add) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + let inputBlock: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? [] + let sr: Double = graph.engine.sampleRate + + if anyCoeffIsGenerator { + let freqBlock: [Double]? = freqIsGenerator + ? freqInput.calculatedSamples(graph: graph, count: count).first : nil + let attackBlock: [Double]? = attackTimeIsGenerator + ? attackTimeInput.calculatedSamples(graph: graph, count: count).first : nil + let decayBlock: [Double]? = decayTimeIsGenerator + ? decayTimeInput.calculatedSamples(graph: graph, count: count).first : nil + + let lastIdx: Int = count - 1 + let f0: Double = freqBlock.map { $0.isEmpty ? freqInput.floatValue(graph: graph) : $0[0] } + ?? freqInput.floatValue(graph: graph) + let fN: Double = freqBlock.map { $0.isEmpty ? f0 : $0[min($0.count - 1, lastIdx)] } ?? f0 + let a0: Double = attackBlock.map { $0.isEmpty ? attackTimeInput.floatValue(graph: graph) : $0[0] } + ?? attackTimeInput.floatValue(graph: graph) + let aN: Double = attackBlock.map { $0.isEmpty ? a0 : $0[min($0.count - 1, lastIdx)] } ?? a0 + let d0: Double = decayBlock.map { $0.isEmpty ? decayTimeInput.floatValue(graph: graph) : $0[0] } + ?? decayTimeInput.floatValue(graph: graph) + let dN: Double = decayBlock.map { $0.isEmpty ? d0 : $0[min($0.count - 1, lastIdx)] } ?? d0 + + let decayStart: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: f0, decayTime: d0, sr: sr) + let decayEnd: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: fN, decayTime: dN, sr: sr) + let attackStart: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: f0, decayTime: a0, sr: sr) + let attackEnd: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: fN, decayTime: aN, sr: sr) + + runTwoPoleResonatorInterpolatedBlock( + input: inputBlock, into: &_result[0], + y1: &yDecay1, y2: &yDecay2, + start: decayStart, end: decayEnd, count: count) + runTwoPoleResonatorInterpolatedBlock( + input: inputBlock, into: &scratch, + y1: &yAttack1, y2: &yAttack2, + start: attackStart, end: attackEnd, count: count) + } else { + let freq: Double = freqInput.floatValue(graph: graph) + let attackTime: Double = attackTimeInput.floatValue(graph: graph) + let decayTime: Double = decayTimeInput.floatValue(graph: graph) + let decayC: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: freq, decayTime: decayTime, sr: sr) + let attackC: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: freq, decayTime: attackTime, sr: sr) + + runTwoPoleResonatorScalarBlock( + input: inputBlock, into: &_result[0], + y1: &yDecay1, y2: &yDecay2, + b0: decayC.b0, na1: decayC.na1, na2: decayC.na2, count: count) + runTwoPoleResonatorScalarBlock( + input: inputBlock, into: &scratch, + y1: &yAttack1, y2: &yAttack2, + b0: attackC.b0, na1: attackC.na1, na2: attackC.na2, count: count) + } + + // Output = decay response − attack response (FOF grain). + _result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer) in + guard let dstP: UnsafeMutablePointer = dst.baseAddress else { return } + scratch.withUnsafeBufferPointer { (atk: UnsafeBufferPointer) in + guard let atkP: UnsafePointer = atk.baseAddress else { return } + for i: Int in 0.. [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + let controlRate: Double = graph.engine.sampleRate / Double(graph.engine.blockSize) + let freq: Double = freqInput.floatValue(graph: graph) + let attackTime: Double = attackTimeInput.floatValue(graph: graph) + let decayTime: Double = decayTimeInput.floatValue(graph: graph) + let x: Double = inputSource.floatValue(graph: graph) + + let decayC: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: freq, decayTime: decayTime, sr: controlRate) + let attackC: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: freq, decayTime: attackTime, sr: controlRate) + + let yDecay: Double = decayC.b0 * x - decayC.na1 * yDecay1 - decayC.na2 * yDecay2 + yDecay2 = denormalsToZero(yDecay1) + yDecay1 = denormalsToZero(yDecay) + let yAttack: Double = attackC.b0 * x - attackC.na1 * yAttack1 - attackC.na2 * yAttack2 + yAttack2 = denormalsToZero(yAttack1) + yAttack1 = denormalsToZero(yAttack) + + var fillValue: Double = yDecay - yAttack + _result[0].withUnsafeMutableBufferPointer { (buf: inout UnsafeMutableBufferPointer) in + guard let base: UnsafeMutablePointer = buf.baseAddress else { return } + vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count)) + } + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + previousOutputValue = _result[0][count - 1] + return _result + } + } +} + +// MARK: - GeneratorEnum + +extension Formlet: GeneratorEnum { + public typealias AudioType = Formlet.Audio + public typealias ControlType = Formlet.Control +} diff --git a/Sources/Lyrebird/Generators/Filters/Klank.swift b/Sources/Lyrebird/Generators/Filters/Klank.swift new file mode 100644 index 0000000..d5d1bfb --- /dev/null +++ b/Sources/Lyrebird/Generators/Filters/Klank.swift @@ -0,0 +1,331 @@ +// Klank.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Accelerate + +/// Number of channels (= per-resonator parameters) required by ``Klank``: `freq`, `amp`, +/// `decay`. Each ``LyrebirdBuffer`` frame supplies one resonator's parameters. The channel +/// order (`freq, amp, decay`) matches the SuperCollider `Klank` specification triple. +public let klankSpecChannelCount: Int = 3 + +/// Buffer channel index of the resonant frequency (Hz). +public let klankFreqChannel: Int = 0 + +/// Buffer channel index of the per-resonator amplitude (linear gain). +public let klankAmpChannel: Int = 1 + +/// Buffer channel index of the −60 dB ring decay time (seconds). +public let klankDecayChannel: Int = 2 + +/// Floor applied to per-resonator effective frequency when computing coefficients. +private let klankMinFreq: Double = 0.1 + +/// Floor applied to per-resonator effective decay time when computing coefficients. +private let klankMinDecay: Double = 1.0e-6 + +/// Natural-log of the SC-conventional −60 dB target. `R = exp(klankLog0001 / (decay·sr))`. +private let klankLog0001: Double = log(0.001) + +/// Bank of N parallel two-pole (Ringz-style) resonators with **block-rate spec modulation**. +/// +/// `Klank` is the modulatable counterpart of ``ResonatorBank``. Like `ResonatorBank` it reads +/// a per-resonator `[freq, amp, decay]` table from a single ``LyrebirdBuffer`` (`channelCount +/// == 3`, one resonator per frame) and drives every resonator in parallel from a shared input, +/// summing to one mono channel. `Klank` additionally exposes the three SuperCollider `Klank` +/// modulation parameters — `freqscale`, `freqoffset`, `decayscale` — which scale and shift the +/// whole table without re-specifying it: +/// +/// ``` +/// freq_k_effective = freq_k · freqscale + freqoffset +/// decay_k_effective = decay_k · decayscale +/// ``` +/// +/// Each is any `ValidGeneratorInput`, snapshotted once per audio block (block-rate / "control +/// rate" respecification). Wire a control generator to glide the bank's tuning or ring time +/// while it sounds. The full table can additionally be swapped at run time via +/// ``setBuffer(_:engine:)`` (RT-safe ``RTBufferSlot`` handoff), so both per-mode editing and +/// whole-table replacement are available. +/// +/// ## Difference equation (per resonator k) +/// +/// ``` +/// R_k = exp(log(0.001) / (decay_k_effective · sr)) // −60 dB after decay_k_effective seconds +/// w0_k = 2π · freq_k_effective / sr +/// b0_k = (1 − R_k) · amp_k +/// na1_k = −2 · R_k · cos(w0_k) +/// na2_k = R_k² +/// y_k[n] = b0_k · x[n] − na1_k · y_k[n−1] − na2_k · y_k[n−2] +/// ``` +/// +/// The output sample is `Σ_k y_k[n]`. Coefficients are recomputed once per block from the +/// snapshotted spec and modulation values, then the per-sample inner loop is vectorised +/// across the bank with vDSP (identical kernel to ``ResonatorBank``). +/// +/// `freq_effective` is clamped to `>= 0.1` Hz; `decay_effective` is clamped to `>= 1e-6` s. No +/// internal clamp is applied to `amp` (negative amplitudes invert phase). +/// +/// ## Usage +/// +/// ```swift +/// let bank = LyrebirdBuffer(count: 3, channelCount: klankSpecChannelCount) +/// // [freq, amp, decay] per mode +/// for (i, t) in [ +/// (400.0, 1.0, 1.0), +/// (1500.0, 0.5, 0.6), +/// (3300.0, 0.25, 0.3), +/// ].enumerated() { +/// bank.setValue(t.0, frame: i, channel: klankFreqChannel) +/// bank.setValue(t.1, frame: i, channel: klankAmpChannel) +/// bank.setValue(t.2, frame: i, channel: klankDecayChannel) +/// } +/// +/// let exciter = Impulse.Audio(freq: 0.5, mul: 0.4) +/// // Sweep the whole bank up an octave with an LFO. +/// let voice = Klank.Audio( +/// input: exciter, buffer: bank, +/// freqscale: OscSin.Control(freq: 0.2) * 0.5 + 1.5 +/// ) +/// ``` +public enum Klank { + + /// Audio-rate parallel resonator bank with block-rate `freqscale` / `freqoffset` / + /// `decayscale` modulation. + /// + /// - Parameters: + /// - input: Mono signal driving every resonator in the bank. Any `ValidGeneratorInput`. + /// - buffer: Mode table. Must have `channelCount == 3` and `count >= 1`. Frame `k` + /// provides resonator `k`'s `[freq, amp, decay]`. Bank size = `buffer.count`. Live + /// `setValue` writes are picked up once per audio block; whole-table swap via + /// ``setBuffer(_:engine:)``. + /// - freqscale: Multiplier applied to every resonator frequency. Snapshotted per block. + /// Defaults to `1.0`. + /// - freqoffset: Hz added to every resonator frequency after scaling. Snapshotted per + /// block. Defaults to `0.0`. + /// - decayscale: Multiplier applied to every resonator decay time. Snapshotted per block. + /// Defaults to `1.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: GeneratorBase, AudioGenerator { + + // MARK: Inputs + + private let _inputSource: any ValidGeneratorInput + /// Atomic slot — supports live whole-table swap via ``setBuffer(_:engine:)``. + /// Loaded once per audio block. + private let _slot: RTBufferSlot + + private let _freqScaleInput: any ValidGeneratorInput + private let _freqScaleIsGenerator: Bool + private let _freqOffsetInput: any ValidGeneratorInput + private let _freqOffsetIsGenerator: Bool + private let _decayScaleInput: any ValidGeneratorInput + private let _decayScaleIsGenerator: Bool + + // MARK: State (one entry per resonator) + + private let _bankSize: Int + private var _b0: [Double] + private var _na1: [Double] + private var _na2: [Double] + private var _y1: [Double] + private var _y2: [Double] + + // MARK: Per-sample scratch (size = _bankSize) + + private var _newY: [Double] + private var _tmp: [Double] + + // MARK: Output + private let _mulAdd: MulAddSpec + + // MARK: Init + + /// - Parameters: + /// - input: Mono signal driving every resonator in the bank. Any `ValidGeneratorInput`. + /// - buffer: Mode table. Must have `channelCount == 3` and `count >= 1`. Frame `k` + /// provides resonator `k`'s `[freq, amp, decay]`. Bank size = `buffer.count`. Live + /// `setValue` writes are picked up once per audio block; whole-table swap via + /// ``setBuffer(_:engine:)``. + /// - freqscale: Multiplier applied to every resonator frequency. Snapshotted per block. + /// Defaults to `1.0`. + /// - freqoffset: Hz added to every resonator frequency after scaling. Snapshotted per + /// block. Defaults to `0.0`. + /// - decayscale: Multiplier applied to every resonator decay time. Snapshotted per + /// block. Defaults to `1.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public init( + input: any ValidGeneratorInput, + buffer: LyrebirdBuffer, + freqscale: any ValidGeneratorInput = 1.0, + freqoffset: any ValidGeneratorInput = 0.0, + decayscale: any ValidGeneratorInput = 1.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + precondition( + buffer.channelCount == klankSpecChannelCount, + "Klank: buffer must have channelCount == \(klankSpecChannelCount) " + + "(freq, amp, decay); got channelCount=\(buffer.channelCount)" + ) + precondition( + buffer.count >= 1, + "Klank: buffer must have count >= 1; got count=\(buffer.count)" + ) + + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + self._inputSource = resolvedInput + self._slot = RTBufferSlot(initial: buffer) + + let resolvedFreqScale: any ValidGeneratorInput = freqscale._resolvedInput() + self._freqScaleInput = resolvedFreqScale + self._freqScaleIsGenerator = resolvedFreqScale is any Generator + let resolvedFreqOffset: any ValidGeneratorInput = freqoffset._resolvedInput() + self._freqOffsetInput = resolvedFreqOffset + self._freqOffsetIsGenerator = resolvedFreqOffset is any Generator + let resolvedDecayScale: any ValidGeneratorInput = decayscale._resolvedInput() + self._decayScaleInput = resolvedDecayScale + self._decayScaleIsGenerator = resolvedDecayScale is any Generator + + let n: Int = buffer.count + self._bankSize = n + self._b0 = makeSampleBuffer(n) + self._na1 = makeSampleBuffer(n) + self._na2 = makeSampleBuffer(n) + self._y1 = makeSampleBuffer(n) + self._y2 = makeSampleBuffer(n) + self._newY = makeSampleBuffer(n) + self._tmp = makeSampleBuffer(n) + self._mulAdd = MulAddSpec(mul: mul, add: add) + } + + /// Replace the mode table driving the bank. Pass `nil` to silence the bank (filter + /// state is preserved). + /// + /// The new buffer must have `channelCount == klankSpecChannelCount` (3) and + /// `count == bankSize` (the initial buffer's count) — internal state arrays are sized + /// at init. The previously installed buffer's retain is routed through the engine's + /// buffer-swap kill queue for off-RT release. + public func setBuffer(_ buffer: LyrebirdBuffer?, engine: SynthesisEngine) { + if let buffer: LyrebirdBuffer { + precondition( + buffer.channelCount == klankSpecChannelCount, + "Klank.setBuffer: buffer must have channelCount == \(klankSpecChannelCount), got \(buffer.channelCount)" + ) + precondition( + buffer.count == _bankSize, + "Klank.setBuffer: buffer count must equal initial bank size \(_bankSize), got \(buffer.count)" + ) + } + _slot.swap(buffer, engine: engine) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let n: Int = _bankSize + let inputBlock: [Double] = _inputSource.calculatedSamples(graph: graph, count: count).first ?? [] + let sr: Double = graph.engine.sampleRate + + // Snapshot block-rate modulation. Evaluated unconditionally so any wired + // modulation generator advances its state by `count` samples this block. + let freqScale: Double = lastGeneratorSampleOrFloat( + _freqScaleInput, isGenerator: _freqScaleIsGenerator, graph: graph, count: count) + let freqOffset: Double = lastGeneratorSampleOrFloat( + _freqOffsetInput, isGenerator: _freqOffsetIsGenerator, graph: graph, count: count) + let decayScale: Double = lastGeneratorSampleOrFloat( + _decayScaleInput, isGenerator: _decayScaleIsGenerator, graph: graph, count: count) + + // Slot empty or buffer invalidated → emit silence and hold filter state. + guard let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid else { + _result[0].withUnsafeMutableBufferPointer { buf in + guard let base: UnsafeMutablePointer = buf.baseAddress else { return } + vDSP_vclrD(base, 1, vDSP_Length(count)) + } + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + return _result + } + + // Snapshot per-resonator (freq, amp, decay), apply modulation, recompute coeffs. + let twoPiOverSr: Double = 2.0 * .pi / sr + let recipSr: Double = 1.0 / sr + for k: Int in 0.. = b0p.baseAddress, + let na1Base: UnsafePointer = na1p.baseAddress, + let na2Base: UnsafePointer = na2p.baseAddress, + let y1Base: UnsafeMutablePointer = y1p.baseAddress, + let y2Base: UnsafeMutablePointer = y2p.baseAddress, + let newYBase: UnsafeMutablePointer = newYp.baseAddress, + let tmpBase: UnsafeMutablePointer = tmpp.baseAddress, + let resBase: UnsafeMutablePointer = resBuf.baseAddress + else { return } + + for i: Int in 0.. [[Double]] { + _checkCount(count) + + let sr: Double = graph.engine.sampleRate + + let inputBlock: [Double] = _input.calculatedSamples(graph: graph, count: count).first ?? [] + let inputCount: Int = inputBlock.count + + let (upSamples, scalarUp) = resolveGeneratorOrScalar( + _up, isGenerator: _upIsGenerator, graph: graph, count: count) + let (dnSamples, scalarDn) = resolveGeneratorOrScalar( + _dn, isGenerator: _dnIsGenerator, graph: graph, count: count) + + // Scalar-path per-sample step is block-constant: precompute once. + let scalarUpStep: Double = scalarUp / sr + let scalarDnStep: Double = scalarDn / sr + + var state: Double = _state + var initialized: Bool = _initialized + + for i: Int in 0.. state + upStep { + state += upStep + } else if x < state - dnStep { + state -= dnStep + } else { + state = x + } + _result[0][i] = state + } + + _state = state + _initialized = initialized + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + return _result + } + } + + // MARK: - Control + + /// Control-rate linear slew-rate limiter. Advances one slew step per audio block. + /// + /// Override of `calculatedSamples` bypasses the sub-block loop — the slew step must + /// advance exactly once per audio block. The coefficient is computed at the control rate + /// (`sampleRate / blockSize`); `up` and `dn` remain in units per second and produce the + /// same wall-clock slew time regardless of block size (matching `Lag.Control`). + /// + /// The output block is flat (constant). For smoothly interpolated output, use `Slew.Audio`. + /// + /// - Parameters: + /// - input: Signal to slew-limit. + /// - up: Maximum rising slope in units per second. Defaults to `1.0`. + /// - dn: Maximum falling slope in units per second. Defaults to `1.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Control: _Base, ControlGenerator { + + public var previousOutputValue: Double = 0.0 + + /// - Parameters: + /// - input: Signal to slew-limit. + /// - up: Maximum rising slope in units per second. Defaults to `1.0`. + /// - dn: Maximum falling slope in units per second. Defaults to `1.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + up: any ValidGeneratorInput = 1.0, + dn: any ValidGeneratorInput = 1.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, up: up, dn: dn, mul: mul, add: add) + _setupSubBlockBuffer() + } + + /// Bypass sub-block loop: slew state must advance exactly once per audio block. + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + let controlRate: Double = graph.engine.sampleRate / Double(graph.engine.blockSize) + let x: Double = _input.floatValue(graph: graph) + let upVal: Double = _up.floatValue(graph: graph) + let dnVal: Double = _dn.floatValue(graph: graph) + + if !_initialized { + _state = x + _initialized = true + } else { + let upStep: Double = upVal / controlRate + let dnStep: Double = dnVal / controlRate + if x > _state + upStep { + _state += upStep + } else if x < _state - dnStep { + _state -= dnStep + } else { + _state = x + } + } + + var fillValue: Double = _state + _result[0].withUnsafeMutableBufferPointer { buf in + guard let base: UnsafeMutablePointer = buf.baseAddress else { return } + vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count)) + } + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + guard count > 0 else { return _result } + previousOutputValue = _result[0][count - 1] + return _result + } + } +} + +// MARK: - GeneratorEnum + +extension Slew: GeneratorEnum { + public typealias AudioType = Slew.Audio + public typealias ControlType = Slew.Control +} diff --git a/Sources/Lyrebird/Generators/Oscillators/Klang.swift b/Sources/Lyrebird/Generators/Oscillators/Klang.swift new file mode 100644 index 0000000..31f1579 --- /dev/null +++ b/Sources/Lyrebird/Generators/Oscillators/Klang.swift @@ -0,0 +1,311 @@ +// Klang.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// MARK: - Default sine table (module-level lazy, one per process) + +/// Pre-computed sine table shared by every ``Klang`` instance that does not pass its own +/// table. Initialised once on the first `Klang.Audio` init (non-RT); later accesses — including +/// the RT render callback — are lock-free reads of an already-initialised value. +private let klangDefaultTable: LyrebirdBuffer = { + let buf: LyrebirdBuffer = LyrebirdBuffer(count: lyrebirdDefaultTableSize) + buf.fillSine() + return buf +}() + +/// Number of channels (= per-partial parameters) required by ``Klang``: `freq`, `amp`, +/// `phase`. Each ``LyrebirdBuffer`` frame supplies one partial's parameters. The channel +/// order (`freq, amp, phase`) matches the SuperCollider `Klang` specification triple. +public let klangSpecChannelCount: Int = 3 + +/// Buffer channel index of the partial frequency (Hz). +public let klangFreqChannel: Int = 0 + +/// Buffer channel index of the per-partial amplitude (linear gain). +public let klangAmpChannel: Int = 1 + +/// Buffer channel index of the per-partial initial phase (cycles, `[0, 1)`). Read once at +/// `init` to seed the phase accumulator; ignored on later ``setBuffer(_:engine:)`` swaps. +public let klangPhaseChannel: Int = 2 + +/// Bank of N summed sine partials — the additive-synthesis counterpart of ``Klank``. +/// +/// `Klang` reads a per-partial `[freq, amp, phase]` table from a single ``LyrebirdBuffer`` +/// (`channelCount == 3`, one partial per frame) and outputs the sum of N sine oscillators on +/// one mono channel. Unlike ``Klank`` it takes **no input** — it is a pure source. It exposes +/// the two SuperCollider `Klang` modulation parameters — `freqscale`, `freqoffset` — which +/// scale and shift every partial frequency without re-specifying the table: +/// +/// ``` +/// freq_k_effective = freq_k · freqscale + freqoffset +/// ``` +/// +/// Both are any `ValidGeneratorInput`, snapshotted once per audio block (block-rate / "control +/// rate"). `freq` and `amp` are re-read from the table each block, so live `setValue` edits and +/// whole-table ``setBuffer(_:engine:)`` swaps retune the bank while it sounds. The `phase` +/// channel is **only** read at `init` to seed each partial's running phase accumulator — phases +/// free-run thereafter and are unaffected by later table swaps (so the bank never clicks on a +/// respecification). +/// +/// ## Per-partial synthesis +/// +/// ``` +/// incr_k = freq_k_effective · tableSize / sr // phase advance per sample, table units +/// y[n] = Σ_k amp_k · sineTable[phase_k] // interpolated table read +/// phase_k += incr_k // wrapped into [0, tableSize) +/// ``` +/// +/// `amp` is unclamped (negative inverts phase). `freq_effective` is unclamped (negative +/// frequencies simply run the partial in reverse). +/// +/// ## Usage +/// +/// ```swift +/// let spec = LyrebirdBuffer(count: 4, channelCount: klangSpecChannelCount) +/// // A harmonic stack: [freq, amp, phase] +/// for (i, t) in [ +/// (200.0, 0.50, 0.0), +/// (400.0, 0.25, 0.0), +/// (600.0, 0.12, 0.0), +/// (800.0, 0.06, 0.0), +/// ].enumerated() { +/// spec.setValue(t.0, frame: i, channel: klangFreqChannel) +/// spec.setValue(t.1, frame: i, channel: klangAmpChannel) +/// spec.setValue(t.2, frame: i, channel: klangPhaseChannel) +/// } +/// +/// // Detune the whole stack up a fifth with an envelope. +/// let voice = Klang.Audio(buffer: spec, freqscale: 1.5) +/// ``` +public enum Klang { + + /// Audio-rate additive sine bank with block-rate `freqscale` / `freqoffset` modulation. + /// + /// - Parameters: + /// - buffer: Partial table. Must have `channelCount == 3` and `count >= 1`. Frame `k` + /// provides partial `k`'s `[freq, amp, phase]`. Bank size = `buffer.count`. Live + /// `setValue` writes to `freq`/`amp` are picked up once per audio block; whole-table + /// swap via ``setBuffer(_:engine:)``. The `phase` channel seeds the accumulators at + /// `init` only. + /// - freqscale: Multiplier applied to every partial frequency. Snapshotted per block. + /// Defaults to `1.0`. + /// - freqoffset: Hz added to every partial frequency after scaling. Snapshotted per + /// block. Defaults to `0.0`. + /// - interpolation: Sine-table interpolation mode. Defaults to `.linear`. + /// - table: Sine table (power-of-two size, mono). Defaults to the module-level lazy global. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: GeneratorBase, AudioGenerator { + + // MARK: Inputs + + /// Atomic slot — supports live whole-table swap via ``setBuffer(_:engine:)``. + /// Loaded once per audio block. + private let _slot: RTBufferSlot + + private let _freqScaleInput: any ValidGeneratorInput + private let _freqScaleIsGenerator: Bool + private let _freqOffsetInput: any ValidGeneratorInput + private let _freqOffsetIsGenerator: Bool + + // MARK: Sine table + + private let _sineTable: LyrebirdBuffer + private let _interpolation: TableInterpolation + + // MARK: State (one entry per partial) + + private let _bankSize: Int + /// Per-partial phase in table-index units `[0, tableSize)`. Seeded at init from the + /// spec's `phase` channel; free-runs thereafter. + private var _phase: [Double] + + // MARK: Output + private let _mulAdd: MulAddSpec + + // MARK: Init + + /// - Parameters: + /// - buffer: Partial table. Must have `channelCount == 3` and `count >= 1`. Frame `k` + /// provides partial `k`'s `[freq, amp, phase]`. Bank size = `buffer.count`. Live + /// `setValue` writes to `freq`/`amp` are picked up once per audio block; whole-table + /// swap via ``setBuffer(_:engine:)``. The `phase` channel seeds the accumulators at + /// `init` only. + /// - freqscale: Multiplier applied to every partial frequency. Snapshotted per block. + /// Defaults to `1.0`. + /// - freqoffset: Hz added to every partial frequency after scaling. Snapshotted per + /// block. Defaults to `0.0`. + /// - interpolation: Sine-table interpolation mode. Defaults to `.linear`. + /// - table: Sine table (power-of-two size, mono). Defaults to the module-level lazy global. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public init( + buffer: LyrebirdBuffer, + freqscale: any ValidGeneratorInput = 1.0, + freqoffset: any ValidGeneratorInput = 0.0, + interpolation: TableInterpolation = .linear, + table: LyrebirdBuffer? = nil, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + precondition( + buffer.channelCount == klangSpecChannelCount, + "Klang: buffer must have channelCount == \(klangSpecChannelCount) " + + "(freq, amp, phase); got channelCount=\(buffer.channelCount)" + ) + precondition( + buffer.count >= 1, + "Klang: buffer must have count >= 1; got count=\(buffer.count)" + ) + + let resolvedTable: LyrebirdBuffer = table ?? klangDefaultTable + let tableSize: Int = resolvedTable.count + precondition( + tableSize > 0 && (tableSize & (tableSize - 1)) == 0, + "Klang requires a power-of-two table size; got \(tableSize)." + ) + precondition( + resolvedTable.channelCount == lyrebirdBufferMonoChannelCount, + "Klang requires a mono table (channelCount == 1); got channelCount == \(resolvedTable.channelCount)." + ) + self._sineTable = resolvedTable + self._interpolation = interpolation + self._slot = RTBufferSlot(initial: buffer) + + let resolvedFreqScale: any ValidGeneratorInput = freqscale._resolvedInput() + self._freqScaleInput = resolvedFreqScale + self._freqScaleIsGenerator = resolvedFreqScale is any Generator + let resolvedFreqOffset: any ValidGeneratorInput = freqoffset._resolvedInput() + self._freqOffsetInput = resolvedFreqOffset + self._freqOffsetIsGenerator = resolvedFreqOffset is any Generator + + let n: Int = buffer.count + self._bankSize = n + // Seed per-partial phase (cycles → table-index units, normalised to [0, tableSize)). + let tableSizeFloat: Double = Double(tableSize) + var seededPhase: [Double] = makeSampleBuffer(n) + for k: Int in 0.. [[Double]] { + _checkCount(count) + + let n: Int = _bankSize + let sr: Double = graph.engine.sampleRate + let tableSize: Int = _sineTable.count + let tableSizeFloat: Double = Double(tableSize) + let tableMask: Int = tableSize - 1 + + // Snapshot block-rate modulation. Evaluated unconditionally so any wired + // modulation generator advances its state by `count` samples this block. + let freqScale: Double = lastGeneratorSampleOrFloat( + _freqScaleInput, isGenerator: _freqScaleIsGenerator, graph: graph, count: count) + let freqOffset: Double = lastGeneratorSampleOrFloat( + _freqOffsetInput, isGenerator: _freqOffsetIsGenerator, graph: graph, count: count) + + // Slot empty / buffer invalidated / table invalidated → silence, hold phase. + guard let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), + buffer.isValid, _sineTable.isValid else { + for i: Int in 0.. Double { + var p: Double = phase + increment + if p >= tableSizeFloat { p -= tableSizeFloat } + if p >= tableSizeFloat || p < 0 { + p = p.truncatingRemainder(dividingBy: tableSizeFloat) + if p < 0 { p += tableSizeFloat } + } + return p +} + +// MARK: - GeneratorEnum + +// GeneratorEnum conformance is intentionally omitted — Klang.Audio is Audio-only. +// Each partial advances its phase accumulator every sample, so a control-rate variant would +// need a distinct architecture (per-sample state on a control-rate input is the same as audio +// rate). diff --git a/Sources/Lyrebird/Generators/Oscillators/LFGauss.swift b/Sources/Lyrebird/Generators/Oscillators/LFGauss.swift new file mode 100644 index 0000000..8092b4d --- /dev/null +++ b/Sources/Lyrebird/Generators/Oscillators/LFGauss.swift @@ -0,0 +1,226 @@ +// LFGauss.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +// MARK: - Shared constants + +/// Exponent scale for the Gaussian `exp(-0.5 · (x / width)²)` — i.e. `−1 / (2σ²)` +/// folded into the `(x / width)²` form so `width` reads directly as the standard +/// deviation (in units of the half-period axis `x ∈ [−1, 1]`). +private let lfGaussExponentScale: Double = -0.5 + +/// Lower clamp on `width` to keep the Gaussian exponent finite (avoids divide-by-zero +/// as `width → 0`). +private let lfGaussMinWidth: Double = 1.0e-6 + +/// Lower clamp on `period` (seconds) so the phase increment stays finite. +private let lfGaussMinPeriod: Double = 1.0e-6 + +/// Evaluate the bell value for a normalised phase in `[0, 1)`. +/// +/// Maps `phase` onto the symmetric axis `x = 2·phase − 1 ∈ [−1, 1)` so the peak +/// (`1.0`) lands at the period midpoint (`phase = 0.5`) and the troughs at the +/// period boundaries. `width` is the standard deviation on that axis. +@inline(__always) +private func lfGaussValue(phase: Double, width: Double) -> Double { + let w: Double = max(width, lfGaussMinWidth) + let x: Double = 2.0 * phase - 1.0 + let a: Double = x / w + return exp(lfGaussExponentScale * a * a) +} + +// MARK: - LFGauss + +/// Gaussian bell-shaped oscillator. Raw output in `(0, 1]` (before `mul` / `add`). +/// +/// Over each `period` the output traces a Gaussian bell: near `0` at the period +/// boundaries, peaking at `1.0` at the period midpoint. `width` is the standard +/// deviation as a fraction of the half-period (smaller → narrower spike). A smooth +/// non-band-limited LFO and a ready-made grain-window shape. +/// +/// ``` +/// x = 2·phase − 1 (phase ∈ [0, 1) advances 1 / (period · sr) per sample) +/// out = exp(−0.5 · (x / width)²) +/// ``` +/// +/// - Parameters: +/// - period: Bell period in seconds. Clamped to a small positive minimum. Accepts generator input. +/// - width: Standard deviation as a fraction of the half-period. Smaller → narrower. Defaults to `0.1`. +/// - phase: Initial phase offset in normalized cycles `[0, 1)`. `0` starts at a trough. Defaults to `0.0`. +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum LFGauss { + + // MARK: - _Base + + /// Shared state for `LFGauss.Audio` and `LFGauss.Control`. + public class _Base: GeneratorBase { + let periodInput: any ValidGeneratorInput + let widthInput: any ValidGeneratorInput + let periodIsGenerator: Bool + let widthIsGenerator: Bool + var _phase: Double + var _mulAdd: MulAddSpec + + init( + period: any ValidGeneratorInput, + width: any ValidGeneratorInput, + phase: Double, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedPeriod: any ValidGeneratorInput = period._resolvedInput() + let resolvedWidth: any ValidGeneratorInput = width._resolvedInput() + self.periodInput = resolvedPeriod + self.widthInput = resolvedWidth + self.periodIsGenerator = resolvedPeriod is any Generator + self.widthIsGenerator = resolvedWidth is any Generator + var p: Double = phase.truncatingRemainder(dividingBy: 1.0) + if p < 0 { p += 1.0 } + self._phase = p + self._mulAdd = MulAddSpec(mul: mul, add: add) + } + } + + // MARK: - Audio + + /// Audio-rate Gaussian oscillator. Evaluates `period` / `width` per sample. + /// + /// - Parameters: + /// - period: Bell period in seconds. Clamped to a small positive minimum. Accepts generator input. + /// - width: Standard deviation as a fraction of the half-period. Smaller → narrower. Defaults to `0.1`. + /// - phase: Initial phase offset in normalized cycles `[0, 1)`. `0` starts at a trough. Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - period: Bell period in seconds. Clamped to a small positive minimum. Accepts generator input. + /// - width: Standard deviation as a fraction of the half-period. Smaller → narrower. Defaults to `0.1`. + /// - phase: Initial phase offset in normalized cycles `[0, 1)`. `0` starts at a trough. Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + period: any ValidGeneratorInput, + width: any ValidGeneratorInput = 0.1, + phase: Double = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(period: period, width: width, phase: phase, mul: mul, add: add) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + let sampleRate: Double = Double(graph.engine.sampleRate) + + let periodSamples: [Double]? + let scalarDt: Double + if periodIsGenerator { + periodSamples = periodInput.calculatedSamples(graph: graph, count: count).first + scalarDt = 0 + } else { + periodSamples = nil + scalarDt = 1.0 / (max(periodInput.floatValue(graph: graph), lfGaussMinPeriod) * sampleRate) + } + + let (widthSamples, scalarWidth) = resolveGeneratorOrScalar( + widthInput, isGenerator: widthIsGenerator, graph: graph, count: count) + + for i: Int in 0.. [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + let sampleRate: Double = Double(graph.engine.sampleRate) + let countFloat: Double = Double(count) + let period: Double = max(periodInput.floatValue(graph: graph), lfGaussMinPeriod) + let width: Double = widthInput.floatValue(graph: graph) + + let dt: Double = 1.0 / (period * sampleRate) + _phase += dt * countFloat + normalizeOscPhase(&_phase) + + let target: Double = lfGaussValue(phase: _phase, width: width) + let rampStart: Double = _rampTarget + _rampTarget = target + previousOutputValue = fillRampedResult( + into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) + return _result + } + } +} + +// MARK: - GeneratorEnum + +extension LFGauss: GeneratorEnum { + public typealias AudioType = LFGauss.Audio + public typealias ControlType = LFGauss.Control +} diff --git a/Sources/Lyrebird/Generators/Oscillators/OscSin.swift b/Sources/Lyrebird/Generators/Oscillators/OscSin.swift index f41e418..3b2de52 100644 --- a/Sources/Lyrebird/Generators/Oscillators/OscSin.swift +++ b/Sources/Lyrebird/Generators/Oscillators/OscSin.swift @@ -42,16 +42,11 @@ fileprivate func sinTableRead( case .cubic: let intPhase: Int = Int(phase) let t: Double = phase - Double(intPhase) - let t2: Double = t * t - let t3: Double = t2 * t let pM1: Double = table[(intPhase - 1) & tableMask] let p0: Double = table[intPhase & tableMask] let p1: Double = table[(intPhase + 1) & tableMask] let p2: Double = table[(intPhase + 2) & tableMask] - return 0.5 * ((2 * p0) - + (-pM1 + p1) * t - + (2*pM1 - 5*p0 + 4*p1 - p2) * t2 - + (-pM1 + 3*p0 - 3*p1 + p2) * t3) + return catmullRomCubic(pM1, p0, p1, p2, t: t) } } @@ -249,16 +244,11 @@ public enum OscSin { for i: Int in 0.. Double { let intPhase: Int = Int(phase) let t: Double = phase - Double(intPhase) - let t2: Double = t * t - let t3: Double = t2 * t let pM1: Double = table[(intPhase - 1 + tableSize) % tableSize] let p0: Double = table[intPhase % tableSize] let p1: Double = table[(intPhase + 1) % tableSize] let p2: Double = table[(intPhase + 2) % tableSize] - return 0.5 * ((2 * p0) - + (-pM1 + p1) * t - + (2 * pM1 - 5 * p0 + 4 * p1 - p2) * t2 - + (-pM1 + 3 * p0 - 3 * p1 + p2) * t3) + return catmullRomCubic(pM1, p0, p1, p2, t: t) } /// Combined dispatcher — picks the right interpolated read for `interpolation`. @@ -121,16 +116,11 @@ internal func oscillatorTableReadCubic( ) -> Double { let intPhase: Int = Int(phase) let t: Double = phase - Double(intPhase) - let t2: Double = t * t - let t3: Double = t2 * t let pM1: Double = table[(intPhase - 1 + tableSize) % tableSize] let p0: Double = table[intPhase % tableSize] let p1: Double = table[(intPhase + 1) % tableSize] let p2: Double = table[(intPhase + 2) % tableSize] - return 0.5 * ((2 * p0) - + (-pM1 + p1) * t - + (2 * pM1 - 5 * p0 + 4 * p1 - p2) * t2 - + (-pM1 + 3 * p0 - 3 * p1 + p2) * t3) + return catmullRomCubic(pM1, p0, p1, p2, t: t) } @inline(__always) diff --git a/Sources/Lyrebird/Generators/Oscillators/Phasor.swift b/Sources/Lyrebird/Generators/Oscillators/Phasor.swift new file mode 100644 index 0000000..2b1d438 --- /dev/null +++ b/Sources/Lyrebird/Generators/Oscillators/Phasor.swift @@ -0,0 +1,318 @@ +// Phasor.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// File-scope zero-fill block — used as the `??` fallback when the trigger +/// input generator returns an empty channel array. +private let phasorZeroBlock: [Double] = [Double]( + repeating: 0, + count: lyrebirdDefaultResultBufferSize +) + +/// Linear phase accumulator (ramp generator). Equivalent to SuperCollider `Phasor`. +/// +/// Accumulates `rate` units per sample within the half-open range `[start, end)`. On a +/// ≤0 → >0 rising edge of `trig`, phase resets to `resetPos` at that exact sample. When +/// the phase would exceed `end` or fall below `start`, it wraps using +/// `truncatingRemainder(dividingBy: span)` — safe for any rate including values larger +/// than the span. +/// +/// `rate` is a **per-sample increment**, not a frequency in Hz. To scan a wavetable +/// of length `N` at a pitch of `freq` Hz, pass `rate = freq * N / sampleRate`. +/// +/// ## Usage +/// ```swift +/// // Default: ramp 0..1 at 1.0/sample (single-sample wrap). +/// Phasor.Audio() +/// +/// // Table scan: 1024-sample wavetable at 440 Hz, 44100 Hz sample rate. +/// let tableSize: Double = 1024.0 +/// Phasor.Audio(rate: 440.0 * tableSize / 44100.0, start: 0, end: tableSize) +/// +/// // Reset on impulse trigger. +/// Phasor.Audio(trig: Impulse.Audio(freq: 2.0), rate: 0.01, resetPos: 0.25) +/// ``` +/// +/// - Parameters: +/// - trig: Trigger signal. ≤0 → >0 rising edges reset phase to `resetPos`. Defaults to `0.0` (never triggers). +/// - rate: Per-sample phase increment (not Hz). Negative values ramp downward. Defaults to `1.0`. +/// - start: Lower bound of the output range (inclusive). Defaults to `0.0`. +/// - end: Upper bound of the output range (exclusive). Defaults to `1.0`. +/// - resetPos: Phase value to jump to on each rising edge of `trig`. Defaults to `0.0`. +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum Phasor { + + // MARK: - Shared base + + /// Shared stored properties and initialiser for `Phasor.Audio` and `Phasor.Control`. + public class _Base: GeneratorBase { + let _trig: any ValidGeneratorInput + let _rate: any ValidGeneratorInput + let _start: any ValidGeneratorInput + let _end: any ValidGeneratorInput + let _resetPos: any ValidGeneratorInput + let _mulAdd: MulAddSpec + let _rateIsGenerator: Bool + let _startIsGenerator: Bool + let _endIsGenerator: Bool + let _resetPosIsGenerator: Bool + + /// Accumulated phase. Starts uninitialised — lazy init on first block so the initial + /// value is taken from `start` at render time, which may itself be a generator. + var _phase: Double = 0.0 + var _prevTrig: Double = 0.0 + var _initialized: Bool = false + + init( + trig: any ValidGeneratorInput, + rate: any ValidGeneratorInput, + start: any ValidGeneratorInput, + end: any ValidGeneratorInput, + resetPos: any ValidGeneratorInput, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedTrig: any ValidGeneratorInput = trig._resolvedInput() + let resolvedRate: any ValidGeneratorInput = rate._resolvedInput() + let resolvedStart: any ValidGeneratorInput = start._resolvedInput() + let resolvedEnd: any ValidGeneratorInput = end._resolvedInput() + let resolvedResetPos: any ValidGeneratorInput = resetPos._resolvedInput() + _trig = resolvedTrig + _rate = resolvedRate + _start = resolvedStart + _end = resolvedEnd + _resetPos = resolvedResetPos + _rateIsGenerator = resolvedRate is any Generator + _startIsGenerator = resolvedStart is any Generator + _endIsGenerator = resolvedEnd is any Generator + _resetPosIsGenerator = resolvedResetPos is any Generator + _mulAdd = MulAddSpec(mul: mul, add: add) + super.init() + } + } + + // MARK: - Audio + + /// Audio-rate linear phase accumulator. Evaluates all inputs per sample. + /// + /// - Parameters: + /// - trig: Trigger signal. ≤0 → >0 rising edges reset phase to `resetPos`. Defaults to `0.0`. + /// - rate: Per-sample phase increment (not Hz). Negative values ramp downward. Defaults to `1.0`. + /// - start: Lower bound of the output range (inclusive). Defaults to `0.0`. + /// - end: Upper bound of the output range (exclusive). Defaults to `1.0`. + /// - resetPos: Phase value on each rising trigger edge. Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - trig: Trigger signal. ≤0 → >0 rising edges reset phase to `resetPos`. Defaults to `0.0`. + /// - rate: Per-sample phase increment (not Hz). Negative values ramp downward. Defaults to `1.0`. + /// - start: Lower bound of the output range (inclusive). Defaults to `0.0`. + /// - end: Upper bound of the output range (exclusive). Defaults to `1.0`. + /// - resetPos: Phase value on each rising trigger edge. Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + trig: any ValidGeneratorInput = 0.0, + rate: any ValidGeneratorInput = 1.0, + start: any ValidGeneratorInput = 0.0, + end: any ValidGeneratorInput = 1.0, + resetPos: any ValidGeneratorInput = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(trig: trig, rate: rate, start: start, end: end, resetPos: resetPos, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + // Trig input is always evaluated at audio rate — scanning for rising edges + // requires the full per-sample block, not just a scalar value. + let trigBlock: [Double] = _trig.calculatedSamples(graph: graph, count: count).first + ?? phasorZeroBlock + let trigCount: Int = trigBlock.count + + // Continuous-valued inputs resolved via the shared helper (tuple-destructure is + // the CLAUDE.md-documented exception to the explicit-type-annotation rule). + let (rateSamples, scalarRate) = resolveGeneratorOrScalar( + _rate, isGenerator: _rateIsGenerator, graph: graph, count: count) + let (startSamples, scalarStart) = resolveGeneratorOrScalar( + _start, isGenerator: _startIsGenerator, graph: graph, count: count) + let (endSamples, scalarEnd) = resolveGeneratorOrScalar( + _end, isGenerator: _endIsGenerator, graph: graph, count: count) + let (resetPosSamples, scalarResetPos) = resolveGeneratorOrScalar( + _resetPos, isGenerator: _resetPosIsGenerator, graph: graph, count: count) + + var prevTrig: Double = _prevTrig + var initialized: Bool = _initialized + var phase: Double = _phase + + for i: Int in 0.. 0 && prevTrig <= 0 { + phase = rp + } + prevTrig = t + + _result[0][i] = phase + + // Advance phase by rate. + phase += r + + // Wrap phase into [s, e). + let span: Double = e - s + if span > 0 { + if phase >= e || phase < s { + phase = s + (phase - s).truncatingRemainder(dividingBy: span) + if phase < s { phase += span } + } + } + } + + _phase = phase + _prevTrig = prevTrig + _initialized = initialized + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + return _result + } + } + + // MARK: - Control + + /// Control-rate linear phase accumulator. Advances phase once per audio block. + /// + /// Override of `calculatedSamples` bypasses the sub-block loop — phase must advance + /// exactly once per audio block regardless of `controlBlockSize`. When the accumulator + /// wraps mid-block at control rate, the ramp output will exhibit a backward artifact on + /// the wrap block; this is an accepted control-rate limitation identical to + /// `LFSawtooth.Control`. + /// + /// - Parameters: + /// - trig: Trigger signal. ≤0 → >0 edges in the full block reset phase to `resetPos`. Defaults to `0.0`. + /// - rate: Per-sample phase increment (not Hz). Defaults to `1.0`. + /// - start: Lower bound of the output range (inclusive). Defaults to `0.0`. + /// - end: Upper bound of the output range (exclusive). Defaults to `1.0`. + /// - resetPos: Phase value on a rising trigger edge. Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Control: _Base, ControlGenerator { + + public var previousOutputValue: Double = 0.0 + private var _rampTarget: Double = 0.0 + + /// - Parameters: + /// - trig: Trigger signal. ≤0 → >0 edges in the full block reset phase to `resetPos`. Defaults to `0.0`. + /// - rate: Per-sample phase increment (not Hz). Defaults to `1.0`. + /// - start: Lower bound of the output range (inclusive). Defaults to `0.0`. + /// - end: Upper bound of the output range (exclusive). Defaults to `1.0`. + /// - resetPos: Phase value on a rising trigger edge. Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + trig: any ValidGeneratorInput = 0.0, + rate: any ValidGeneratorInput = 1.0, + start: any ValidGeneratorInput = 0.0, + end: any ValidGeneratorInput = 1.0, + resetPos: any ValidGeneratorInput = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(trig: trig, rate: rate, start: start, end: end, resetPos: resetPos, mul: mul, add: add) + _setupSubBlockBuffer() + } + + /// Bypass sub-block loop: phase must advance exactly once per audio block. + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + // Read scalar values via floatValue (control-rate). + let rate: Double = _rate.floatValue(graph: graph) + let start: Double = _start.floatValue(graph: graph) + let end: Double = _end.floatValue(graph: graph) + let resetPos: Double = _resetPos.floatValue(graph: graph) + + // Scan the full trig block once per audio block for any rising edge. + // Always call calculatedSamples so Closure inputs (tests) and AudioGenerator + // inputs both deliver per-sample trigger data. + let trigBlock: [Double] = _trig.calculatedSamples(graph: graph, count: count).first + ?? phasorZeroBlock + let trigCount: Int = trigBlock.count + + if !_initialized { + _phase = start + _initialized = true + } + + var prevTrig: Double = _prevTrig + var didReset: Bool = false + for i: Int in 0.. 0 && prevTrig <= 0 { + didReset = true + } + prevTrig = t + } + _prevTrig = prevTrig + + if didReset { + _phase = resetPos + } + + // Advance phase by rate * count (one audio-block step). + _phase += rate * Double(count) + + // Wrap phase into [start, end). + let span: Double = end - start + if span > 0 { + if _phase >= end || _phase < start { + _phase = start + (_phase - start).truncatingRemainder(dividingBy: span) + if _phase < start { _phase += span } + } + } + + let target: Double = _phase + + let rampStart: Double = _rampTarget + _rampTarget = target + guard count > 0 else { return _result } + previousOutputValue = fillRampedResult( + into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) + return _result + } + } +} + +extension Phasor: GeneratorEnum { + public typealias AudioType = Phasor.Audio + public typealias ControlType = Phasor.Control +} diff --git a/Sources/Lyrebird/Generators/Routing/CrossFade.swift b/Sources/Lyrebird/Generators/Routing/CrossFade.swift new file mode 100644 index 0000000..20154d2 --- /dev/null +++ b/Sources/Lyrebird/Generators/Routing/CrossFade.swift @@ -0,0 +1,221 @@ +// CrossFade.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Darwin + +/// Half-pi constant for CrossFade equal-power gain derivation. +private let crossFadeHalfPi: Double = .pi / 2 + +// MARK: - CrossFade + +/// Equal-power crossfade between two inputs. Equivalent to SuperCollider `XFade2`. +/// +/// Crossfades between `inA` and `inB` using an equal-power curve derived from a quarter- +/// sine/cosine pair. `mul` plays the role of SC's `level` argument (overall output gain). +/// +/// **Mono only.** Operates on channel 0 of each input; multichannel support is deferred. +/// +/// Equal-power gain derivation: +/// - Map `p = clamp(pan + 1, 0, 2) * 0.5` so `p ∈ [0, 1]`. +/// - `gainA = cos(p × π/2)`, `gainB = sin(p × π/2)`. +/// - At `pan = -1`: A full, B silent. At `pan = +1`: A silent, B full. +/// - At `pan = 0`: both at `cos(π/4) = √2/2 ≈ 0.7071` — equal-power invariant +/// `gainA² + gainB² = 1` holds at every `pan` value. +/// +/// ```swift +/// // Crossfade between two oscillators — generator pan input for smooth sweep. +/// let xfade = CrossFade.Audio(inA: osc1, inB: osc2, pan: modLFO) +/// ``` +/// +/// - Parameters: +/// - inA: First input signal. +/// - inB: Second input signal. +/// - pan: Crossfade position in `[-1, 1]`. `-1` = full `inA`; `+1` = full `inB`. +/// Values outside `[-1, 1]` are clamped. Defaults to `0.0`. +/// - mul: Output multiplier (SC `level`). Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum CrossFade { + + // MARK: - Shared base + + /// Shared stored properties for `CrossFade.Audio` and `CrossFade.Control`. + public class _Base: GeneratorBase { + let _inA: any ValidGeneratorInput + let _inB: any ValidGeneratorInput + let _panInput: any ValidGeneratorInput + let _inAIsGenerator: Bool + let _inBIsGenerator: Bool + let _panIsGenerator: Bool + let _mulAdd: MulAddSpec + + init( + inA: any ValidGeneratorInput, + inB: any ValidGeneratorInput, + pan: any ValidGeneratorInput, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedA: any ValidGeneratorInput = inA._resolvedInput() + let resolvedB: any ValidGeneratorInput = inB._resolvedInput() + let resolvedPan: any ValidGeneratorInput = pan._resolvedInput() + _inA = resolvedA + _inB = resolvedB + _panInput = resolvedPan + _inAIsGenerator = resolvedA is any Generator + _inBIsGenerator = resolvedB is any Generator + _panIsGenerator = resolvedPan is any Generator + _mulAdd = MulAddSpec(mul: mul, add: add) + } + } + + // MARK: - Audio rate + + /// Audio-rate equal-power crossfade between two inputs. + /// + /// When `pan` is a scalar, gains are computed once per block. When `pan` is a generator, + /// gains are computed per sample via `sampleOrFallback`. + /// + /// - Parameters: + /// - inA: First input signal. + /// - inB: Second input signal. + /// - pan: Crossfade position in `[-1, 1]`. `-1` = full `inA`; `+1` = full `inB`. + /// Values outside `[-1, 1]` are clamped. Defaults to `0.0`. + /// - mul: Output multiplier (SC `level`). Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - inA: First input signal. + /// - inB: Second input signal. + /// - pan: Crossfade position in `[-1, 1]`. `-1` = full `inA`; `+1` = full `inB`. + /// Values outside `[-1, 1]` are clamped. Defaults to `0.0`. + /// - mul: Output multiplier (SC `level`). Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + inA: any ValidGeneratorInput, + inB: any ValidGeneratorInput, + pan: any ValidGeneratorInput = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(inA: inA, inB: inB, pan: pan, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let (aSamples, aScalar) = resolveGeneratorOrScalar( + _inA, isGenerator: _inAIsGenerator, graph: graph, count: count) + let (bSamples, bScalar) = resolveGeneratorOrScalar( + _inB, isGenerator: _inBIsGenerator, graph: graph, count: count) + let (panSamples, panScalar) = resolveGeneratorOrScalar( + _panInput, isGenerator: _panIsGenerator, graph: graph, count: count) + + if panSamples == nil { + // Scalar pan: compute gains once for the whole block. + let clampedPan: Double = Swift.max(-1.0, Swift.min(1.0, panScalar)) + let p: Double = (clampedPan + 1.0) * 0.5 + let gainA: Double = cos(p * crossFadeHalfPi) + let gainB: Double = sin(p * crossFadeHalfPi) + for i: Int in 0.. [[Double]] { + _checkCount(count) + + let a: Double = _inA.floatValue(graph: graph) + let b: Double = _inB.floatValue(graph: graph) + let rawPan: Double = _panInput.floatValue(graph: graph) + let clampedPan: Double = Swift.max(-1.0, Swift.min(1.0, rawPan)) + let p: Double = (clampedPan + 1.0) * 0.5 + let gainA: Double = cos(p * crossFadeHalfPi) + let gainB: Double = sin(p * crossFadeHalfPi) + var target: Double = a * gainA + b * gainB + if !_mulAdd.isIdentity { + target = target * _mulAdd.mulInput.floatValue(graph: graph) + + _mulAdd.addInput.floatValue(graph: graph) + } + fillScalarRampedResult( + into: &_result, + previousOutputValue: &previousOutputValue, + target: target, + count: count + ) + return _result + } + + public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } + } +} + +// MARK: - GeneratorEnum + +extension CrossFade: GeneratorEnum { + public typealias AudioType = CrossFade.Audio + public typealias ControlType = CrossFade.Control +} diff --git a/Sources/Lyrebird/Generators/Routing/LinearCrossFade.swift b/Sources/Lyrebird/Generators/Routing/LinearCrossFade.swift new file mode 100644 index 0000000..baa9107 --- /dev/null +++ b/Sources/Lyrebird/Generators/Routing/LinearCrossFade.swift @@ -0,0 +1,211 @@ +// LinearCrossFade.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// MARK: - LinearCrossFade + +/// Linear crossfade between two inputs. Equivalent to SuperCollider `LinXFade2`. +/// +/// Crossfades between `inA` and `inB` using a linear (constant-power-sum) curve. +/// `mul` plays the role of SC's `level` argument (overall output gain). +/// +/// **Mono only.** Operates on channel 0 of each input; multichannel support is deferred. +/// +/// Linear gain derivation: +/// - `gainA = (1 − pan) * 0.5`, `gainB = (1 + pan) * 0.5`, where `pan ∈ [−1, 1]`. +/// - At `pan = −1`: A full (1.0), B silent (0.0). At `pan = +1`: A silent, B full. +/// - At `pan = 0`: both at `0.5` — sum invariant `gainA + gainB = 1` holds everywhere. +/// +/// ```swift +/// // Linear crossfade between two oscillators. +/// let xfade = LinearCrossFade.Audio(inA: osc1, inB: osc2, pan: 0.3) +/// ``` +/// +/// - Parameters: +/// - inA: First input signal. +/// - inB: Second input signal. +/// - pan: Crossfade position in `[-1, 1]`. `-1` = full `inA`; `+1` = full `inB`. +/// Values outside `[-1, 1]` are clamped. Defaults to `0.0`. +/// - mul: Output multiplier (SC `level`). Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum LinearCrossFade { + + // MARK: - Shared base + + /// Shared stored properties for `LinearCrossFade.Audio` and `LinearCrossFade.Control`. + public class _Base: GeneratorBase { + let _inA: any ValidGeneratorInput + let _inB: any ValidGeneratorInput + let _panInput: any ValidGeneratorInput + let _inAIsGenerator: Bool + let _inBIsGenerator: Bool + let _panIsGenerator: Bool + let _mulAdd: MulAddSpec + + init( + inA: any ValidGeneratorInput, + inB: any ValidGeneratorInput, + pan: any ValidGeneratorInput, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedA: any ValidGeneratorInput = inA._resolvedInput() + let resolvedB: any ValidGeneratorInput = inB._resolvedInput() + let resolvedPan: any ValidGeneratorInput = pan._resolvedInput() + _inA = resolvedA + _inB = resolvedB + _panInput = resolvedPan + _inAIsGenerator = resolvedA is any Generator + _inBIsGenerator = resolvedB is any Generator + _panIsGenerator = resolvedPan is any Generator + _mulAdd = MulAddSpec(mul: mul, add: add) + } + } + + // MARK: - Audio rate + + /// Audio-rate linear crossfade between two inputs. + /// + /// When `pan` is a scalar, gains are computed once per block. When `pan` is a generator, + /// gains are computed per sample via the generator block. + /// + /// - Parameters: + /// - inA: First input signal. + /// - inB: Second input signal. + /// - pan: Crossfade position in `[-1, 1]`. `-1` = full `inA`; `+1` = full `inB`. + /// Values outside `[-1, 1]` are clamped. Defaults to `0.0`. + /// - mul: Output multiplier (SC `level`). Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - inA: First input signal. + /// - inB: Second input signal. + /// - pan: Crossfade position in `[-1, 1]`. `-1` = full `inA`; `+1` = full `inB`. + /// Values outside `[-1, 1]` are clamped. Defaults to `0.0`. + /// - mul: Output multiplier (SC `level`). Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + inA: any ValidGeneratorInput, + inB: any ValidGeneratorInput, + pan: any ValidGeneratorInput = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(inA: inA, inB: inB, pan: pan, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let (aSamples, aScalar) = resolveGeneratorOrScalar( + _inA, isGenerator: _inAIsGenerator, graph: graph, count: count) + let (bSamples, bScalar) = resolveGeneratorOrScalar( + _inB, isGenerator: _inBIsGenerator, graph: graph, count: count) + let (panSamples, panScalar) = resolveGeneratorOrScalar( + _panInput, isGenerator: _panIsGenerator, graph: graph, count: count) + + if panSamples == nil { + // Scalar pan: compute gains once for the whole block. + let clampedPan: Double = Swift.max(-1.0, Swift.min(1.0, panScalar)) + let gainA: Double = (1.0 - clampedPan) * 0.5 + let gainB: Double = (1.0 + clampedPan) * 0.5 + for i: Int in 0.. [[Double]] { + _checkCount(count) + + let a: Double = _inA.floatValue(graph: graph) + let b: Double = _inB.floatValue(graph: graph) + let rawPan: Double = _panInput.floatValue(graph: graph) + let clampedPan: Double = Swift.max(-1.0, Swift.min(1.0, rawPan)) + let gainA: Double = (1.0 - clampedPan) * 0.5 + let gainB: Double = (1.0 + clampedPan) * 0.5 + var target: Double = a * gainA + b * gainB + if !_mulAdd.isIdentity { + target = target * _mulAdd.mulInput.floatValue(graph: graph) + + _mulAdd.addInput.floatValue(graph: graph) + } + fillScalarRampedResult( + into: &_result, + previousOutputValue: &previousOutputValue, + target: target, + count: count + ) + return _result + } + + public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } + } +} + +// MARK: - GeneratorEnum + +extension LinearCrossFade: GeneratorEnum { + public typealias AudioType = LinearCrossFade.Audio + public typealias ControlType = LinearCrossFade.Control +} diff --git a/Sources/Lyrebird/Generators/Routing/Select.swift b/Sources/Lyrebird/Generators/Routing/Select.swift new file mode 100644 index 0000000..47c7d1b --- /dev/null +++ b/Sources/Lyrebird/Generators/Routing/Select.swift @@ -0,0 +1,222 @@ +// Select.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// File-scope zero-fill block for Select — fallback when upstream returns no channel. +private let selectZeroBlock: [Double] = [Double]( + repeating: 0, + count: lyrebirdDefaultResultBufferSize +) + +// MARK: - Select + +/// Index-selected N-input switch. Equivalent to SuperCollider `Select`. +/// +/// Outputs the input at integer index `which` (truncated toward zero, clamped to +/// `[0, N−1]`). All inputs are pulled every block so their internal state advances — +/// SC semantics. Mono output (channel 0 of each input is used). +/// +/// **SC parity note:** in SuperCollider `Select` all inputs are evaluated every block +/// regardless of which is selected. This keeps sequenced and modulated sources in sync +/// when switching between them. Lyrebird preserves this behaviour. +/// +/// ```swift +/// // Switch between three oscillators. +/// let sel = Select.Audio(which: lfo, inputs: [osc1, osc2, osc3]) +/// ``` +/// +/// - Parameters: +/// - which: Input index. Truncated toward zero; clamped to `[0, N−1]`. Can be a +/// generator for per-sample switching (audio rate) or block-rate switching (control rate). +/// - inputs: Array of signal sources. Must contain at least one element. +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum Select { + + // MARK: - Shared base + + /// Shared stored properties for `Select.Audio` and `Select.Control`. + public class _Base: GeneratorBase { + let _inputs: [any ValidGeneratorInput] + let _whichInput: any ValidGeneratorInput + let _whichIsGenerator: Bool + /// Per-input generator classification, resolved at `init` time. `true` when the + /// corresponding element of `_inputs` is an `any Generator`; `false` for scalar / + /// Closure inputs. Classified on the resolved value — never queried on the RT thread. + let _inputIsGenerator: [Bool] + let _inputCount: Int + let _mulAdd: MulAddSpec + + /// Pre-allocated per-input scratch rows: `_inputCount` rows of + /// `lyrebirdDefaultResultBufferSize` each. Populated in `_computeSamples` before + /// the output loop; never resized on the RT thread. + var _scratch: [[Double]] + + init( + which: any ValidGeneratorInput, + inputs: [any ValidGeneratorInput], + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + precondition(!inputs.isEmpty, "Select requires at least one input") + let resolvedWhich: any ValidGeneratorInput = which._resolvedInput() + let resolvedInputs: [any ValidGeneratorInput] = inputs.map { $0._resolvedInput() } + _whichInput = resolvedWhich + _whichIsGenerator = resolvedWhich is any Generator + _inputs = resolvedInputs + _inputIsGenerator = resolvedInputs.map { $0 is any Generator } + _inputCount = resolvedInputs.count + _mulAdd = MulAddSpec(mul: mul, add: add) + _scratch = makeResultBuffer(channels: resolvedInputs.count) + } + } + + // MARK: - Audio rate + + /// Audio-rate N-input index switch. + /// + /// All inputs are pulled every block (SC semantics). Per-sample `which` selects the + /// source index at audio rate. Non-integer `which` truncates toward zero. + /// + /// - Parameters: + /// - which: Input index. Truncated toward zero; clamped to `[0, N−1]`. + /// - inputs: Array of signal sources. Must contain at least one element. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - which: Input index. Truncated toward zero; clamped to `[0, N−1]`. + /// - inputs: Array of signal sources. Must contain at least one element. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + which: any ValidGeneratorInput, + inputs: [any ValidGeneratorInput], + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(which: which, inputs: inputs, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + // Pull all inputs (SC semantics: every input advances every block). + // Generator inputs: calculatedSamples — copy channel 0 into scratch via pointer. + // Scalar/Closure inputs: floatValue — fill scratch row with the scalar (no alloc). + for k: Int in 0..<_inputCount { + if _inputIsGenerator[k] { + let srcBlock: [Double] = _inputs[k].calculatedSamples( + graph: graph, count: count).first ?? selectZeroBlock + srcBlock.withUnsafeBufferPointer { srcBuf in + guard let srcBase: UnsafePointer = srcBuf.baseAddress else { return } + _scratch[k].withUnsafeMutableBufferPointer { dstBuf in + guard let dstBase: UnsafeMutablePointer = dstBuf.baseAddress + else { return } + dstBase.update(from: srcBase, count: count) + } + } + } else { + let scalar: Double = _inputs[k].floatValue(graph: graph) + _scratch[k].withUnsafeMutableBufferPointer { dstBuf in + guard let dstBase: UnsafeMutablePointer = dstBuf.baseAddress + else { return } + for i: Int in 0.. [[Double]] { + _checkCount(count) + + // Pull all inputs via floatValue (advances state, SC semantics). + // Cache values so we can re-read the selected one without a second floatValue call. + for k: Int in 0..<_inputCount { + _scratch[k][0] = _inputs[k].floatValue(graph: graph) + } + + let lastIdx: Int = _inputCount - 1 + let rawIdx: Double = _whichInput.floatValue(graph: graph) + let idx: Int = Swift.max(0, Swift.min(lastIdx, Int(rawIdx))) + var target: Double = _scratch[idx][0] + if !_mulAdd.isIdentity { + target = target * _mulAdd.mulInput.floatValue(graph: graph) + + _mulAdd.addInput.floatValue(graph: graph) + } + fillScalarRampedResult( + into: &_result, + previousOutputValue: &previousOutputValue, + target: target, + count: count + ) + return _result + } + + public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } + } +} + +// MARK: - GeneratorEnum + +extension Select: GeneratorEnum { + public typealias AudioType = Select.Audio + public typealias ControlType = Select.Control +} diff --git a/Sources/Lyrebird/Generators/Triggers/PulseCount.swift b/Sources/Lyrebird/Generators/Triggers/PulseCount.swift new file mode 100644 index 0000000..4553824 --- /dev/null +++ b/Sources/Lyrebird/Generators/Triggers/PulseCount.swift @@ -0,0 +1,221 @@ +// PulseCount.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// File-scope zero-fill block — used as the `??` fallback when an upstream +/// generator returns an empty channel array. +private let pulseCountZeroBlock: [Double] = [Double]( + repeating: 0, + count: lyrebirdDefaultResultBufferSize +) + +/// Trigger-edge running counter. +/// +/// Increments an internal counter by `1` on each ≤0 → >0 rising edge of `trig`. +/// A rising edge of `reset` clears the counter to `0.0` before any `trig` +/// increment at the same sample. The counter is never clamped — it grows without +/// bound as long as triggers arrive. +/// +/// SC equivalent: `PulseCount`. +/// +/// ```swift +/// // Count impulses; use with Stepper for a step-sequencer index. +/// let clock = Impulse.Audio(freq: 4.0) +/// let reset = Impulse.Audio(freq: 0.5) +/// let idx = PulseCount.Audio(trig: clock, reset: reset) +/// ``` +/// +/// - Parameters: +/// - trig: Trigger signal. ≤0 → >0 edges increment the counter. +/// - reset: Reset signal. ≤0 → >0 edges clear the counter to `0.0` before the `trig` +/// increment at that sample. Defaults to `0.0` (never resets). +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum PulseCount { + + // MARK: - Shared base + + public class _Base: GeneratorBase { + let _trigInput: any ValidGeneratorInput + let _resetInput: any ValidGeneratorInput + let _mulAdd: MulAddSpec + + var _count: Double = 0.0 + var _prevTrig: Double = 0.0 + var _prevReset: Double = 0.0 + + init( + trig: any ValidGeneratorInput, + reset: any ValidGeneratorInput, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedTrig: any ValidGeneratorInput = trig._resolvedInput() + let resolvedReset: any ValidGeneratorInput = reset._resolvedInput() + _trigInput = resolvedTrig + _resetInput = resolvedReset + _mulAdd = MulAddSpec(mul: mul, add: add) + } + } + + // MARK: - Audio rate + + /// Sample-accurate trigger counter with optional reset. + /// + /// - Parameters: + /// - trig: Trigger signal. ≤0 → >0 edges increment the counter. + /// - reset: Reset signal. ≤0 → >0 edges clear the counter before the `trig` increment. + /// Defaults to `0.0` (never resets). + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - trig: Trigger signal. ≤0 → >0 edges increment the counter. + /// - reset: Reset signal. ≤0 → >0 edges clear the counter before the `trig` increment. + /// Defaults to `0.0` (never resets). + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + trig: any ValidGeneratorInput, + reset: any ValidGeneratorInput = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(trig: trig, reset: reset, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let trigSamples: [Double] = _trigInput.calculatedSamples(graph: graph, count: count).first + ?? pulseCountZeroBlock + let resetSamples: [Double] = _resetInput.calculatedSamples(graph: graph, count: count).first + ?? pulseCountZeroBlock + + var count_: Double = _count + var prevTrig: Double = _prevTrig + var prevReset: Double = _prevReset + + for i: Int in 0.. 0 && prevReset <= 0 { + count_ = 0 + } + if t > 0 && prevTrig <= 0 { + count_ += 1 + } + + prevTrig = t + prevReset = r + _result[0][i] = count_ + } + + _count = count_ + _prevTrig = prevTrig + _prevReset = prevReset + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + return _result + } + } + + // MARK: - Control rate + + /// Block-rate trigger counter. Scans the full audio-rate trigger block and accumulates + /// all rising edges. The block-final count is output as a flat block — no ramp. + /// + /// > Note: Counter outputs must not be interpolated/smoothed because they are + /// > discrete-valued. This variant writes a flat constant block equal to the + /// > block-final count rather than using `fillRampedResult`. + /// + /// - Parameters: + /// - trig: Trigger signal. ≤0 → >0 edges increment the counter. + /// - reset: Reset signal. ≤0 → >0 edges clear the counter before the `trig` increment. + /// Defaults to `0.0` (never resets). + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Control: _Base, ControlGenerator { + public var previousOutputValue: Double = 0.0 + + /// - Parameters: + /// - trig: Trigger signal. ≤0 → >0 edges increment the counter. + /// - reset: Reset signal. ≤0 → >0 edges clear the counter before the `trig` increment. + /// Defaults to `0.0` (never resets). + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + trig: any ValidGeneratorInput, + reset: any ValidGeneratorInput = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(trig: trig, reset: reset, mul: mul, add: add) + _setupSubBlockBuffer() + } + + /// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning + /// the full audio-rate input once per audio block, not per sub-block chunk. + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let trigSamples: [Double] = _trigInput.calculatedSamples(graph: graph, count: count).first + ?? pulseCountZeroBlock + let resetSamples: [Double] = _resetInput.calculatedSamples(graph: graph, count: count).first + ?? pulseCountZeroBlock + + var count_: Double = _count + var prevTrig: Double = _prevTrig + var prevReset: Double = _prevReset + + for i: Int in 0.. 0 && prevReset <= 0 { + count_ = 0 + } + if t > 0 && prevTrig <= 0 { + count_ += 1 + } + + prevTrig = t + prevReset = r + } + + _count = count_ + _prevTrig = prevTrig + _prevReset = prevReset + + for i: Int in 0.. 0 { previousOutputValue = _result[0][count - 1] } + return _result + } + } +} + +extension PulseCount: GeneratorEnum { + public typealias AudioType = PulseCount.Audio + public typealias ControlType = PulseCount.Control +} diff --git a/Sources/Lyrebird/Generators/Triggers/Schmidt.swift b/Sources/Lyrebird/Generators/Triggers/Schmidt.swift new file mode 100644 index 0000000..41c829c --- /dev/null +++ b/Sources/Lyrebird/Generators/Triggers/Schmidt.swift @@ -0,0 +1,223 @@ +// Schmidt.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// File-scope zero-fill block — used as the `??` fallback when an upstream +/// generator returns an empty channel array. +private let schmidtZeroBlock: [Double] = [Double]( + repeating: 0, + count: lyrebirdDefaultResultBufferSize +) + +/// Schmitt trigger with hysteresis. +/// +/// Maintains a binary `0.0` / `1.0` state with separate switch-on and switch-off +/// thresholds, preventing rapid toggling near the threshold (chatter rejection). +/// +/// - When state is `0.0` and `input > hi`, state switches to `1.0`. +/// - When state is `1.0` and `input < lo`, state switches to `0.0`. +/// - When `input` is between `lo` and `hi` ("hysteresis band"), state is unchanged. +/// +/// SC equivalent: `Schmidt`. +/// +/// ```swift +/// // Gate signal on amplitude with 0.1/0.3 hysteresis band. +/// let amp = AmplitudeFollower.Audio(input: In.Audio(bus: 0)) +/// let gate = Schmidt.Audio(input: amp, lo: 0.1, hi: 0.3) +/// ``` +/// +/// - Parameters: +/// - input: Signal whose level drives the state machine. +/// - lo: Switch-off threshold. When state is `1.0` and `input < lo`, switches to `0.0`. +/// Any `ValidGeneratorInput` — may be audio-rate, control-rate, or a scalar literal. +/// Defaults to `0.0`. +/// - hi: Switch-on threshold. When state is `0.0` and `input > hi`, switches to `1.0`. +/// Any `ValidGeneratorInput` — may be audio-rate, control-rate, or a scalar literal. +/// Defaults to `0.0`. +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum Schmidt { + + // MARK: - Shared base + + public class _Base: GeneratorBase { + let _input: any ValidGeneratorInput + let _loInput: any ValidGeneratorInput + let _hiInput: any ValidGeneratorInput + let _loIsGenerator: Bool + let _hiIsGenerator: Bool + let _mulAdd: MulAddSpec + + var _state: Double = 0.0 + + init( + input: any ValidGeneratorInput, + lo: any ValidGeneratorInput, + hi: any ValidGeneratorInput, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + let resolvedLo: any ValidGeneratorInput = lo._resolvedInput() + let resolvedHi: any ValidGeneratorInput = hi._resolvedInput() + _input = resolvedInput + _loInput = resolvedLo + _hiInput = resolvedHi + _loIsGenerator = resolvedLo is any Generator + _hiIsGenerator = resolvedHi is any Generator + _mulAdd = MulAddSpec(mul: mul, add: add) + } + } + + // MARK: - Audio rate + + /// Sample-accurate Schmitt trigger. Both `lo` and `hi` may be audio-rate generators. + /// + /// - Parameters: + /// - input: Signal whose level drives the state machine. + /// - lo: Switch-off threshold (any `ValidGeneratorInput`). Defaults to `0.0`. + /// - hi: Switch-on threshold (any `ValidGeneratorInput`). Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - input: Signal whose level drives the state machine. + /// - lo: Switch-off threshold. When state is `1.0` and `input < lo`, switches to `0.0`. + /// Defaults to `0.0`. + /// - hi: Switch-on threshold. When state is `0.0` and `input > hi`, switches to `1.0`. + /// Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + lo: any ValidGeneratorInput = 0.0, + hi: any ValidGeneratorInput = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, lo: lo, hi: hi, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples(graph: graph, count: count).first + ?? schmidtZeroBlock + let (loSamples, loScalar) = resolveGeneratorOrScalar( + _loInput, isGenerator: _loIsGenerator, graph: graph, count: count) + let (hiSamples, hiScalar) = resolveGeneratorOrScalar( + _hiInput, isGenerator: _hiIsGenerator, graph: graph, count: count) + + var state: Double = _state + for i: Int in 0.. hi { + state = 1.0 + } else if state > 0 && x < lo { + state = 0.0 + } + _result[0][i] = state + } + _state = state + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + return _result + } + } + + // MARK: - Control rate + + /// Block-rate Schmitt trigger. Scans the full audio-rate input for state transitions; + /// outputs the block-final binary state as a flat block — no ramp. + /// + /// > Note: Schmitt trigger output is discrete (0.0 or 1.0) and must not be + /// > interpolated/smoothed. This variant writes a flat constant block equal to the + /// > block-final state rather than using `fillRampedResult`. + /// + /// - Parameters: + /// - input: Signal whose level drives the state machine. + /// - lo: Switch-off threshold (any `ValidGeneratorInput`). Defaults to `0.0`. + /// - hi: Switch-on threshold (any `ValidGeneratorInput`). Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Control: _Base, ControlGenerator { + public var previousOutputValue: Double = 0.0 + + /// - Parameters: + /// - input: Signal whose level drives the state machine. + /// - lo: Switch-off threshold. When state is `1.0` and `input < lo`, switches to `0.0`. + /// Defaults to `0.0`. + /// - hi: Switch-on threshold. When state is `0.0` and `input > hi`, switches to `1.0`. + /// Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + lo: any ValidGeneratorInput = 0.0, + hi: any ValidGeneratorInput = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, lo: lo, hi: hi, mul: mul, add: add) + _setupSubBlockBuffer() + } + + /// Bypasses `ControlGenerator` sub-block loop — state-machine scanning requires + /// the full audio-rate input once per audio block, not per sub-block chunk. + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples(graph: graph, count: count).first + ?? schmidtZeroBlock + let (loSamples, loScalar) = resolveGeneratorOrScalar( + _loInput, isGenerator: _loIsGenerator, graph: graph, count: count) + let (hiSamples, hiScalar) = resolveGeneratorOrScalar( + _hiInput, isGenerator: _hiIsGenerator, graph: graph, count: count) + + var state: Double = _state + for i: Int in 0.. hi { + state = 1.0 + } else if state > 0 && x < lo { + state = 0.0 + } + } + _state = state + + for i: Int in 0.. 0 { previousOutputValue = _result[0][count - 1] } + return _result + } + } +} + +extension Schmidt: GeneratorEnum { + public typealias AudioType = Schmidt.Audio + public typealias ControlType = Schmidt.Control +} diff --git a/Sources/Lyrebird/Generators/Triggers/Stepper.swift b/Sources/Lyrebird/Generators/Triggers/Stepper.swift new file mode 100644 index 0000000..f66e0b6 --- /dev/null +++ b/Sources/Lyrebird/Generators/Triggers/Stepper.swift @@ -0,0 +1,301 @@ +// Stepper.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// File-scope zero-fill block — used as the `??` fallback when an upstream +/// generator returns an empty channel array. +private let stepperZeroBlock: [Double] = [Double]( + repeating: 0, + count: lyrebirdDefaultResultBufferSize +) + +/// Wrapping integer step counter. +/// +/// On each ≤0 → >0 rising edge of `trig`, advances an internal integer value by +/// `step` within the range `[min, max]`, wrapping around at the boundaries. +/// A rising edge of `reset` returns the counter to `resetval` before the `trig` +/// step at that same sample. +/// +/// The range, step size, and reset value are init-time scalars and cannot be +/// modulated at runtime. +/// +/// SC equivalent: `Stepper`. +/// +/// ```swift +/// // 8-step sequencer index cycling 0..7. +/// let clock = Impulse.Audio(freq: 4.0) +/// let idx = Stepper.Audio(trig: clock, min: 0, max: 7, step: 1, resetval: 0) +/// ``` +/// +/// - Parameters: +/// - trig: Trigger signal. ≤0 → >0 edges advance the counter by `step`. +/// - reset: Reset signal. ≤0 → >0 edges return the counter to `resetval` before the step. +/// Defaults to `0.0` (never resets). +/// - min: Minimum value (inclusive) of the counter range. Init-time scalar. Defaults to `0`. +/// - max: Maximum value (inclusive) of the counter range. Init-time scalar. Must be ≥ `min`. +/// Defaults to `7`. +/// - step: Amount added per trigger edge. May be negative for downward stepping. +/// Init-time scalar. Defaults to `1`. +/// - resetval: Value written on a reset edge, clamped into `[min, max]`. +/// Init-time scalar. Defaults to `0`. +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum Stepper { + + // MARK: - Shared base + + public class _Base: GeneratorBase { + let _trigInput: any ValidGeneratorInput + let _resetInput: any ValidGeneratorInput + let _mulAdd: MulAddSpec + let _min: Int + let _span: Int + let _step: Int + let _resetval: Int + + var _value: Int = 0 + var _prevTrig: Double = 0.0 + var _prevReset: Double = 0.0 + + init( + trig: any ValidGeneratorInput, + reset: any ValidGeneratorInput, + min: Int, + max: Int, + step: Int, + resetval: Int, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + precondition(max >= min, "Stepper: max (\(max)) must be >= min (\(min))") + let resolvedTrig: any ValidGeneratorInput = trig._resolvedInput() + let resolvedReset: any ValidGeneratorInput = reset._resolvedInput() + _trigInput = resolvedTrig + _resetInput = resolvedReset + _mulAdd = MulAddSpec(mul: mul, add: add) + _min = min + _span = max - min + 1 + _step = step + _resetval = Swift.min(max, Swift.max(min, resetval)) + _value = _resetval + } + } + + // MARK: - Audio rate + + /// Sample-accurate wrapping step counter. + /// + /// - Parameters: + /// - trig: Trigger signal. ≤0 → >0 edges advance the counter by `step`. + /// - reset: Reset signal. ≤0 → >0 edges return the counter to `resetval`. + /// Defaults to `0.0` (never resets). + /// - min: Minimum value (inclusive). Init-time scalar. Defaults to `0`. + /// - max: Maximum value (inclusive). Must be ≥ `min`. Init-time scalar. Defaults to `7`. + /// - step: Amount added per trigger edge. Init-time scalar. Defaults to `1`. + /// - resetval: Value written on a reset edge, clamped to `[min, max]`. + /// Init-time scalar. Defaults to `0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - trig: Trigger signal. ≤0 → >0 edges advance the counter by `step`. + /// - reset: Reset signal. ≤0 → >0 edges return the counter to `resetval`. + /// Defaults to `0.0` (never resets). + /// - min: Minimum value (inclusive). Init-time scalar. Defaults to `0`. + /// - max: Maximum value (inclusive). Must be ≥ `min`. Init-time scalar. Defaults to `7`. + /// - step: Amount added per trigger edge. Init-time scalar. Defaults to `1`. + /// - resetval: Value written on a reset edge, clamped to `[min, max]`. + /// Init-time scalar. Defaults to `0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + trig: any ValidGeneratorInput, + reset: any ValidGeneratorInput = 0.0, + min: Int = 0, + max: Int = 7, + step: Int = 1, + resetval: Int = 0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init( + trig: trig, + reset: reset, + min: min, + max: max, + step: step, + resetval: resetval, + mul: mul, + add: add + ) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let trigSamples: [Double] = _trigInput.calculatedSamples(graph: graph, count: count).first + ?? stepperZeroBlock + let resetSamples: [Double] = _resetInput.calculatedSamples(graph: graph, count: count).first + ?? stepperZeroBlock + + var value: Int = _value + var prevTrig: Double = _prevTrig + var prevReset: Double = _prevReset + let span: Int = _span + let min_: Int = _min + let step: Int = _step + + for i: Int in 0.. 0 && prevReset <= 0 { + value = _resetval + } + if t > 0 && prevTrig <= 0 { + // Modular wrap using ((n % span) + span) % span pattern to handle + // negative step values correctly. + let shifted: Int = value + step - min_ + value = min_ + ((shifted % span) + span) % span + } + + prevTrig = t + prevReset = r + _result[0][i] = Double(value) + } + + _value = value + _prevTrig = prevTrig + _prevReset = prevReset + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + return _result + } + } + + // MARK: - Control rate + + /// Block-rate wrapping step counter. Scans the full audio-rate trigger block and + /// accumulates all rising edges. The block-final step value is output as a flat + /// block — no ramp. + /// + /// > Note: Counter/step outputs must not be interpolated/smoothed because they are + /// > discrete-valued. This variant writes a flat constant block equal to the + /// > block-final step value rather than using `fillRampedResult`. + /// + /// - Parameters: + /// - trig: Trigger signal. ≤0 → >0 edges advance the counter by `step`. + /// - reset: Reset signal. ≤0 → >0 edges return the counter to `resetval`. + /// Defaults to `0.0` (never resets). + /// - min: Minimum value (inclusive). Init-time scalar. Defaults to `0`. + /// - max: Maximum value (inclusive). Must be ≥ `min`. Init-time scalar. Defaults to `7`. + /// - step: Amount added per trigger edge. Init-time scalar. Defaults to `1`. + /// - resetval: Value written on a reset edge, clamped to `[min, max]`. + /// Init-time scalar. Defaults to `0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Control: _Base, ControlGenerator { + public var previousOutputValue: Double = 0.0 + + /// - Parameters: + /// - trig: Trigger signal. ≤0 → >0 edges advance the counter by `step`. + /// - reset: Reset signal. ≤0 → >0 edges return the counter to `resetval`. + /// Defaults to `0.0` (never resets). + /// - min: Minimum value (inclusive). Init-time scalar. Defaults to `0`. + /// - max: Maximum value (inclusive). Must be ≥ `min`. Init-time scalar. Defaults to `7`. + /// - step: Amount added per trigger edge. Init-time scalar. Defaults to `1`. + /// - resetval: Value written on a reset edge, clamped to `[min, max]`. + /// Init-time scalar. Defaults to `0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + trig: any ValidGeneratorInput, + reset: any ValidGeneratorInput = 0.0, + min: Int = 0, + max: Int = 7, + step: Int = 1, + resetval: Int = 0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init( + trig: trig, + reset: reset, + min: min, + max: max, + step: step, + resetval: resetval, + mul: mul, + add: add + ) + _setupSubBlockBuffer() + } + + /// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning + /// the full audio-rate input once per audio block, not per sub-block chunk. + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let trigSamples: [Double] = _trigInput.calculatedSamples(graph: graph, count: count).first + ?? stepperZeroBlock + let resetSamples: [Double] = _resetInput.calculatedSamples(graph: graph, count: count).first + ?? stepperZeroBlock + + var value: Int = _value + var prevTrig: Double = _prevTrig + var prevReset: Double = _prevReset + let span: Int = _span + let min_: Int = _min + let step: Int = _step + + for i: Int in 0.. 0 && prevReset <= 0 { + value = _resetval + } + if t > 0 && prevTrig <= 0 { + let shifted: Int = value + step - min_ + value = min_ + ((shifted % span) + span) % span + } + + prevTrig = t + prevReset = r + } + + _value = value + _prevTrig = prevTrig + _prevReset = prevReset + + for i: Int in 0.. 0 { previousOutputValue = _result[0][count - 1] } + return _result + } + } +} + +extension Stepper: GeneratorEnum { + public typealias AudioType = Stepper.Audio + public typealias ControlType = Stepper.Control +} diff --git a/Sources/Lyrebird/Generators/Triggers/Trig.swift b/Sources/Lyrebird/Generators/Triggers/Trig.swift new file mode 100644 index 0000000..fa4c968 --- /dev/null +++ b/Sources/Lyrebird/Generators/Triggers/Trig.swift @@ -0,0 +1,226 @@ +// Trig.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// File-scope zero-fill block — used as the `??` fallback when an upstream +/// generator returns an empty channel array. +private let trigZeroBlock: [Double] = [Double]( + repeating: 0, + count: lyrebirdDefaultResultBufferSize +) + +/// Trigger-length pulse that outputs the captured input level. +/// +/// On each ≤0 → >0 rising edge of `input`, captures the input value at that +/// exact frame and outputs it for `dur` seconds, then returns to `0.0`. +/// A new rising edge during the hold restarts the timer and re-captures the +/// level at the new edge frame. +/// +/// SC equivalent: `Trig`. +/// +/// ```swift +/// // Capture amplitude and hold it for 0.1 s every time a trigger fires. +/// let amp = AmplitudeFollower.Audio(input: In.Audio(bus: 0)) +/// let clock = Impulse.Audio(freq: 4.0) +/// let pulse = Trig.Audio(input: amp, dur: 0.1) +/// ``` +/// +/// - Parameters: +/// - input: Signal to monitor for rising edges; the captured level is this value at the edge frame. +/// - dur: Hold duration in seconds. Converted to samples via engine sample rate. +/// Clamped to a minimum of 1 sample. Init-time scalar only. +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum Trig { + + // MARK: - Shared base + + public class _Base: GeneratorBase { + let _input: any ValidGeneratorInput + let _mulAdd: MulAddSpec + let _dur: Double + + var _prevTrig: Double = 0.0 + var _remaining: Int = 0 + var _level: Double = 0.0 + + init( + input: any ValidGeneratorInput, + dur: Double, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + _input = resolvedInput + _dur = dur + _mulAdd = MulAddSpec(mul: mul, add: add) + } + } + + // MARK: - Audio rate + + /// Sample-accurate trig pulse that outputs the input level for `dur` seconds. + /// + /// - Parameters: + /// - input: Signal to monitor for rising edges; captured level is this value at the edge frame. + /// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - input: Signal to monitor for rising edges; captured level is this value at the edge frame. + /// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + dur: Double = 0.1, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, dur: dur, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples(graph: graph, count: count).first + ?? trigZeroBlock + let sampleRate: Double = graph.engine.sampleRate + let delaySamples: Int = max(1, Int((_dur * sampleRate).rounded())) + + var prevTrig: Double = _prevTrig + var remaining: Int = _remaining + var level: Double = _level + + for i: Int in 0.. 0 && prevTrig <= 0 { + // Rising edge: capture level and restart countdown. + level = x + remaining = delaySamples + } + prevTrig = x + + if remaining > 0 { + _result[0][i] = level + remaining -= 1 + } else { + _result[0][i] = 0.0 + } + } + + _prevTrig = prevTrig + _remaining = remaining + _level = level + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + return _result + } + } + + // MARK: - Control rate + + /// Block-rate trig pulse. Scans the full audio-rate input block for rising edges. + /// The block-final level (captured value or 0) is output as a flat block — no ramp. + /// + /// > Note: Trigger/counter outputs must not be interpolated/smoothed because they + /// > are discrete-valued. This variant writes a flat constant block equal to the + /// > block-final state rather than using `fillRampedResult`. + /// + /// - Parameters: + /// - input: Signal to monitor for rising edges; captured level is this value at the edge frame. + /// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Control: _Base, ControlGenerator { + public var previousOutputValue: Double = 0.0 + + /// - Parameters: + /// - input: Signal to monitor for rising edges; captured level is this value at the edge frame. + /// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + dur: Double = 0.1, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, dur: dur, mul: mul, add: add) + _setupSubBlockBuffer() + } + + /// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning + /// the full audio-rate input once per audio block, not per sub-block chunk. + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples(graph: graph, count: count).first + ?? trigZeroBlock + let sampleRate: Double = graph.engine.sampleRate + let delaySamples: Int = max(1, Int((_dur * sampleRate).rounded())) + + var prevTrig: Double = _prevTrig + var remaining: Int = _remaining + var level: Double = _level + + // Run the exact per-sample state machine and capture the output at + // the final sample — the block-representative (block-final) value. + // Capturing the per-sample output (rather than inferring from the + // post-loop `remaining`) keeps the boundary correct when a hold + // spans exactly one block: the hold is active across every sample, + // so the block-final value is `level`, not `0`. + var lastOutput: Double = 0.0 + for i: Int in 0.. 0 && prevTrig <= 0 { + level = x + remaining = delaySamples + } + prevTrig = x + + if remaining > 0 { + lastOutput = level + remaining -= 1 + } else { + lastOutput = 0.0 + } + } + + _prevTrig = prevTrig + _remaining = remaining + _level = level + + let outputValue: Double = lastOutput + + for i: Int in 0.. 0 { previousOutputValue = _result[0][count - 1] } + return _result + } + } +} + +extension Trig: GeneratorEnum { + public typealias AudioType = Trig.Audio + public typealias ControlType = Trig.Control +} diff --git a/Sources/Lyrebird/Generators/Triggers/Trig1.swift b/Sources/Lyrebird/Generators/Triggers/Trig1.swift new file mode 100644 index 0000000..6dc9d78 --- /dev/null +++ b/Sources/Lyrebird/Generators/Triggers/Trig1.swift @@ -0,0 +1,219 @@ +// Trig1.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// File-scope zero-fill block — used as the `??` fallback when an upstream +/// generator returns an empty channel array. +private let trig1ZeroBlock: [Double] = [Double]( + repeating: 0, + count: lyrebirdDefaultResultBufferSize +) + +/// Trigger-length unity pulse. +/// +/// Identical to `Trig` but always outputs `1.0` (unity) rather than the +/// captured input level. On each ≤0 → >0 rising edge of `input`, outputs +/// `1.0` for `dur` seconds, then returns to `0.0`. A new rising edge during +/// the hold restarts the timer. +/// +/// SC equivalent: `Trig1`. +/// +/// ```swift +/// // Produce a 50 ms gate pulse on every impulse trigger. +/// let clock = Impulse.Audio(freq: 4.0) +/// let gate = Trig1.Audio(input: clock, dur: 0.05) +/// ``` +/// +/// - Parameters: +/// - input: Signal to monitor for ≤0 → >0 rising edges. +/// - dur: Hold duration in seconds. Converted to samples via engine sample rate. +/// Clamped to a minimum of 1 sample. Init-time scalar only. +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum Trig1 { + + // MARK: - Shared base + + public class _Base: GeneratorBase { + let _input: any ValidGeneratorInput + let _mulAdd: MulAddSpec + let _dur: Double + + var _prevTrig: Double = 0.0 + var _remaining: Int = 0 + + init( + input: any ValidGeneratorInput, + dur: Double, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + _input = resolvedInput + _dur = dur + _mulAdd = MulAddSpec(mul: mul, add: add) + } + } + + // MARK: - Audio rate + + /// Sample-accurate unity pulse held for `dur` seconds on each rising edge. + /// + /// - Parameters: + /// - input: Signal to monitor for ≤0 → >0 rising edges. + /// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - input: Signal to monitor for ≤0 → >0 rising edges. + /// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + dur: Double = 0.1, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, dur: dur, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples(graph: graph, count: count).first + ?? trig1ZeroBlock + let sampleRate: Double = graph.engine.sampleRate + let delaySamples: Int = max(1, Int((_dur * sampleRate).rounded())) + + var prevTrig: Double = _prevTrig + var remaining: Int = _remaining + + for i: Int in 0.. 0 && prevTrig <= 0 { + // Rising edge: restart countdown. + remaining = delaySamples + } + prevTrig = x + + if remaining > 0 { + _result[0][i] = 1.0 + remaining -= 1 + } else { + _result[0][i] = 0.0 + } + } + + _prevTrig = prevTrig + _remaining = remaining + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + return _result + } + } + + // MARK: - Control rate + + /// Block-rate unity pulse. Scans the full audio-rate input block for rising edges. + /// The block-final state (`1.0` if hold is active, else `0.0`) is output as a flat + /// block — no ramp. + /// + /// > Note: Trigger/counter outputs must not be interpolated/smoothed because they + /// > are discrete-valued. This variant writes a flat constant block equal to the + /// > block-final state rather than using `fillRampedResult`. + /// + /// - Parameters: + /// - input: Signal to monitor for ≤0 → >0 rising edges. + /// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Control: _Base, ControlGenerator { + public var previousOutputValue: Double = 0.0 + + /// - Parameters: + /// - input: Signal to monitor for ≤0 → >0 rising edges. + /// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + dur: Double = 0.1, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, dur: dur, mul: mul, add: add) + _setupSubBlockBuffer() + } + + /// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning + /// the full audio-rate input once per audio block, not per sub-block chunk. + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples(graph: graph, count: count).first + ?? trig1ZeroBlock + let sampleRate: Double = graph.engine.sampleRate + let delaySamples: Int = max(1, Int((_dur * sampleRate).rounded())) + + var prevTrig: Double = _prevTrig + var remaining: Int = _remaining + + // Run the exact per-sample state machine and capture the output at + // the final sample — the block-representative (block-final) value. + // Capturing the per-sample output (rather than inferring from the + // post-loop `remaining`) keeps the boundary correct when a pulse + // spans exactly one block: the pulse is high across every sample, + // so the block-final value is `1.0`, not `0`. + var lastOutput: Double = 0.0 + for i: Int in 0.. 0 && prevTrig <= 0 { + remaining = delaySamples + } + prevTrig = x + + if remaining > 0 { + lastOutput = 1.0 + remaining -= 1 + } else { + lastOutput = 0.0 + } + } + + _prevTrig = prevTrig + _remaining = remaining + + let outputValue: Double = lastOutput + + for i: Int in 0.. 0 { previousOutputValue = _result[0][count - 1] } + return _result + } + } +} + +extension Trig1: GeneratorEnum { + public typealias AudioType = Trig1.Audio + public typealias ControlType = Trig1.Control +} diff --git a/Sources/Lyrebird/Generators/Triggers/TriggeredDelay.swift b/Sources/Lyrebird/Generators/Triggers/TriggeredDelay.swift new file mode 100644 index 0000000..a31da8e --- /dev/null +++ b/Sources/Lyrebird/Generators/Triggers/TriggeredDelay.swift @@ -0,0 +1,234 @@ +// TriggeredDelay.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// File-scope zero-fill block — used as the `??` fallback when an upstream +/// generator returns an empty channel array. +private let triggeredDelayZeroBlock: [Double] = [Double]( + repeating: 0, + count: lyrebirdDefaultResultBufferSize +) + +/// Delayed single-sample trigger. +/// +/// On a ≤0 → >0 rising edge of `input`, starts a countdown of `dur` seconds. +/// When the countdown completes, emits a single-sample `1.0` pulse. +/// Additional rising edges arriving while the countdown is active are **ignored** +/// — only the first edge in each idle→counting cycle is honoured. +/// +/// SC equivalent: `TDelay`. +/// +/// ```swift +/// // Delayed gate: fire 0.2 s after each impulse. +/// let clock = Impulse.Audio(freq: 2.0) +/// let delayed = TriggeredDelay.Audio(input: clock, dur: 0.2) +/// ``` +/// +/// - Parameters: +/// - input: Trigger signal. ≤0 → >0 edges start the countdown when idle. +/// - dur: Delay duration in seconds. Converted to samples via engine sample rate. +/// Clamped to a minimum of 1 sample. Init-time scalar only. +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public enum TriggeredDelay { + + /// Sentinel value indicating the generator is idle (no active countdown). + private static let idleRemaining: Int = -1 + + // MARK: - Shared base + + public class _Base: GeneratorBase { + let _input: any ValidGeneratorInput + let _mulAdd: MulAddSpec + let _dur: Double + + var _prevTrig: Double = 0.0 + /// `-1` when idle; counts down to `0` when active. + var _remaining: Int = TriggeredDelay.idleRemaining + + init( + input: any ValidGeneratorInput, + dur: Double, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + _input = resolvedInput + _dur = dur + _mulAdd = MulAddSpec(mul: mul, add: add) + } + } + + // MARK: - Audio rate + + /// Sample-accurate delayed trigger. Emits a single-sample `1.0` after `dur` seconds. + /// + /// - Parameters: + /// - input: Trigger signal. ≤0 → >0 edges start the countdown when idle. + /// - dur: Delay duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - input: Trigger signal. ≤0 → >0 edges start the countdown when idle. + /// - dur: Delay duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + dur: Double = 0.1, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, dur: dur, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples(graph: graph, count: count).first + ?? triggeredDelayZeroBlock + let sampleRate: Double = graph.engine.sampleRate + let delaySamples: Int = max(1, Int((_dur * sampleRate).rounded())) + let idle: Int = TriggeredDelay.idleRemaining + + var prevTrig: Double = _prevTrig + var remaining: Int = _remaining + + for i: Int in 0.. 0 { + remaining -= 1 + if remaining == 0 { + _result[0][i] = 1.0 + // Return to idle immediately so a new edge can be accepted + // on the very next sample. + remaining = idle + prevTrig = x + continue + } + } + _result[0][i] = 0.0 + + // Accept a new edge only when idle. + if remaining == idle && x > 0 && prevTrig <= 0 { + remaining = delaySamples + } + prevTrig = x + } + + _prevTrig = prevTrig + _remaining = remaining + + _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) + return _result + } + } + + // MARK: - Control rate + + /// Block-rate delayed trigger. Scans the full audio-rate input block; the first + /// idle rising edge starts the countdown. When the countdown reaches zero, the + /// block containing that frame outputs `1.0` (flat), then returns to `0.0`. + /// + /// > Note: Trigger/counter outputs must not be interpolated/smoothed because they + /// > are discrete-valued. This variant writes a flat constant block equal to the + /// > block-final state rather than using `fillRampedResult`. + /// + /// - Parameters: + /// - input: Trigger signal. ≤0 → >0 edges start the countdown when idle. + /// - dur: Delay duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Control: _Base, ControlGenerator { + public var previousOutputValue: Double = 0.0 + + /// - Parameters: + /// - input: Trigger signal. ≤0 → >0 edges start the countdown when idle. + /// - dur: Delay duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + dur: Double = 0.1, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, dur: dur, mul: mul, add: add) + _setupSubBlockBuffer() + } + + /// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning + /// the full audio-rate input once per audio block, not per sub-block chunk. + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let inputSamples: [Double] = _input.calculatedSamples(graph: graph, count: count).first + ?? triggeredDelayZeroBlock + let sampleRate: Double = graph.engine.sampleRate + let delaySamples: Int = max(1, Int((_dur * sampleRate).rounded())) + let idle: Int = TriggeredDelay.idleRemaining + + var prevTrig: Double = _prevTrig + var remaining: Int = _remaining + var fired: Bool = false + + for i: Int in 0.. 0 { + remaining -= 1 + if remaining == 0 { + fired = true + remaining = idle + prevTrig = x + continue + } + } + + // Accept a new edge only when idle. + if remaining == idle && x > 0 && prevTrig <= 0 { + remaining = delaySamples + } + prevTrig = x + } + + _prevTrig = prevTrig + _remaining = remaining + + let outputValue: Double = fired ? 1.0 : 0.0 + + for i: Int in 0.. 0 { previousOutputValue = _result[0][count - 1] } + return _result + } + } +} + +extension TriggeredDelay: GeneratorEnum { + public typealias AudioType = TriggeredDelay.Audio + public typealias ControlType = TriggeredDelay.Control +} diff --git a/Sources/Lyrebird/Generators/Waveshaping/CrossoverDistortion.swift b/Sources/Lyrebird/Generators/Waveshaping/CrossoverDistortion.swift new file mode 100644 index 0000000..a94ceeb --- /dev/null +++ b/Sources/Lyrebird/Generators/Waveshaping/CrossoverDistortion.swift @@ -0,0 +1,221 @@ +// CrossoverDistortion.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// MARK: - CrossoverDistortion + +/// Crossover / dead-zone distortion inspired by SuperCollider `CrossoverDistortion`. +/// +/// Introduces a dead zone of width `2 × amp` centred on zero. Signals in `[-amp, amp]` +/// are silenced; signals outside that range are shifted back toward zero and passed through. +/// A smooth-knee option (`smooth > 0`) applies a C¹-continuous quadratic ease-in at the +/// dead-zone boundary, avoiding the click of the hard-knee discontinuity in the first derivative. +/// +/// ## Transfer function +/// +/// For input `x`, threshold `a = max(0, amp)`, sign `s = x < 0 ? -1 : 1`: +/// ``` +/// if |x| ≤ a: out = 0 (dead zone) +/// else let over = |x| − a: +/// let kneeWidth = a × smooth // 0 = hard knee, a = full-width knee +/// if kneeWidth > 0 && over < kneeWidth: +/// out = s × over² / (2 × kneeWidth) // C¹ ease-in: slope 0 at a, slope 1 at a + kneeWidth +/// else: +/// out = s × (over − 0.5 × kneeWidth) // linear continuation maintaining C¹ at knee exit +/// ``` +/// +/// ## Usage +/// ```swift +/// // Hard-knee crossover (SC default behaviour). +/// let dist = CrossoverDistortion.Audio(input: signal, amp: 0.5) +/// +/// // Soft-knee crossover with 50 % knee smoothing. +/// let soft = CrossoverDistortion.Audio(input: signal, amp: 0.3, smooth: 0.5) +/// ``` +public enum CrossoverDistortion { + + // MARK: - Shared base + + /// Shared stored properties for `CrossoverDistortion.Audio` and `CrossoverDistortion.Control`. + /// + /// Not for direct use — instantiate `CrossoverDistortion.Audio` or + /// `CrossoverDistortion.Control`. + public class _Base: GeneratorBase { + + let _input: any ValidGeneratorInput + let _ampInput: any ValidGeneratorInput + let _smoothInput: any ValidGeneratorInput + let _inputIsGenerator: Bool + let _ampIsGenerator: Bool + let _smoothIsGenerator: Bool + let _mulAdd: MulAddSpec + + init( + input: any ValidGeneratorInput, + amp: any ValidGeneratorInput, + smooth: any ValidGeneratorInput, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + let resolvedAmp: any ValidGeneratorInput = amp._resolvedInput() + let resolvedSmooth: any ValidGeneratorInput = smooth._resolvedInput() + _input = resolvedInput + _ampInput = resolvedAmp + _smoothInput = resolvedSmooth + _inputIsGenerator = resolvedInput is any Generator + _ampIsGenerator = resolvedAmp is any Generator + _smoothIsGenerator = resolvedSmooth is any Generator + _mulAdd = MulAddSpec(mul: mul, add: add) + } + } + + // MARK: - Audio + + /// Audio-rate crossover distortion. Evaluates input, `amp`, and `smooth` per sample + /// when any of them is a generator input; otherwise uses scalar fast paths. + /// + /// - Parameters: + /// - input: Signal to distort. + /// - amp: Crossover threshold (dead-zone half-width, ≥ 0). SC uses the name `amp` for + /// this parameter; it is **not** an output gain — use `mul` for gain. Defaults to `0.5`. + /// - smooth: Knee smoothness `[0, 1]`. `0` = hard knee; `1` = full-width C¹ ease-in. + /// Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - input: Signal to distort. + /// - amp: Crossover threshold (dead-zone half-width, ≥ 0). SC uses the name `amp` for + /// this parameter; it is **not** an output gain — use `mul` for gain. Defaults to `0.5`. + /// - smooth: Knee smoothness `[0, 1]`. `0` = hard knee; `1` = full-width C¹ ease-in. + /// Defaults to `0.0`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + amp: any ValidGeneratorInput = 0.5, + smooth: any ValidGeneratorInput = 0.0, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, amp: amp, smooth: smooth, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let (inputSamples, scalarInput) = resolveGeneratorOrScalar( + _input, isGenerator: _inputIsGenerator, graph: graph, count: count) + let (ampSamples, scalarAmp) = resolveGeneratorOrScalar( + _ampInput, isGenerator: _ampIsGenerator, graph: graph, count: count) + let (smoothSamples, scalarSmooth) = resolveGeneratorOrScalar( + _smoothInput, isGenerator: _smoothIsGenerator, graph: graph, count: count) + + for i: Int in 0.. Double { previousOutputValue } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let x: Double = _input.floatValue(graph: graph) + let amp: Double = Swift.max(0.0, _ampInput.floatValue(graph: graph)) + let sm: Double = Swift.min(1.0, Swift.max(0.0, _smoothInput.floatValue(graph: graph))) + + var target: Double = crossoverDistortionSample(x: x, amp: amp, smooth: sm) + if !_mulAdd.isIdentity { + target = target * _mulAdd.mulInput.floatValue(graph: graph) + + _mulAdd.addInput.floatValue(graph: graph) + } + fillScalarRampedResult( + into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) + return _result + } + } +} + +// MARK: - Transfer function helper + +/// Per-sample crossover distortion computation. +/// +/// Factored out to share between `Audio` (per-sample hot loop) and `Control` (once per block). +/// `@inline(__always)` to avoid any call overhead in the audio-rate inner loop. +/// +/// - Parameters: +/// - x: Input sample. +/// - amp: Dead-zone half-width (already clamped ≥ 0 by caller). +/// - smooth: Knee smoothness (already clamped to `[0, 1]` by caller). +/// - Returns: Distorted output sample. +@inline(__always) +internal func crossoverDistortionSample(x: Double, amp: Double, smooth: Double) -> Double { + let absx: Double = abs(x) + let s: Double = x < 0 ? -1.0 : 1.0 + guard absx > amp else { return 0.0 } + let over: Double = absx - amp + let kneeWidth: Double = amp * smooth + if kneeWidth > 0 && over < kneeWidth { + return s * (over * over) / (2.0 * kneeWidth) + } + return s * (over - 0.5 * kneeWidth) +} + +// MARK: - GeneratorEnum + +extension CrossoverDistortion: GeneratorEnum { + public typealias AudioType = CrossoverDistortion.Audio + public typealias ControlType = CrossoverDistortion.Control +} diff --git a/Sources/Lyrebird/Generators/Waveshaping/Disintegrator.swift b/Sources/Lyrebird/Generators/Waveshaping/Disintegrator.swift new file mode 100644 index 0000000..2e77933 --- /dev/null +++ b/Sources/Lyrebird/Generators/Waveshaping/Disintegrator.swift @@ -0,0 +1,141 @@ +// Disintegrator.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// MARK: - Disintegrator + +/// Stochastic sample-dropping distortion inspired by SuperCollider `Disintegrator`. +/// +/// Each sample is independently tested against a random uniform draw: if the draw falls +/// below `probability`, the sample is "disintegrated" — replaced by `input × multiplier`. +/// At `probability = 0`, all samples pass through unchanged. At `probability = 1` with +/// `multiplier = 0`, the output is silence. +/// +/// Audio-only (no Control variant). "Block-rate disintegration" has no meaningful +/// physical interpretation — the stochastic draw must advance per sample. +/// +/// ## Usage +/// ```swift +/// // Drop ~50 % of samples to silence (chopped/glitch effect). +/// let dist = Disintegrator.Audio(input: signal, probability: 0.5, multiplier: 0.0) +/// +/// // Attenuate ~30 % of samples by half (subtle grit). +/// let grit = Disintegrator.Audio(input: signal, probability: 0.3, multiplier: 0.5) +/// +/// // Deterministic seed for reproducible test output. +/// let det = Disintegrator.Audio(input: signal, probability: 0.5, seed: 42) +/// ``` +public enum Disintegrator { + + // MARK: - Shared base + + /// Shared PRNG state and inputs for `Disintegrator.Audio`. + /// + /// Not for direct use — instantiate `Disintegrator.Audio`. + public class _Base: NoiseBase { + + let _input: any ValidGeneratorInput + let _probabilityInput: any ValidGeneratorInput + let _multiplierInput: any ValidGeneratorInput + let _inputIsGenerator: Bool + let _probIsGenerator: Bool + let _multIsGenerator: Bool + + init( + input: any ValidGeneratorInput, + probability: any ValidGeneratorInput, + multiplier: any ValidGeneratorInput, + seed: UInt64?, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + let resolvedProb: any ValidGeneratorInput = probability._resolvedInput() + let resolvedMult: any ValidGeneratorInput = multiplier._resolvedInput() + _input = resolvedInput + _probabilityInput = resolvedProb + _multiplierInput = resolvedMult + _inputIsGenerator = resolvedInput is any Generator + _probIsGenerator = resolvedProb is any Generator + _multIsGenerator = resolvedMult is any Generator + // `rngState` and `_mulAdd` are owned by `NoiseBase`. + super.init( + initialRngState: lyrebirdSeedXorshift64(from: seed), + mul: mul, + add: add + ) + } + } + + // MARK: - Audio + + /// Audio-rate stochastic sample-dropping distortion. + /// + /// - Parameters: + /// - input: Signal to process. + /// - probability: Probability `[0, 1]` that each sample is disintegrated. + /// Clamped to `[0, 1]` internally. Defaults to `0.5`. + /// - multiplier: Factor applied to disintegrated samples. `0.0` drops to silence; + /// `1.0` is a no-op (same as probability = 0). Defaults to `0.0`. + /// - seed: PRNG seed. Pass `nil` for a time-derived seed (unique per instance). + /// Pass an explicit value for deterministic / test output. Defaults to `nil`. + /// - mul: Output multiplier applied after disintegration. Defaults to `1.0`. + /// - add: Output offset applied after disintegration. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - input: Signal to process. + /// - probability: Probability `[0, 1]` that each sample is disintegrated. + /// Clamped to `[0, 1]` internally. Defaults to `0.5`. + /// - multiplier: Factor applied to disintegrated samples. `0.0` drops to silence; + /// `1.0` is a no-op (same as probability = 0). Defaults to `0.0`. + /// - seed: PRNG seed. Pass `nil` for a time-derived seed (unique per instance). + /// Pass an explicit value for deterministic / test output. Defaults to `nil`. + /// - mul: Output multiplier applied after disintegration. Defaults to `1.0`. + /// - add: Output offset applied after disintegration. Defaults to `0.0`. + public override init( + input: any ValidGeneratorInput, + probability: any ValidGeneratorInput = 0.5, + multiplier: any ValidGeneratorInput = 0.0, + seed: UInt64? = nil, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(input: input, probability: probability, multiplier: multiplier, seed: seed, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let (inputSamples, scalarInput) = resolveGeneratorOrScalar( + _input, isGenerator: _inputIsGenerator, graph: graph, count: count) + let (probSamples, scalarProb) = resolveGeneratorOrScalar( + _probabilityInput, isGenerator: _probIsGenerator, graph: graph, count: count) + let (multSamples, scalarMult) = resolveGeneratorOrScalar( + _multiplierInput, isGenerator: _multIsGenerator, graph: graph, count: count) + + // Precomputed bipolar-to-unipolar scale: xorshift64Next returns [-1,1], + // shift to [0,1) by (v * 0.5 + 0.5). + let halfShift: Double = 0.5 + + for i: Int in 0..= 2, + "Waveshaper requires table.count >= 2; got \(table.count)." + ) + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + self._slot = RTBufferSlot(initial: table) + self._tableSize = table.count + self._input = resolvedInput + self._inputIsGenerator = resolvedInput is any Generator + self._mulAdd = MulAddSpec(mul: mul, add: add) + } + + /// Replace the transfer-curve table at runtime. + /// + /// The new table must be mono (`channelCount == 1`) and have the same `count` as the + /// table this instance was initialised with (position values are in table-index units). + /// Pass `nil` to silence the waveshaper until a valid table is installed. + /// The previous table's retain is routed through `engine.freeQueue` for off-RT release. + /// + /// - Parameters: + /// - table: New transfer curve, or `nil` to silence. + /// - engine: Engine whose `freeQueue` receives the previous table's reference. + public func setTable(_ table: LyrebirdBuffer?, engine: SynthesisEngine) { + if let t: LyrebirdBuffer = table { + precondition( + t.channelCount == lyrebirdBufferMonoChannelCount, + "Waveshaper.setTable: table must be mono (channelCount == 1), got \(t.channelCount)" + ) + precondition( + t.count == _tableSize, + "Waveshaper.setTable: table count must equal initial table size \(_tableSize), got \(t.count)" + ) + } + _slot.swap(table, engine: engine) + } + } + + // MARK: - Audio + + /// Audio-rate transfer-function waveshaper. Evaluates the input per sample and reads + /// the transfer curve with linear interpolation. + /// + /// ## RT-allocation model + /// `_result` is pre-allocated in `init`. No heap allocation in steady state. + /// + /// - Parameters: + /// - table: Pre-filled `LyrebirdBuffer` transfer curve (mono, `count >= 2`). + /// - input: Signal to waveshape. Values outside `[-1, 1]` are clamped. + /// - mul: Output multiplier applied after shaping. Defaults to `1.0`. + /// - add: Output offset added after multiplier. Defaults to `0.0`. + public final class Audio: _Base, AudioGenerator { + + /// - Parameters: + /// - table: Pre-filled `LyrebirdBuffer` transfer curve (mono, `count >= 2`). + /// - input: Signal to waveshape. Values outside `[-1, 1]` are clamped. + /// - mul: Output multiplier applied after shaping. Defaults to `1.0`. + /// - add: Output offset added after multiplier. Defaults to `0.0`. + public override init( + table: LyrebirdBuffer, + input: any ValidGeneratorInput, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(table: table, input: input, mul: mul, add: add) + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let tableSize: Int = _tableSize + let tableSizeMinusOne: Double = Double(tableSize - 1) + let halfScale: Double = 0.5 + + let (inputSamples, scalarInput) = resolveGeneratorOrScalar( + _input, isGenerator: _inputIsGenerator, graph: graph, count: count) + + guard let table: LyrebirdBuffer = _slot.load(engine: graph.engine), table.isValid else { + // Invalid/nil table — output silence; apply mul/add to preserve `add` offset. + for i: Int in 0..= 2`). + /// - input: Signal to waveshape. Block-rate: only the scalar `floatValue` is read per block. + /// Values outside `[-1, 1]` are clamped. + /// - mul: Output multiplier applied after shaping. Defaults to `1.0`. + /// - add: Output offset added after multiplier. Defaults to `0.0`. + public final class Control: _Base, ControlGenerator { + + public var previousOutputValue: Double = 0.0 + + /// - Parameters: + /// - table: Pre-filled `LyrebirdBuffer` transfer curve (mono, `count >= 2`). + /// - input: Signal to waveshape. Block-rate: only the scalar `floatValue` is read per block. + /// Values outside `[-1, 1]` are clamped. + /// - mul: Output multiplier applied after shaping. Defaults to `1.0`. + /// - add: Output offset added after multiplier. Defaults to `0.0`. + public override init( + table: LyrebirdBuffer, + input: any ValidGeneratorInput, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + super.init(table: table, input: input, mul: mul, add: add) + _setupSubBlockBuffer() + } + + public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + let tableSize: Int = _tableSize + let tableSizeMinusOne: Double = Double(tableSize - 1) + let halfScale: Double = 0.5 + + let rawX: Double = _input.floatValue(graph: graph) + let x: Double = Swift.max(-1.0, Swift.min(1.0, rawX)) + + var target: Double + if let table: LyrebirdBuffer = _slot.load(engine: graph.engine), table.isValid { + let pos: Double = (x * halfScale + halfScale) * tableSizeMinusOne + target = oscillatorTableReadLinear(table, tableSize: tableSize, phase: pos) + } else { + target = 0.0 + } + if !_mulAdd.isIdentity { + target = target * _mulAdd.mulInput.floatValue(graph: graph) + + _mulAdd.addInput.floatValue(graph: graph) + } + fillScalarRampedResult( + into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) + return _result + } + } +} + +// MARK: - GeneratorEnum + +extension Waveshaper: GeneratorEnum { + public typealias AudioType = Waveshaper.Audio + public typealias ControlType = Waveshaper.Control +} diff --git a/Sources/Lyrebird/Lyrebird.docc/BuiltInGenerators.md b/Sources/Lyrebird/Lyrebird.docc/BuiltInGenerators.md index 7fea51d..f037967 100644 --- a/Sources/Lyrebird/Lyrebird.docc/BuiltInGenerators.md +++ b/Sources/Lyrebird/Lyrebird.docc/BuiltInGenerators.md @@ -26,7 +26,11 @@ caseless namespace enum conforming to ``GeneratorEnum``. Paired built-in generat ``AmplitudeFollower``, ``Compressor``, ``Expander``, ``ChannelSelect``, ``Tanh``, ``Pow``, ``Clip``, ``Fold``, ``Wrap``, ``SoftClip``, ``LinLin``, ``LinExp``, ``ExpLin``, ``ExpExp``, ``Abs``, ``Sign``, ``Floor``, ``Ceil``, ``Round``, ``Sqrt``, -``Reciprocal``, ``Log``, ``Exp``, ``Min``, ``Max``. +``Reciprocal``, ``Log``, ``Exp``, ``Min``, ``Max``, +``Trig``, ``Trig1``, ``TriggeredDelay``, ``PulseCount``, ``Stepper``, ``Schmidt``, +``Phasor``, ``Slew``, ``ZeroCrossing``, ``Slope``, ``RunningMin``, ``RunningMax``, +``Select``, ``CrossFade``, ``LinearCrossFade``, ``Waveshaper``, ``CrossoverDistortion``. +(``Disintegrator`` is Audio-only — no Control variant, so no `GeneratorEnum` pairing.) New paired generators must add the same two-line extension — see . ## Topics @@ -43,6 +47,18 @@ New paired generators must add the same two-line extension — see +### Waveshaping and Distortion + +- + +### Triggers and Timing + +- + +### Routing and Morphing + +- + ### Envelopes - diff --git a/Sources/Lyrebird/Lyrebird.docc/Generators/Filters.md b/Sources/Lyrebird/Lyrebird.docc/Generators/Filters.md index e5fcb9d..d71c273 100644 --- a/Sources/Lyrebird/Lyrebird.docc/Generators/Filters.md +++ b/Sources/Lyrebird/Lyrebird.docc/Generators/Filters.md @@ -159,3 +159,19 @@ Decay2.Audio(input: impulse, attackTime: 0.01, decayTime: 0.5) // rounded attack LeakDC.Audio(input: sig) // default coef 0.995 LeakDC.Control(input: sig) // default coef 0.9 ``` + +### Slew Limiting + +``Slew`` limits how fast the output can change: it moves toward the input by at most `up` +units per second when rising and `dn` units per second when falling. This is **linear** +rate-limiting — distinct from the exponential smoothing of ``Lag``. Useful for portamento, +de-zippering, and taming abrupt control jumps. The state initialises to the first input +sample (no startup transient). + +```swift +Slew.Audio(input: sig, up: 100.0, dn: 100.0) // ≤ 100 units/sec slope in either direction +Slew.Audio(input: pitch, up: 50.0, dn: 200.0) // slow glide up, fast fall +Slew.Control(input: cv, up: 10.0, dn: 10.0) // block-rate slew +``` + +- `up` / `dn` — maximum rising / falling slope in units per second. Default `1.0` each. diff --git a/Sources/Lyrebird/Lyrebird.docc/Generators/Oscillators.md b/Sources/Lyrebird/Lyrebird.docc/Generators/Oscillators.md index 2efc789..e3560d4 100644 --- a/Sources/Lyrebird/Lyrebird.docc/Generators/Oscillators.md +++ b/Sources/Lyrebird/Lyrebird.docc/Generators/Oscillators.md @@ -203,6 +203,26 @@ LFDutyCycle.Control(freq: 0.5, dutyCycle: 0.75) --- +## Phasor + +``Phasor`` is a linear ramp / phase accumulator. Unlike the oscillators above it is driven +by a per-sample increment `rate` (not a frequency in Hz) and ramps over an arbitrary range +`[start, end)`, wrapping when it reaches `end`. A rising edge on `trig` resets the phase to +`resetPos`. This is the canonical oscillator-sync source and wavetable / buffer scan driver. + +```swift +Phasor.Audio(rate: 1.0, start: 0.0, end: 512.0) // scan a 512-frame table +Phasor.Audio(trig: sync, rate: inc, start: 0.0, end: 1.0) // re-triggerable [0,1) ramp +Phasor.Control(rate: 0.001, start: 0.0, end: 1.0) // slow control ramp +``` + +- `trig` — any ``ValidGeneratorInput``; a rising edge resets phase to `resetPos`. Defaults to `0.0`. +- `rate` — per-sample increment (NOT Hz). For a Hz-based scan use `rate = freq * (end - start) / sampleRate`. Defaults to `1.0`. +- `start` / `end` — ramp bounds; output is `[start, end)`. Default `0.0` / `1.0`. +- `resetPos` — value the phase jumps to on a trigger. Defaults to `0.0`. + +--- + ## Choosing Between Band-Limited and LFO Oscillators | Use case | Recommendation | diff --git a/Sources/Lyrebird/Lyrebird.docc/Generators/Routing.md b/Sources/Lyrebird/Lyrebird.docc/Generators/Routing.md new file mode 100644 index 0000000..896d6e5 --- /dev/null +++ b/Sources/Lyrebird/Lyrebird.docc/Generators/Routing.md @@ -0,0 +1,57 @@ +# Routing and Morphing + +@Metadata { + @PageKind(article) +} + +Generators for choosing between and blending multiple input signals: an index-driven +N-way selector and two-input crossfades. + +These complement the bus-level routing in (``In`` / ``Out`` / ``MixIn`` / +``SumChannels``) and the per-sample channel extraction of ``ChannelSelect``. + +Each provides an `.Audio` and a `.Control` variant. + +--- + +## Select + +``Select`` outputs the input at integer index `which` (truncated toward zero, clamped to +`[0, N-1]`). All inputs are pulled every block so stateful generators advance regardless of +which is currently selected — matching SuperCollider's `Select`. `which` may be audio-rate +for per-sample source switching. + +```swift +Select.Audio(which: index, inputs: [oscA, oscB, noise]) // pick one of three sources +Select.Control(which: 1.0, inputs: [a, b, c]) // block-rate selection +``` + +- `which` — any ``ValidGeneratorInput``; truncated + clamped to a valid index. +- `inputs` — `[any ValidGeneratorInput]`; at least one required. + +## Crossfading + +``CrossFade`` blends two inputs with an **equal-power** curve; ``LinearCrossFade`` uses a +**linear** curve. `pan ∈ [-1, 1]`: `-1` = full `inA`, `+1` = full `inB`, `0` = centre +(equal-power centre is `√2/2 ≈ 0.707` each; linear centre is `0.5` each). `mul` is the +overall output gain (SuperCollider's `level`). + +```swift +CrossFade.Audio(inA: dry, inB: wet, pan: mix) // equal-power morph +LinearCrossFade.Audio(inA: a, inB: b, pan: 0.0) // linear 50/50 +``` + +- `pan` — any ``ValidGeneratorInput`` in `[-1, 1]`. Defaults to `0.0`. + +> Note: ``CrossFade`` and ``LinearCrossFade`` operate on channel 0 of each input (mono). + +## Topics + +### Selection + +- ``Select`` + +### Crossfading + +- ``CrossFade`` +- ``LinearCrossFade`` diff --git a/Sources/Lyrebird/Lyrebird.docc/Generators/SignalAnalysis.md b/Sources/Lyrebird/Lyrebird.docc/Generators/SignalAnalysis.md index 25c3883..e15c7ef 100644 --- a/Sources/Lyrebird/Lyrebird.docc/Generators/SignalAnalysis.md +++ b/Sources/Lyrebird/Lyrebird.docc/Generators/SignalAnalysis.md @@ -81,6 +81,13 @@ last `lfo` sample observed during the high window. - ``AmplitudeFollower`` - ``FreqTracker`` +### Time-Domain Analysis + +- ``ZeroCrossing`` +- ``Slope`` +- ``RunningMin`` +- ``RunningMax`` + ### Dynamics (analysis-driven) - ``Compressor`` diff --git a/Sources/Lyrebird/Lyrebird.docc/Generators/Triggers.md b/Sources/Lyrebird/Lyrebird.docc/Generators/Triggers.md new file mode 100644 index 0000000..2be318a --- /dev/null +++ b/Sources/Lyrebird/Lyrebird.docc/Generators/Triggers.md @@ -0,0 +1,84 @@ +# Triggers and Timing + +@Metadata { + @PageKind(article) +} + +Generators that detect, shape, delay, count, and step on trigger edges. A *trigger* is +a rising edge — a sample that crosses from `≤ 0` to `> 0`. These are the building blocks +of drum machines, arpeggiators, gate logic, and clock-driven sequencing. + +Each generator provides an `.Audio` (sample-accurate) and a `.Control` (block-rate) +variant. The Control variants run the same state machine across the block but emit a flat +block-final value — trigger and counter outputs are discrete and are never smoothed/ramped. + +For sending a trigger from the audio graph back to the language side, see ``SendTrigger`` +(). For latching and gating an arbitrary signal on a trigger, see +``Gate`` / ``SampleAndHold`` in . + +--- + +## Pulse Shaping + +``Trig`` and ``Trig1`` stretch a momentary trigger into a gate of fixed duration. +``Trig`` holds the *input level* captured at the edge; ``Trig1`` holds unity (`1.0`). +A new edge during the hold restarts the timer. + +```swift +Trig.Audio(input: impulse, dur: 0.1) // hold the trigger level for 100 ms +Trig1.Audio(input: impulse, dur: 0.05) // 50 ms unity gate on each edge +``` + +- `dur` — hold time in seconds (init-time scalar). Defaults to `0.1`. + +## Trigger Delay and Counting + +``TriggeredDelay`` re-fires a trigger after a delay (ignoring edges while counting); +``PulseCount`` accumulates a running count of rising edges with an optional reset. + +```swift +TriggeredDelay.Audio(input: impulse, dur: 0.25) // echo the trigger 250 ms later +PulseCount.Audio(trig: clock, reset: bar) // count clocks, reset each bar +``` + +- `dur` — delay in seconds (init-time scalar). Defaults to `0.1`. +- `reset` — any ``ValidGeneratorInput``; a rising edge zeroes the count. Defaults to `0.0`. + +## Stepping + +``Stepper`` walks an integer counter by `step` on each trigger, wrapping inclusively in +`[min, max]`, with an optional reset to `resetval`. Ideal as a step-sequencer index. + +```swift +Stepper.Audio(trig: clock, reset: 0.0, min: 0, max: 7, step: 1) // 0,1,…,7,0,… +``` + +- `min` / `max` / `step` / `resetval` — init-time `Int` scalars. `max >= min` required. + +## Threshold Detection + +``Schmidt`` is a Schmitt trigger with hysteresis: output goes to `1` when the input rises +above `hi`, back to `0` when it falls below `lo`, and holds in between. + +```swift +Schmidt.Audio(input: sig, lo: -0.2, hi: 0.2) // hysteresis band [-0.2, 0.2] +``` + +- `lo` / `hi` — any ``ValidGeneratorInput``; switch-off and switch-on thresholds. + +## Topics + +### Pulse Shaping + +- ``Trig`` +- ``Trig1`` + +### Trigger Delay and Counting + +- ``TriggeredDelay`` +- ``PulseCount`` + +### Stepping and Thresholds + +- ``Stepper`` +- ``Schmidt`` diff --git a/Sources/Lyrebird/Lyrebird.docc/Generators/Waveshaping.md b/Sources/Lyrebird/Lyrebird.docc/Generators/Waveshaping.md new file mode 100644 index 0000000..c891f2d --- /dev/null +++ b/Sources/Lyrebird/Lyrebird.docc/Generators/Waveshaping.md @@ -0,0 +1,73 @@ +# Waveshaping and Distortion + +@Metadata { + @PageKind(article) +} + +Nonlinear amplitude shaping: an arbitrary transfer-function lookup, a crossover/dead-zone +distortion, and a stochastic sample-dropping effect. + +These complement the closed-form shapers in (``Tanh`` / ``SoftClip`` +/ ``Clip`` / ``Fold`` / ``Wrap``). + +--- + +## Waveshaper + +``Waveshaper`` maps the input through a transfer curve stored in a ``LyrebirdBuffer``. The +input is clamped to `[-1, 1]` and used to index the table with linear interpolation (the +table edges *saturate* — they do not wrap). Build the curve with the buffer fill helpers +(see ), e.g. ``LyrebirdBuffer/fillChebyshev(coefficients:)`` for +harmonic waveshaping or ``LyrebirdBuffer/fillWaveshaper(_:)`` for preset distortion curves. +The table is held via an RT-safe slot and can be swapped live with `setTable(_:engine:)`. + +```swift +let curve = LyrebirdBuffer(count: 1024) +curve.fillChebyshev(coefficients: [0, 1, 0, 0.3]) // add a 3rd harmonic +let shaped = Waveshaper.Audio(table: curve, input: osc) +``` + +- `table` — mono ``LyrebirdBuffer`` transfer curve (≥ 2 frames). +- `input` — any ``ValidGeneratorInput``; clamped to `[-1, 1]`. + +## CrossoverDistortion + +``CrossoverDistortion`` applies a dead-zone of half-width `amp`: input within `[-amp, amp]` +is silenced, beyond it passes linearly. `smooth ∈ [0, 1]` rounds the corner with a +C1-continuous quadratic knee of width `amp · smooth`. Models transistor crossover artefacts; +useful for grit and gating-style distortion. + +```swift +CrossoverDistortion.Audio(input: sig, amp: 0.1, smooth: 0.0) // hard dead zone +CrossoverDistortion.Audio(input: sig, amp: 0.1, smooth: 0.5) // softened knee +``` + +- `amp` — dead-zone half-width (≥ 0, SuperCollider's crossover threshold). Defaults to `0.5`. +- `smooth` — knee smoothness `[0, 1]`; `0` is a hard knee. Defaults to `0.0`. + +## Disintegrator + +``Disintegrator`` randomly "disintegrates" samples: with probability `probability` a sample +is replaced by `input × multiplier` (default `0` = silence), otherwise it passes unchanged. +Produces glitch / dropout / bit-erosion textures. Audio-only — the stochastic draw advances +per sample and has no block-rate form. + +```swift +Disintegrator.Audio(input: sig, probability: 0.3, multiplier: 0.0) // drop ~30% to silence +Disintegrator.Audio(input: sig, probability: 0.5, seed: 42) // deterministic +``` + +- `probability` — `[0, 1]` chance a sample is disintegrated. Defaults to `0.5`. +- `multiplier` — factor applied to disintegrated samples. Defaults to `0.0`. +- `seed` — `UInt64?` PRNG seed; `nil` = time-derived. Defaults to `nil`. + +## Topics + +### Transfer-Function Shaping + +- ``Waveshaper`` + +### Distortion + +- ``CrossoverDistortion`` +- ``Disintegrator`` diff --git a/Sources/Lyrebird/Lyrebird.docc/Lyrebird.md b/Sources/Lyrebird/Lyrebird.docc/Lyrebird.md index 1c14fd0..52bfe4f 100644 --- a/Sources/Lyrebird/Lyrebird.docc/Lyrebird.md +++ b/Sources/Lyrebird/Lyrebird.docc/Lyrebird.md @@ -51,6 +51,10 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass - +### Waveshaping and Distortion + +- + ### Reverb Library - @@ -68,6 +72,10 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass - - +### Triggers and Timing + +- + ### Pitch Shifting - @@ -92,6 +100,7 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass - - - +- ### Bus Allocation diff --git a/Sources/Lyrebird/Math/CubicInterpolation.swift b/Sources/Lyrebird/Math/CubicInterpolation.swift new file mode 100644 index 0000000..cf77ef1 --- /dev/null +++ b/Sources/Lyrebird/Math/CubicInterpolation.swift @@ -0,0 +1,50 @@ +// CubicInterpolation.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// MARK: - Catmull-Rom cubic kernel + +/// Named coefficients of the 4-point Catmull-Rom cubic kernel (expanded form). +/// `2` is omitted — it is exempt from the named-constant rule and reads clearly +/// inline (`2 * p0`, `2 * pM1`). +private let catmullRomHalf: Double = 0.5 +private let catmullRomFive: Double = 5.0 +private let catmullRomFour: Double = 4.0 +private let catmullRomThree: Double = 3.0 + +/// 4-point Catmull-Rom cubic interpolation. +/// +/// Returns the spline value at `t ∈ [0, 1]` on the segment between `p0` and `p1`, +/// using the surrounding samples `pM1` (before `p0`) and `p2` (after `p1`): +/// +/// ``` +/// p(t) = 0.5 · ( 2·p0 +/// + (−pM1 + p1)·t +/// + (2·pM1 − 5·p0 + 4·p1 − p2)·t² +/// + (−pM1 + 3·p0 − 3·p1 + p2)·t³ ) +/// ``` +/// +/// This is the single source of the cubic kernel shared by every interpolated +/// reader in the framework — table-lookup oscillators (`OscSin`, `OscTable`, +/// `oscillatorTableReadCubic`), buffer playback (`PlayBuffer`), the chaotic +/// oscillators (`chaoticInterpolate`), and the fractional-delay lines +/// (`DelayLine`, `DelayLineFeedback`, `CombFilter`, `AllpassFilter`). +/// `@inline(__always)` so the generated code matches the previous hand-inlined form. +@inline(__always) +@_spi(LyrebirdExtensions) +public func catmullRomCubic( + _ pM1: Double, + _ p0: Double, + _ p1: Double, + _ p2: Double, + t: Double +) -> Double { + let t2: Double = t * t + let t3: Double = t2 * t + return catmullRomHalf * ((2 * p0) + + (-pM1 + p1) * t + + (2 * pM1 - catmullRomFive * p0 + catmullRomFour * p1 - p2) * t2 + + (-pM1 + catmullRomThree * p0 - catmullRomThree * p1 + p2) * t3) +} diff --git a/Sources/Lyrebird/Utilities/LyrebirdPaths.swift b/Sources/Lyrebird/Utilities/LyrebirdPaths.swift index 70b2298..bee9205 100644 --- a/Sources/Lyrebird/Utilities/LyrebirdPaths.swift +++ b/Sources/Lyrebird/Utilities/LyrebirdPaths.swift @@ -112,9 +112,19 @@ public enum LyrebirdPaths { FileManager.default.temporaryDirectory } - /// The current user's home directory. + /// The user's home directory. + /// + /// On macOS this is the real login home (`/Users/`). On iOS (and other + /// sandboxed platforms) there is no user-writable home — `homeDirectoryForCurrentUser` + /// returns the app's sandbox container root, which is not a usable write target — so + /// this returns the app's Documents directory (``documents``) instead, the canonical + /// writable, user-visible location there. public static var home: URL { + #if os(macOS) FileManager.default.homeDirectoryForCurrentUser + #else + searchPath(.documentDirectory) + #endif } /// The process current working directory. diff --git a/Sources/LyrebirdCLI/CLICommand.swift b/Sources/LyrebirdCLI/CLICommand.swift index b57f65e..179501a 100644 --- a/Sources/LyrebirdCLI/CLICommand.swift +++ b/Sources/LyrebirdCLI/CLICommand.swift @@ -18,7 +18,14 @@ public enum CLICommand: Equatable { /// When `lyrebirdPath` is set, the generated `Package.swift` and (where /// applicable) `.xcodeproj` reference Lyrebird as a local SPM package at /// that absolute path instead of pulling from the published Git URL. - case new(name: String, template: ProjectTemplate, lyrebirdPath: String?) + /// When `shoegazePath` is set (shoegaze template only), the ShoeGaze + /// package is wired as a local SPM dependency at that absolute path. + case new( + name: String, + template: ProjectTemplate, + lyrebirdPath: String?, + shoegazePath: String? + ) /// Run the current project with `swift run`. case run(release: Bool) /// Export a named Synthesizer template to a Swift source file. @@ -69,9 +76,22 @@ public enum CLICommand: Equatable { } else { lyrebirdPath = nil } - return .new(name: arguments[2], - template: template, - lyrebirdPath: lyrebirdPath) + // Optional `--shoegaze-path ` for shoegaze template only. + // Value must not be a flag token. + let shoegazePath: String? + if let sIdx: Array.Index = arguments.firstIndex(of: "--shoegaze-path"), + sIdx + 1 < arguments.count, + !arguments[sIdx + 1].hasPrefix("-") { + shoegazePath = arguments[sIdx + 1] + } else { + shoegazePath = nil + } + return .new( + name: arguments[2], + template: template, + lyrebirdPath: lyrebirdPath, + shoegazePath: shoegazePath + ) case "run": let release: Bool = arguments.contains("--release") diff --git a/Sources/LyrebirdCLI/LyrebirdCLI.swift b/Sources/LyrebirdCLI/LyrebirdCLI.swift index 0b3b83b..bc8b540 100644 --- a/Sources/LyrebirdCLI/LyrebirdCLI.swift +++ b/Sources/LyrebirdCLI/LyrebirdCLI.swift @@ -25,8 +25,8 @@ struct LyrebirdCLIMain { print("lyrebird \(lyrebirdVersion)") case .help: printHelp() - case .new(let name, let template, let lyrebirdPath): - runNew(name: name, template: template, lyrebirdPath: lyrebirdPath) + case .new(let name, let template, let lyrebirdPath, let shoegazePath): + runNew(name: name, template: template, lyrebirdPath: lyrebirdPath, shoegazePath: shoegazePath) case .run(let release): runProject(release: release) case .export(let name, let toPath, let overwrite): @@ -106,7 +106,8 @@ struct LyrebirdCLIMain { private static func runNew( name: String, template: ProjectTemplate, - lyrebirdPath: String? + lyrebirdPath: String?, + shoegazePath: String? = nil ) { let resolvedPath: String? if let p: String = lyrebirdPath { @@ -129,11 +130,34 @@ struct LyrebirdCLIMain { """, stderr) } + + // Resolve ShoeGaze path (shoegaze template only). + let resolvedShoegazePath: String? + if let p: String = shoegazePath { + resolvedShoegazePath = URL(fileURLWithPath: p).standardizedFileURL.path + } else { + resolvedShoegazePath = nil + } + if template == .shoegaze || template == .shoegazeIOS { + if let path: String = resolvedShoegazePath { + print("ShoeGaze dependency: local checkout at \(path)") + } else { + fputs(""" + note: --shoegaze-path not supplied; the generated project will use \ + the placeholder URL \(ProjectScaffolder.shoegazePackageURL). \ + Edit the project or re-run with --shoegaze-path \ + until ShoeGaze is published at that URL. + + """, stderr) + } + } + do { try ProjectScaffolder.scaffold( name: name, template: template, - lyrebirdPath: effectivePath + lyrebirdPath: effectivePath, + shoegazePath: resolvedShoegazePath ) print("Created \(name)/") } catch ProjectScaffolder.Error.projectExists(let n) { @@ -194,8 +218,15 @@ struct LyrebirdCLIMain { Usage: lyrebird [command] Commands: - new [--template ] Scaffold a new Lyrebird Swift Package - Templates: basic (default), demo, ui-demo, nrt, score + new [--template ] Scaffold a new Lyrebird project + SPM templates (open Package.swift in Xcode): + basic (default), demo, ui-demo, nrt, score + Xcode-project templates (build to .app or .appex): + shoegaze macOS guitar-pedalboard app (Xcode, .app) + shoegaze-ios iOS guitar-pedalboard app (Xcode, .app) + macos-ui-xcode macOS @UIParam synth app + ios-ui iOS @UIParam synth app + auv3 AUv3 host + .appex run [--release] Build and run the current project export [--to p] Export a Synthesizer template to a .swift file install-templates [--force] Install Xcode file templates (Generator, @@ -205,6 +236,13 @@ struct LyrebirdCLIMain { version Print lyrebird version help Show this help + Flags for `new`: + --template Template name (see above) + --lyrebird-path Use a local Lyrebird checkout instead of the + published remote package URL + --shoegaze-path (shoegaze / shoegaze-ios) Use a local ShoeGaze + checkout instead of the placeholder remote URL + Run `lyrebird` with no arguments for an interactive shell. """) } diff --git a/Sources/LyrebirdCLI/ProjectScaffolder+ShoeGazeIOS.swift b/Sources/LyrebirdCLI/ProjectScaffolder+ShoeGazeIOS.swift new file mode 100644 index 0000000..323e75a --- /dev/null +++ b/Sources/LyrebirdCLI/ProjectScaffolder+ShoeGazeIOS.swift @@ -0,0 +1,526 @@ +// ProjectScaffolder+ShoeGazeIOS.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +// MARK: - shoegaze-ios template + +extension ProjectScaffolder { + + /// Write the full `shoegaze-ios` template tree at `projectRoot`. + /// + /// Single iOS application target. SwiftUI `@main` entry point wired to + /// `iOSAudioDriver` via `AVAudioSession`. Lyrebird + LyrebirdUI + + /// LyrebirdShoeGaze + LyrebirdShoeGazeUI pulled in via SPM dependencies. + /// A default board (Overdrive → Delay → Reverb → Modulation) fed by the + /// built-in test loop is constructed at launch inside an `@Observable` + /// `AppModel`. + static func writeShoeGazeIOSFiles( + name: String, + projectRoot: String, + lyrebirdPath: String?, + shoegazePath: String?, + fm: FileManager + ) throws { + let appGroupDir: String = (projectRoot as NSString).appendingPathComponent(name) + let xcodeprojDir: String = (projectRoot as NSString).appendingPathComponent("\(name).xcodeproj") + let schemeDir: String = (xcodeprojDir as NSString) + .appendingPathComponent("xcshareddata/xcschemes") + + for dir: String in [appGroupDir, xcodeprojDir, schemeDir] { + do { + try fm.createDirectory(atPath: dir, + withIntermediateDirectories: true, + attributes: nil) + } catch { + try? fm.removeItem(atPath: projectRoot) + throw Error.fileSystemError(path: dir, reason: error.localizedDescription) + } + } + + let files: [(String, String)] = [ + ((appGroupDir as NSString).appendingPathComponent("Info.plist"), + iOSAppInfoPlist(name: name)), + ((appGroupDir as NSString).appendingPathComponent("\(name)App.swift"), + shoegazeIOSAppSwift(name: name)), + ((appGroupDir as NSString).appendingPathComponent("\(name)AppModel.swift"), + shoegazeIOSAppModelSwift(name: name)), + ((xcodeprojDir as NSString).appendingPathComponent("project.pbxproj"), + shoegazeIOSPBXProj(name: name, + lyrebirdPath: lyrebirdPath, + shoegazePath: shoegazePath)), + ((schemeDir as NSString).appendingPathComponent("\(name).xcscheme"), + appScheme(name: name, productExtension: "app")), + ] + try writeFiles(files, fm: fm, projectRoot: projectRoot) + } + + // MARK: - Source files + + /// `App.swift` — SwiftUI `@main` entry point for the shoegaze-ios template. + /// + /// Emitted source must not contain the Lyrebird MIT copyright header. + static func shoegazeIOSAppSwift(name: String) -> String { + """ + // \(name) — entry point + import SwiftUI + import LyrebirdShoeGazeUI + + @main + struct \(name)App: App { + @State private var model: \(name)AppModel = \(name)AppModel() + + var body: some Scene { + WindowGroup { + NavigationStack { + ScrollView { + ShoeGazeView(shoeGaze: model.shoeGaze) + .padding(.horizontal, 12) + } + .navigationTitle("\(name)") + } + .onAppear { model.start() } + .onDisappear { model.stop() } + } + } + } + """ + } + + /// `AppModel.swift` — `@Observable` model owning the engine and `ShoeGaze`. + /// + /// Emitted source must not contain the Lyrebird MIT copyright header. + static func shoegazeIOSAppModelSwift(name: String) -> String { + let blockSize: Int = scaffoldDefaultBlockSize + let outputChannels: Int = scaffoldDefaultOutputChannels + return """ + // \(name)AppModel.swift + import AVFoundation + import Observation + import LyrebirdSynth + import LyrebirdShoeGaze + + /// Owns the `SynthesisEngine` and `ShoeGaze` manager for \(name). + /// + /// Call `start()` when the root view appears and `stop()` when it disappears. + /// The engine uses the hardware sample rate from `AVAudioSession` so pitch + /// and timing are accurate on all iOS devices. + @Observable + @MainActor + final class \(name)AppModel { + + private(set) var shoeGaze: ShoeGaze + private let engine: SynthesisEngine + + init() { + // Activate the session before querying `sampleRate` so the + // hardware rate is known (iOS locks to 48 000 Hz on most devices + // regardless of the preferred rate). + let session: AVAudioSession = AVAudioSession.sharedInstance() + try? session.setCategory(.playback, mode: .default) + try? session.setActive(true) + let sampleRate: Double = session.sampleRate + + let eng: SynthesisEngine = SynthesisEngine( + blockSize: \(blockSize), + sampleRate: sampleRate, + numOutputChannels: \(outputChannels), + numInputChannels: 0, + driver: iOSAudioDriver() + ) + self.engine = eng + self.shoeGaze = ShoeGaze(engine: eng) + + do { + let board: PedalBoard = try shoeGaze.addBoard() + try board.add(OverdrivePedal()) + try board.add(DelayPedal()) + try board.add(ReverbPedal()) + try board.add(ModulationPedal()) + try shoeGaze.finalizeBoard(board) + } catch { + print("[\(name)] board build failed: \\(error)") + } + } + + /// Start the audio engine. Call from `.onAppear`. + func start() { + do { + try engine.start() + } catch { + print("[\(name)] engine.start failed: \\(error)") + } + } + + /// Stop the audio engine. Call from `.onDisappear`. + func stop() { + engine.stop() + } + } + """ + } + + // MARK: - pbxproj + + /// `project.pbxproj` for the `shoegaze-ios` template. + /// + /// Identical in structure to the `ios-ui` pbxproj but: + /// - Declares two source files (`App.swift` + `AppModel.swift`) + /// using the `sg`-prefixed UUID constants so they don't collide with the + /// `ios-ui` constants. + /// - References three SPM products: `LyrebirdUI`, `LyrebirdShoeGaze`, and + /// `LyrebirdShoeGazeUI` — the last two from a second package reference + /// pointing at the ShoeGaze package. + static func shoegazeIOSPBXProj( + name: String, + lyrebirdPath: String? = nil, + shoegazePath: String? = nil + ) -> String { + let bundleID: String = "\(defaultBundleIdentifierPrefix).\(name)" + let lyrebirdRefLabel: String = pbxPackageReferenceLabel(lyrebirdPath: lyrebirdPath) + let lyrebirdRefSection: String = pbxPackageReferenceSection(lyrebirdPath: lyrebirdPath) + let shoegazeRefLabel: String = shoegazePackageReferenceLabel(shoegazePath: shoegazePath) + let shoegazeRefSection: String = shoegazePackageReferenceSection(shoegazePath: shoegazePath) + + return """ + // !$*UTF8*$! + { + \tarchiveVersion = 1; + \tclasses = { + \t}; + \tobjectVersion = 60; + \tobjects = { + + /* Begin PBXBuildFile section */ + \t\t\(pbxSGAppFileBuild) /* \(name)App.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxSGAppFileRef) /* \(name)App.swift */; }; + \t\t\(pbxSGAppModelBuild) /* \(name)AppModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxSGAppModelRef) /* \(name)AppModel.swift */; }; + \t\t\(pbxLyrebirdUIFrameworkBuild) /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = \(pbxLyrebirdUIProductDep) /* LyrebirdUI */; }; + \t\t\(pbxSGShoeGazeBuild) /* LyrebirdShoeGaze in Frameworks */ = {isa = PBXBuildFile; productRef = \(pbxSGShoeGazeDep) /* LyrebirdShoeGaze */; }; + \t\t\(pbxSGShoeGazeUIBuild) /* LyrebirdShoeGazeUI in Frameworks */ = {isa = PBXBuildFile; productRef = \(pbxSGShoeGazeUIDep) /* LyrebirdShoeGazeUI */; }; + /* End PBXBuildFile section */ + + /* Begin PBXFileReference section */ + \t\t\(pbxAppProductRef) /* \(name).app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = \(name).app; sourceTree = BUILT_PRODUCTS_DIR; }; + \t\t\(pbxInfoPlistRef) /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + \t\t\(pbxSGAppFileRef) /* \(name)App.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = \(name)App.swift; sourceTree = ""; }; + \t\t\(pbxSGAppModelRef) /* \(name)AppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = \(name)AppModel.swift; sourceTree = ""; }; + /* End PBXFileReference section */ + + /* Begin PBXFrameworksBuildPhase section */ + \t\t\(pbxFrameworksPhase) /* Frameworks */ = { + \t\t\tisa = PBXFrameworksBuildPhase; + \t\t\tbuildActionMask = \(pbxBuildActionMask); + \t\t\tfiles = ( + \t\t\t\t\(pbxLyrebirdUIFrameworkBuild) /* LyrebirdUI in Frameworks */, + \t\t\t\t\(pbxSGShoeGazeBuild) /* LyrebirdShoeGaze in Frameworks */, + \t\t\t\t\(pbxSGShoeGazeUIBuild) /* LyrebirdShoeGazeUI in Frameworks */, + \t\t\t); + \t\t\trunOnlyForDeploymentPostprocessing = 0; + \t\t}; + /* End PBXFrameworksBuildPhase section */ + + /* Begin PBXGroup section */ + \t\t\(pbxMainGroup) = { + \t\t\tisa = PBXGroup; + \t\t\tchildren = ( + \t\t\t\t\(pbxAppGroup) /* \(name) */, + \t\t\t\t\(pbxProductsGroup) /* Products */, + \t\t\t); + \t\t\tsourceTree = ""; + \t\t}; + \t\t\(pbxProductsGroup) /* Products */ = { + \t\t\tisa = PBXGroup; + \t\t\tchildren = ( + \t\t\t\t\(pbxAppProductRef) /* \(name).app */, + \t\t\t); + \t\t\tname = Products; + \t\t\tsourceTree = ""; + \t\t}; + \t\t\(pbxAppGroup) /* \(name) */ = { + \t\t\tisa = PBXGroup; + \t\t\tchildren = ( + \t\t\t\t\(pbxSGAppFileRef) /* \(name)App.swift */, + \t\t\t\t\(pbxSGAppModelRef) /* \(name)AppModel.swift */, + \t\t\t\t\(pbxInfoPlistRef) /* Info.plist */, + \t\t\t); + \t\t\tpath = \(name); + \t\t\tsourceTree = ""; + \t\t}; + /* End PBXGroup section */ + + /* Begin PBXNativeTarget section */ + \t\t\(pbxBlueprintIDApp) /* \(name) */ = { + \t\t\tisa = PBXNativeTarget; + \t\t\tbuildConfigurationList = \(pbxAppBuildConfigList) /* Build configuration list for PBXNativeTarget "\(name)" */; + \t\t\tbuildPhases = ( + \t\t\t\t\(pbxSourcesPhase) /* Sources */, + \t\t\t\t\(pbxFrameworksPhase) /* Frameworks */, + \t\t\t\t\(pbxResourcesPhase) /* Resources */, + \t\t\t); + \t\t\tbuildRules = ( + \t\t\t); + \t\t\tdependencies = ( + \t\t\t); + \t\t\tname = \(name); + \t\t\tpackageProductDependencies = ( + \t\t\t\t\(pbxLyrebirdUIProductDep) /* LyrebirdUI */, + \t\t\t\t\(pbxSGShoeGazeDep) /* LyrebirdShoeGaze */, + \t\t\t\t\(pbxSGShoeGazeUIDep) /* LyrebirdShoeGazeUI */, + \t\t\t); + \t\t\tproductName = \(name); + \t\t\tproductReference = \(pbxAppProductRef) /* \(name).app */; + \t\t\tproductType = "com.apple.product-type.application"; + \t\t}; + /* End PBXNativeTarget section */ + + /* Begin PBXProject section */ + \t\t\(pbxRootObject) /* Project object */ = { + \t\t\tisa = PBXProject; + \t\t\tattributes = { + \t\t\t\tBuildIndependentTargetsInParallel = 1; + \t\t\t\tLastSwiftUpdateCheck = 1600; + \t\t\t\tLastUpgradeCheck = 1600; + \t\t\t\tTargetAttributes = { + \t\t\t\t\t\(pbxBlueprintIDApp) = { + \t\t\t\t\t\tCreatedOnToolsVersion = 16.0; + \t\t\t\t\t}; + \t\t\t\t}; + \t\t\t}; + \t\t\tbuildConfigurationList = \(pbxProjectBuildConfigList) /* Build configuration list for PBXProject "\(name)" */; + \t\t\tcompatibilityVersion = "Xcode 14.0"; + \t\t\tdevelopmentRegion = en; + \t\t\thasScannedForEncodings = 0; + \t\t\tknownRegions = ( + \t\t\t\ten, + \t\t\t\tBase, + \t\t\t); + \t\t\tmainGroup = \(pbxMainGroup); + \t\t\tpackageReferences = ( + \t\t\t\t\(pbxRemoteSPMRef) /* \(lyrebirdRefLabel) */, + \t\t\t\t\(pbxSGShoeGazePackageRef) /* \(shoegazeRefLabel) */, + \t\t\t); + \t\t\tproductRefGroup = \(pbxProductsGroup) /* Products */; + \t\t\tprojectDirPath = ""; + \t\t\tprojectRoot = ""; + \t\t\ttargets = ( + \t\t\t\t\(pbxBlueprintIDApp) /* \(name) */, + \t\t\t); + \t\t}; + /* End PBXProject section */ + + /* Begin PBXResourcesBuildPhase section */ + \t\t\(pbxResourcesPhase) /* Resources */ = { + \t\t\tisa = PBXResourcesBuildPhase; + \t\t\tbuildActionMask = \(pbxBuildActionMask); + \t\t\tfiles = ( + \t\t\t); + \t\t\trunOnlyForDeploymentPostprocessing = 0; + \t\t}; + /* End PBXResourcesBuildPhase section */ + + /* Begin PBXSourcesBuildPhase section */ + \t\t\(pbxSourcesPhase) /* Sources */ = { + \t\t\tisa = PBXSourcesBuildPhase; + \t\t\tbuildActionMask = \(pbxBuildActionMask); + \t\t\tfiles = ( + \t\t\t\t\(pbxSGAppFileBuild) /* \(name)App.swift in Sources */, + \t\t\t\t\(pbxSGAppModelBuild) /* \(name)AppModel.swift in Sources */, + \t\t\t); + \t\t\trunOnlyForDeploymentPostprocessing = 0; + \t\t}; + /* End PBXSourcesBuildPhase section */ + + /* Begin XCBuildConfiguration section */ + \t\t\(pbxAppDebugConfig) /* Debug */ = { + \t\t\tisa = XCBuildConfiguration; + \t\t\tbuildSettings = { + \t\t\t\tCODE_SIGN_STYLE = Automatic; + \t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf; + \t\t\t\tGENERATE_INFOPLIST_FILE = NO; + \t\t\t\tINFOPLIST_FILE = \(name)/Info.plist; + \t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 18.0; + \t\t\t\tLD_RUNPATH_SEARCH_PATHS = ( + \t\t\t\t\t"$(inherited)", + \t\t\t\t\t"@executable_path/Frameworks", + \t\t\t\t); + \t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \(bundleID); + \t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)"; + \t\t\t\tSWIFT_VERSION = 6.0; + \t\t\t\tTARGETED_DEVICE_FAMILY = "1,2"; + \t\t\t}; + \t\t\tname = Debug; + \t\t}; + \t\t\(pbxAppReleaseConfig) /* Release */ = { + \t\t\tisa = XCBuildConfiguration; + \t\t\tbuildSettings = { + \t\t\t\tCODE_SIGN_STYLE = Automatic; + \t\t\t\tDEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + \t\t\t\tGENERATE_INFOPLIST_FILE = NO; + \t\t\t\tINFOPLIST_FILE = \(name)/Info.plist; + \t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 18.0; + \t\t\t\tLD_RUNPATH_SEARCH_PATHS = ( + \t\t\t\t\t"$(inherited)", + \t\t\t\t\t"@executable_path/Frameworks", + \t\t\t\t); + \t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \(bundleID); + \t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)"; + \t\t\t\tSWIFT_VERSION = 6.0; + \t\t\t\tTARGETED_DEVICE_FAMILY = "1,2"; + \t\t\t}; + \t\t\tname = Release; + \t\t}; + \t\t\(pbxProjectDebugConfig) /* Debug */ = { + \t\t\tisa = XCBuildConfiguration; + \t\t\tbuildSettings = { + \t\t\t\tALWAYS_SEARCH_USER_PATHS = NO; + \t\t\t\tCLANG_ENABLE_OBJC_ARC = YES; + \t\t\t\tCOPY_PHASE_STRIP = NO; + \t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf; + \t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES; + \t\t\t\tENABLE_TESTABILITY = YES; + \t\t\t\tENABLE_USER_SCRIPT_SANDBOXING = YES; + \t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu17; + \t\t\t\tGCC_NO_COMMON_BLOCKS = YES; + \t\t\t\tGCC_OPTIMIZATION_LEVEL = 0; + \t\t\t\tONLY_ACTIVE_ARCH = YES; + \t\t\t\tSDKROOT = iphoneos; + \t\t\t\tSWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + \t\t\t\tSWIFT_OPTIMIZATION_LEVEL = "-Onone"; + \t\t\t}; + \t\t\tname = Debug; + \t\t}; + \t\t\(pbxProjectReleaseConfig) /* Release */ = { + \t\t\tisa = XCBuildConfiguration; + \t\t\tbuildSettings = { + \t\t\t\tALWAYS_SEARCH_USER_PATHS = NO; + \t\t\t\tCLANG_ENABLE_OBJC_ARC = YES; + \t\t\t\tCOPY_PHASE_STRIP = NO; + \t\t\t\tDEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + \t\t\t\tENABLE_NS_ASSERTIONS = NO; + \t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES; + \t\t\t\tENABLE_USER_SCRIPT_SANDBOXING = YES; + \t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu17; + \t\t\t\tGCC_NO_COMMON_BLOCKS = YES; + \t\t\t\tSDKROOT = iphoneos; + \t\t\t\tSWIFT_COMPILATION_MODE = wholemodule; + \t\t\t\tSWIFT_OPTIMIZATION_LEVEL = "-O"; + \t\t\t}; + \t\t\tname = Release; + \t\t}; + /* End XCBuildConfiguration section */ + + /* Begin XCConfigurationList section */ + \t\t\(pbxAppBuildConfigList) /* Build configuration list for PBXNativeTarget "\(name)" */ = { + \t\t\tisa = XCConfigurationList; + \t\t\tbuildConfigurations = ( + \t\t\t\t\(pbxAppDebugConfig) /* Debug */, + \t\t\t\t\(pbxAppReleaseConfig) /* Release */, + \t\t\t); + \t\t\tdefaultConfigurationIsVisible = 0; + \t\t\tdefaultConfigurationName = Release; + \t\t}; + \t\t\(pbxProjectBuildConfigList) /* Build configuration list for PBXProject "\(name)" */ = { + \t\t\tisa = XCConfigurationList; + \t\t\tbuildConfigurations = ( + \t\t\t\t\(pbxProjectDebugConfig) /* Debug */, + \t\t\t\t\(pbxProjectReleaseConfig) /* Release */, + \t\t\t); + \t\t\tdefaultConfigurationIsVisible = 0; + \t\t\tdefaultConfigurationName = Release; + \t\t}; + /* End XCConfigurationList section */ + + \(lyrebirdRefSection) + + \(shoegazeRefSection) + + /* Begin XCSwiftPackageProductDependency section */ + \t\t\(pbxLyrebirdUIProductDep) /* LyrebirdUI */ = { + \t\t\tisa = XCSwiftPackageProductDependency; + \t\t\tpackage = \(pbxRemoteSPMRef) /* \(lyrebirdRefLabel) */; + \t\t\tproductName = LyrebirdUI; + \t\t}; + \t\t\(pbxSGShoeGazeDep) /* LyrebirdShoeGaze */ = { + \t\t\tisa = XCSwiftPackageProductDependency; + \t\t\tpackage = \(pbxSGShoeGazePackageRef) /* \(shoegazeRefLabel) */; + \t\t\tproductName = LyrebirdShoeGaze; + \t\t}; + \t\t\(pbxSGShoeGazeUIDep) /* LyrebirdShoeGazeUI */ = { + \t\t\tisa = XCSwiftPackageProductDependency; + \t\t\tpackage = \(pbxSGShoeGazePackageRef) /* \(shoegazeRefLabel) */; + \t\t\tproductName = LyrebirdShoeGazeUI; + \t\t}; + /* End XCSwiftPackageProductDependency section */ + \t}; + \trootObject = \(pbxRootObject) /* Project object */; + } + """ + } + + // MARK: - ShoeGaze package reference helpers + + /// pbxproj snippet for the ShoeGaze SPM package reference. Emits either an + /// `XCRemoteSwiftPackageReference` (when `shoegazePath == nil`) or an + /// `XCLocalSwiftPackageReference` pointing at the absolute path. + static func shoegazePackageReferenceSection(shoegazePath: String?) -> String { + if let path: String = shoegazePath { + let escaped: String = pbxQuoteEscape(path) + return """ + /* Begin XCLocalSwiftPackageReference section */ + \t\t\(pbxSGShoeGazePackageRef) /* XCLocalSwiftPackageReference "shoegaze" */ = { + \t\t\tisa = XCLocalSwiftPackageReference; + \t\t\trelativePath = "\(escaped)"; + \t\t}; + /* End XCLocalSwiftPackageReference section */ + """ + } else { + return """ + /* Begin XCRemoteSwiftPackageReference section */ + \t\t\(pbxSGShoeGazePackageRef) /* XCRemoteSwiftPackageReference "shoegaze" */ = { + \t\t\tisa = XCRemoteSwiftPackageReference; + \t\t\trepositoryURL = "\(shoegazePackageURL)"; + \t\t\trequirement = { + \t\t\t\tkind = upToNextMajorVersion; + \t\t\t\tminimumVersion = \(shoegazeMinimumVersion); + \t\t\t}; + \t\t}; + /* End XCRemoteSwiftPackageReference section */ + """ + } + } + + /// Comment label used in pbxproj for the ShoeGaze package reference. + static func shoegazePackageReferenceLabel(shoegazePath: String?) -> String { + shoegazePath == nil + ? #"XCRemoteSwiftPackageReference "shoegaze""# + : #"XCLocalSwiftPackageReference "shoegaze""# + } + + // MARK: - shoegaze-ios PBX UUID constants + // + // All UUIDs in the `0x03xx` range — no collision with ios-ui (`0x02xx`), + // macos-ui-xcode (`0x01xx`), or auv3 (`0x03Axx` / `0x03xx` note: auv3 + // uses `0x03A0`–`0x03A8`, so shoegaze-ios uses `0x03B0`–`0x03B8`). + + /// `App.swift` file reference UUID. + static let pbxSGAppFileRef: String = "AABB000000000000000003B0" + /// `App.swift` build file UUID. + static let pbxSGAppFileBuild: String = "AABB000000000000000003B1" + /// `AppModel.swift` file reference UUID. + static let pbxSGAppModelRef: String = "AABB000000000000000003B2" + /// `AppModel.swift` build file UUID. + static let pbxSGAppModelBuild: String = "AABB000000000000000003B3" + /// Package reference UUID for the ShoeGaze SPM package. + static let pbxSGShoeGazePackageRef: String = "AABB000000000000000003B4" + /// Product dependency UUID for `LyrebirdShoeGaze`. + static let pbxSGShoeGazeDep: String = "AABB000000000000000003B5" + /// Build file UUID for `LyrebirdShoeGaze` in Frameworks. + static let pbxSGShoeGazeBuild: String = "AABB000000000000000003B6" + /// Product dependency UUID for `LyrebirdShoeGazeUI`. + static let pbxSGShoeGazeUIDep: String = "AABB000000000000000003B7" + /// Build file UUID for `LyrebirdShoeGazeUI` in Frameworks. + static let pbxSGShoeGazeUIBuild: String = "AABB000000000000000003B8" +} diff --git a/Sources/LyrebirdCLI/ProjectScaffolder+ShoeGazeMacOS.swift b/Sources/LyrebirdCLI/ProjectScaffolder+ShoeGazeMacOS.swift new file mode 100644 index 0000000..d3be441 --- /dev/null +++ b/Sources/LyrebirdCLI/ProjectScaffolder+ShoeGazeMacOS.swift @@ -0,0 +1,610 @@ +// ProjectScaffolder+ShoeGazeMacOS.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +// MARK: - shoegaze (macOS Xcode app) template + +extension ProjectScaffolder { + + /// Write the full `shoegaze` macOS app template tree at `projectRoot`. + /// + /// Single macOS application target. SwiftUI `@main` entry point wired to + /// `CoreAudioDriver`. Lyrebird + LyrebirdUI + LyrebirdShoeGaze + + /// LyrebirdShoeGazeUI pulled in via SPM dependencies. A default board + /// (Overdrive → Delay → Reverb → Modulation) fed by the built-in test loop + /// is constructed at launch inside an `@Observable` `AppModel`. + /// + /// An **Audio** menu with **Mute ⌘M** is added via `.commands`. Quit ⌘Q is + /// standard in SwiftUI App and requires no extra code. Recording (Choose + /// Folder / Record / Stop) is already provided by `ShoeGazeView`. + static func writeShoeGazeMacOSFiles( + name: String, + projectRoot: String, + lyrebirdPath: String?, + shoegazePath: String?, + fm: FileManager + ) throws { + let appGroupDir: String = (projectRoot as NSString).appendingPathComponent(name) + let xcodeprojDir: String = (projectRoot as NSString).appendingPathComponent("\(name).xcodeproj") + let schemeDir: String = (xcodeprojDir as NSString) + .appendingPathComponent("xcshareddata/xcschemes") + + for dir: String in [appGroupDir, xcodeprojDir, schemeDir] { + do { + try fm.createDirectory(atPath: dir, + withIntermediateDirectories: true, + attributes: nil) + } catch { + try? fm.removeItem(atPath: projectRoot) + throw Error.fileSystemError(path: dir, reason: error.localizedDescription) + } + } + + let files: [(String, String)] = [ + ((appGroupDir as NSString).appendingPathComponent("Info.plist"), + shoegazeMacOSInfoPlist(name: name)), + ((appGroupDir as NSString).appendingPathComponent("\(name)App.swift"), + shoegazeMacOSAppSwift(name: name)), + ((appGroupDir as NSString).appendingPathComponent("\(name)AppModel.swift"), + shoegazeMacOSAppModelSwift(name: name)), + ((xcodeprojDir as NSString).appendingPathComponent("project.pbxproj"), + shoegazeMacOSPBXProj(name: name, + lyrebirdPath: lyrebirdPath, + shoegazePath: shoegazePath)), + ((schemeDir as NSString).appendingPathComponent("\(name).xcscheme"), + appScheme(name: name, productExtension: "app")), + ] + try writeFiles(files, fm: fm, projectRoot: projectRoot) + } + + // MARK: - Source files + + /// `Info.plist` for the shoegaze macOS app. + /// + /// Extends the standard macOS plist with `NSMicrophoneUsageDescription` + /// (required when switching to `.liveInput`), `NSHighResolutionCapable`, + /// and `LSApplicationCategoryType` set to music. + static func shoegazeMacOSInfoPlist(name: String) -> String { + let bundleIdSetting: String = "$(PRODUCT_BUNDLE_IDENTIFIER)" + let bundleNameSetting: String = "$(PRODUCT_NAME)" + let executableNameSetting: String = "$(EXECUTABLE_NAME)" + let deploymentTargetSetting: String = "$(MACOSX_DEPLOYMENT_TARGET)" + return """ + + + + + CFBundleExecutable + \(executableNameSetting) + CFBundleIdentifier + \(bundleIdSetting) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + \(bundleNameSetting) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSApplicationCategoryType + public.app-category.music + LSMinimumSystemVersion + \(deploymentTargetSetting) + NSHighResolutionCapable + + NSMicrophoneUsageDescription + \(name) requires microphone access for live guitar and audio input. + NSPrincipalClass + NSApplication + NSHumanReadableCopyright + Copyright © \(currentYearString()) \(name). All rights reserved. + + + """ + } + + /// `App.swift` — SwiftUI `@main` entry point for the shoegaze macOS template. + /// + /// Emitted source must not contain the Lyrebird MIT copyright header. + static func shoegazeMacOSAppSwift(name: String) -> String { + """ + // \(name) — entry point + import SwiftUI + import LyrebirdShoeGazeUI + + @main + struct \(name)App: App { + @State private var model: \(name)AppModel = \(name)AppModel() + + var body: some Scene { + WindowGroup { + ShoeGazeView(shoeGaze: model.shoeGaze) + .frame(minWidth: 960, minHeight: 480) + .onAppear { model.start() } + .onDisappear { model.stop() } + } + .commands { + CommandMenu("Audio") { + Button(model.muted ? "Unmute" : "Mute") { + model.toggleMute() + } + .keyboardShortcut("m", modifiers: .command) + } + } + } + } + """ + } + + /// `AppModel.swift` — `@Observable` model owning the engine and `ShoeGaze`. + /// + /// Emitted source must not contain the Lyrebird MIT copyright header. + static func shoegazeMacOSAppModelSwift(name: String) -> String { + let blockSize: Int = scaffoldDefaultBlockSize + let sampleRate: Double = 48_000.0 + let outputChannels: Int = scaffoldDefaultOutputChannels + let audioBusCount: Int = 256 + return """ + // \(name)AppModel.swift + import Observation + import LyrebirdSynth + import LyrebirdShoeGaze + + /// Owns the `SynthesisEngine` and `ShoeGaze` manager for \(name). + /// + /// Call `start()` when the root view appears and `stop()` when it disappears. + /// `toggleMute()` stops and restarts the engine, providing a click-free + /// silence while parameters remain live. + @Observable + @MainActor + final class \(name)AppModel { + + private(set) var shoeGaze: ShoeGaze + private(set) var muted: Bool = false + private let engine: SynthesisEngine + + init() { + let eng: SynthesisEngine = SynthesisEngine( + blockSize: \(blockSize), + sampleRate: \(sampleRate), + numOutputChannels: \(outputChannels), + numInputChannels: 0, + numAudioBuses: \(audioBusCount), + driver: CoreAudioDriver() + ) + self.engine = eng + self.shoeGaze = ShoeGaze(engine: eng) + + do { + let board: PedalBoard = try shoeGaze.addBoard() + try board.add(OverdrivePedal()) + try board.add(DelayPedal()) + try board.add(ReverbPedal()) + try board.add(ModulationPedal()) + try shoeGaze.finalizeBoard(board) + } catch { + print("[\(name)] board build failed: \\(error)") + } + } + + /// Start the audio engine. Call from `.onAppear`. + func start() { + guard !muted else { return } + do { + try engine.start() + } catch { + print("[\(name)] engine.start failed: \\(error)") + } + } + + /// Stop the audio engine. Call from `.onDisappear`. + func stop() { + engine.stop() + } + + /// Toggle mute by stopping/starting the engine. + func toggleMute() { + if muted { + muted = false + do { + try engine.start() + } catch { + print("[\(name)] engine.start (unmute) failed: \\(error)") + } + } else { + engine.stop() + muted = true + } + } + } + """ + } + + // MARK: - pbxproj + + /// `project.pbxproj` for the `shoegaze` macOS app template. + /// + /// Structure mirrors `shoegazeIOSPBXProj` but uses `SDKROOT = macosx`, + /// `MACOSX_DEPLOYMENT_TARGET = 15.0`, macOS-style `LD_RUNPATH_SEARCH_PATHS`, + /// `ENABLE_HARDENED_RUNTIME`, `COMBINE_HIDPI_IMAGES`, and `DEAD_CODE_STRIPPING`. + /// UUIDs are in the `0x03Cxx` range — no collision with ios-ui (`0x02xx`), + /// macos-ui-xcode (`0x01xx`), auv3 (`0x03Axx`), or shoegaze-ios (`0x03Bxx`). + /// Depends on four SPM products: `Lyrebird`, `LyrebirdUI`, `LyrebirdShoeGaze`, + /// `LyrebirdShoeGazeUI`. + static func shoegazeMacOSPBXProj( + name: String, + lyrebirdPath: String? = nil, + shoegazePath: String? = nil + ) -> String { + let bundleID: String = "\(defaultBundleIdentifierPrefix).\(name)" + let lyrebirdRefLabel: String = pbxPackageReferenceLabel(lyrebirdPath: lyrebirdPath) + let lyrebirdRefSection: String = pbxPackageReferenceSection(lyrebirdPath: lyrebirdPath) + let shoegazeRefLabel: String = shoegazeMacOSPackageReferenceLabel(shoegazePath: shoegazePath) + let shoegazeRefSection: String = shoegazeMacOSPackageReferenceSection(shoegazePath: shoegazePath) + + return """ + // !$*UTF8*$! + { + \tarchiveVersion = 1; + \tclasses = { + \t}; + \tobjectVersion = 60; + \tobjects = { + + /* Begin PBXBuildFile section */ + \t\t\(pbxSGMacAppFileBuild) /* \(name)App.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxSGMacAppFileRef) /* \(name)App.swift */; }; + \t\t\(pbxSGMacAppModelBuild) /* \(name)AppModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxSGMacAppModelRef) /* \(name)AppModel.swift */; }; + \t\t\(pbxSGMacLyrebirdBuild) /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = \(pbxSGMacLyrebirdDep) /* Lyrebird */; }; + \t\t\(pbxLyrebirdUIFrameworkBuild) /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = \(pbxLyrebirdUIProductDep) /* LyrebirdUI */; }; + \t\t\(pbxSGMacShoeGazeBuild) /* LyrebirdShoeGaze in Frameworks */ = {isa = PBXBuildFile; productRef = \(pbxSGMacShoeGazeDep) /* LyrebirdShoeGaze */; }; + \t\t\(pbxSGMacShoeGazeUIBuild) /* LyrebirdShoeGazeUI in Frameworks */ = {isa = PBXBuildFile; productRef = \(pbxSGMacShoeGazeUIDep) /* LyrebirdShoeGazeUI */; }; + /* End PBXBuildFile section */ + + /* Begin PBXFileReference section */ + \t\t\(pbxAppProductRef) /* \(name).app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = \(name).app; sourceTree = BUILT_PRODUCTS_DIR; }; + \t\t\(pbxInfoPlistRef) /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + \t\t\(pbxSGMacAppFileRef) /* \(name)App.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = \(name)App.swift; sourceTree = ""; }; + \t\t\(pbxSGMacAppModelRef) /* \(name)AppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = \(name)AppModel.swift; sourceTree = ""; }; + /* End PBXFileReference section */ + + /* Begin PBXFrameworksBuildPhase section */ + \t\t\(pbxFrameworksPhase) /* Frameworks */ = { + \t\t\tisa = PBXFrameworksBuildPhase; + \t\t\tbuildActionMask = \(pbxBuildActionMask); + \t\t\tfiles = ( + \t\t\t\t\(pbxSGMacLyrebirdBuild) /* Lyrebird in Frameworks */, + \t\t\t\t\(pbxLyrebirdUIFrameworkBuild) /* LyrebirdUI in Frameworks */, + \t\t\t\t\(pbxSGMacShoeGazeBuild) /* LyrebirdShoeGaze in Frameworks */, + \t\t\t\t\(pbxSGMacShoeGazeUIBuild) /* LyrebirdShoeGazeUI in Frameworks */, + \t\t\t); + \t\t\trunOnlyForDeploymentPostprocessing = 0; + \t\t}; + /* End PBXFrameworksBuildPhase section */ + + /* Begin PBXGroup section */ + \t\t\(pbxMainGroup) = { + \t\t\tisa = PBXGroup; + \t\t\tchildren = ( + \t\t\t\t\(pbxAppGroup) /* \(name) */, + \t\t\t\t\(pbxProductsGroup) /* Products */, + \t\t\t); + \t\t\tsourceTree = ""; + \t\t}; + \t\t\(pbxProductsGroup) /* Products */ = { + \t\t\tisa = PBXGroup; + \t\t\tchildren = ( + \t\t\t\t\(pbxAppProductRef) /* \(name).app */, + \t\t\t); + \t\t\tname = Products; + \t\t\tsourceTree = ""; + \t\t}; + \t\t\(pbxAppGroup) /* \(name) */ = { + \t\t\tisa = PBXGroup; + \t\t\tchildren = ( + \t\t\t\t\(pbxSGMacAppFileRef) /* \(name)App.swift */, + \t\t\t\t\(pbxSGMacAppModelRef) /* \(name)AppModel.swift */, + \t\t\t\t\(pbxInfoPlistRef) /* Info.plist */, + \t\t\t); + \t\t\tpath = \(name); + \t\t\tsourceTree = ""; + \t\t}; + /* End PBXGroup section */ + + /* Begin PBXNativeTarget section */ + \t\t\(pbxBlueprintIDApp) /* \(name) */ = { + \t\t\tisa = PBXNativeTarget; + \t\t\tbuildConfigurationList = \(pbxAppBuildConfigList) /* Build configuration list for PBXNativeTarget "\(name)" */; + \t\t\tbuildPhases = ( + \t\t\t\t\(pbxSourcesPhase) /* Sources */, + \t\t\t\t\(pbxFrameworksPhase) /* Frameworks */, + \t\t\t\t\(pbxResourcesPhase) /* Resources */, + \t\t\t); + \t\t\tbuildRules = ( + \t\t\t); + \t\t\tdependencies = ( + \t\t\t); + \t\t\tname = \(name); + \t\t\tpackageProductDependencies = ( + \t\t\t\t\(pbxSGMacLyrebirdDep) /* Lyrebird */, + \t\t\t\t\(pbxLyrebirdUIProductDep) /* LyrebirdUI */, + \t\t\t\t\(pbxSGMacShoeGazeDep) /* LyrebirdShoeGaze */, + \t\t\t\t\(pbxSGMacShoeGazeUIDep) /* LyrebirdShoeGazeUI */, + \t\t\t); + \t\t\tproductName = \(name); + \t\t\tproductReference = \(pbxAppProductRef) /* \(name).app */; + \t\t\tproductType = "com.apple.product-type.application"; + \t\t}; + /* End PBXNativeTarget section */ + + /* Begin PBXProject section */ + \t\t\(pbxRootObject) /* Project object */ = { + \t\t\tisa = PBXProject; + \t\t\tattributes = { + \t\t\t\tBuildIndependentTargetsInParallel = 1; + \t\t\t\tLastSwiftUpdateCheck = 1600; + \t\t\t\tLastUpgradeCheck = 1600; + \t\t\t\tTargetAttributes = { + \t\t\t\t\t\(pbxBlueprintIDApp) = { + \t\t\t\t\t\tCreatedOnToolsVersion = 16.0; + \t\t\t\t\t}; + \t\t\t\t}; + \t\t\t}; + \t\t\tbuildConfigurationList = \(pbxProjectBuildConfigList) /* Build configuration list for PBXProject "\(name)" */; + \t\t\tcompatibilityVersion = "Xcode 14.0"; + \t\t\tdevelopmentRegion = en; + \t\t\thasScannedForEncodings = 0; + \t\t\tknownRegions = ( + \t\t\t\ten, + \t\t\t\tBase, + \t\t\t); + \t\t\tmainGroup = \(pbxMainGroup); + \t\t\tpackageReferences = ( + \t\t\t\t\(pbxRemoteSPMRef) /* \(lyrebirdRefLabel) */, + \t\t\t\t\(pbxSGMacShoeGazePackageRef) /* \(shoegazeRefLabel) */, + \t\t\t); + \t\t\tproductRefGroup = \(pbxProductsGroup) /* Products */; + \t\t\tprojectDirPath = ""; + \t\t\tprojectRoot = ""; + \t\t\ttargets = ( + \t\t\t\t\(pbxBlueprintIDApp) /* \(name) */, + \t\t\t); + \t\t}; + /* End PBXProject section */ + + /* Begin PBXResourcesBuildPhase section */ + \t\t\(pbxResourcesPhase) /* Resources */ = { + \t\t\tisa = PBXResourcesBuildPhase; + \t\t\tbuildActionMask = \(pbxBuildActionMask); + \t\t\tfiles = ( + \t\t\t); + \t\t\trunOnlyForDeploymentPostprocessing = 0; + \t\t}; + /* End PBXResourcesBuildPhase section */ + + /* Begin PBXSourcesBuildPhase section */ + \t\t\(pbxSourcesPhase) /* Sources */ = { + \t\t\tisa = PBXSourcesBuildPhase; + \t\t\tbuildActionMask = \(pbxBuildActionMask); + \t\t\tfiles = ( + \t\t\t\t\(pbxSGMacAppFileBuild) /* \(name)App.swift in Sources */, + \t\t\t\t\(pbxSGMacAppModelBuild) /* \(name)AppModel.swift in Sources */, + \t\t\t); + \t\t\trunOnlyForDeploymentPostprocessing = 0; + \t\t}; + /* End PBXSourcesBuildPhase section */ + + /* Begin XCBuildConfiguration section */ + \t\t\(pbxAppDebugConfig) /* Debug */ = { + \t\t\tisa = XCBuildConfiguration; + \t\t\tbuildSettings = { + \t\t\t\tCODE_SIGN_STYLE = Automatic; + \t\t\t\tCOMBINE_HIDPI_IMAGES = YES; + \t\t\t\tDEAD_CODE_STRIPPING = YES; + \t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf; + \t\t\t\tENABLE_HARDENED_RUNTIME = YES; + \t\t\t\tGENERATE_INFOPLIST_FILE = NO; + \t\t\t\tINFOPLIST_FILE = \(name)/Info.plist; + \t\t\t\tLD_RUNPATH_SEARCH_PATHS = ( + \t\t\t\t\t"$(inherited)", + \t\t\t\t\t"@executable_path/../Frameworks", + \t\t\t\t); + \t\t\t\tMACOSX_DEPLOYMENT_TARGET = 15.0; + \t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \(bundleID); + \t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)"; + \t\t\t\tSWIFT_VERSION = 6.0; + \t\t\t}; + \t\t\tname = Debug; + \t\t}; + \t\t\(pbxAppReleaseConfig) /* Release */ = { + \t\t\tisa = XCBuildConfiguration; + \t\t\tbuildSettings = { + \t\t\t\tCODE_SIGN_STYLE = Automatic; + \t\t\t\tCOMBINE_HIDPI_IMAGES = YES; + \t\t\t\tDEAD_CODE_STRIPPING = YES; + \t\t\t\tDEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + \t\t\t\tENABLE_HARDENED_RUNTIME = YES; + \t\t\t\tGENERATE_INFOPLIST_FILE = NO; + \t\t\t\tINFOPLIST_FILE = \(name)/Info.plist; + \t\t\t\tLD_RUNPATH_SEARCH_PATHS = ( + \t\t\t\t\t"$(inherited)", + \t\t\t\t\t"@executable_path/../Frameworks", + \t\t\t\t); + \t\t\t\tMACOSX_DEPLOYMENT_TARGET = 15.0; + \t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \(bundleID); + \t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)"; + \t\t\t\tSWIFT_VERSION = 6.0; + \t\t\t}; + \t\t\tname = Release; + \t\t}; + \t\t\(pbxProjectDebugConfig) /* Debug */ = { + \t\t\tisa = XCBuildConfiguration; + \t\t\tbuildSettings = { + \t\t\t\tALWAYS_SEARCH_USER_PATHS = NO; + \t\t\t\tCLANG_ENABLE_OBJC_ARC = YES; + \t\t\t\tCOPY_PHASE_STRIP = NO; + \t\t\t\tDEAD_CODE_STRIPPING = YES; + \t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf; + \t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES; + \t\t\t\tENABLE_TESTABILITY = YES; + \t\t\t\tENABLE_USER_SCRIPT_SANDBOXING = YES; + \t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu17; + \t\t\t\tGCC_NO_COMMON_BLOCKS = YES; + \t\t\t\tGCC_OPTIMIZATION_LEVEL = 0; + \t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = ( + \t\t\t\t\t"DEBUG=1", + \t\t\t\t\t"$(inherited)", + \t\t\t\t); + \t\t\t\tONLY_ACTIVE_ARCH = YES; + \t\t\t\tSDKROOT = macosx; + \t\t\t\tSWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + \t\t\t\tSWIFT_OPTIMIZATION_LEVEL = "-Onone"; + \t\t\t}; + \t\t\tname = Debug; + \t\t}; + \t\t\(pbxProjectReleaseConfig) /* Release */ = { + \t\t\tisa = XCBuildConfiguration; + \t\t\tbuildSettings = { + \t\t\t\tALWAYS_SEARCH_USER_PATHS = NO; + \t\t\t\tCLANG_ENABLE_OBJC_ARC = YES; + \t\t\t\tCOPY_PHASE_STRIP = NO; + \t\t\t\tDEAD_CODE_STRIPPING = YES; + \t\t\t\tDEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + \t\t\t\tENABLE_NS_ASSERTIONS = NO; + \t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES; + \t\t\t\tENABLE_USER_SCRIPT_SANDBOXING = YES; + \t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu17; + \t\t\t\tGCC_NO_COMMON_BLOCKS = YES; + \t\t\t\tSDKROOT = macosx; + \t\t\t\tSWIFT_COMPILATION_MODE = wholemodule; + \t\t\t\tSWIFT_OPTIMIZATION_LEVEL = "-O"; + \t\t\t}; + \t\t\tname = Release; + \t\t}; + /* End XCBuildConfiguration section */ + + /* Begin XCConfigurationList section */ + \t\t\(pbxAppBuildConfigList) /* Build configuration list for PBXNativeTarget "\(name)" */ = { + \t\t\tisa = XCConfigurationList; + \t\t\tbuildConfigurations = ( + \t\t\t\t\(pbxAppDebugConfig) /* Debug */, + \t\t\t\t\(pbxAppReleaseConfig) /* Release */, + \t\t\t); + \t\t\tdefaultConfigurationIsVisible = 0; + \t\t\tdefaultConfigurationName = Release; + \t\t}; + \t\t\(pbxProjectBuildConfigList) /* Build configuration list for PBXProject "\(name)" */ = { + \t\t\tisa = XCConfigurationList; + \t\t\tbuildConfigurations = ( + \t\t\t\t\(pbxProjectDebugConfig) /* Debug */, + \t\t\t\t\(pbxProjectReleaseConfig) /* Release */, + \t\t\t); + \t\t\tdefaultConfigurationIsVisible = 0; + \t\t\tdefaultConfigurationName = Release; + \t\t}; + /* End XCConfigurationList section */ + + \(lyrebirdRefSection) + + \(shoegazeRefSection) + + /* Begin XCSwiftPackageProductDependency section */ + \t\t\(pbxSGMacLyrebirdDep) /* Lyrebird */ = { + \t\t\tisa = XCSwiftPackageProductDependency; + \t\t\tpackage = \(pbxRemoteSPMRef) /* \(lyrebirdRefLabel) */; + \t\t\tproductName = Lyrebird; + \t\t}; + \t\t\(pbxLyrebirdUIProductDep) /* LyrebirdUI */ = { + \t\t\tisa = XCSwiftPackageProductDependency; + \t\t\tpackage = \(pbxRemoteSPMRef) /* \(lyrebirdRefLabel) */; + \t\t\tproductName = LyrebirdUI; + \t\t}; + \t\t\(pbxSGMacShoeGazeDep) /* LyrebirdShoeGaze */ = { + \t\t\tisa = XCSwiftPackageProductDependency; + \t\t\tpackage = \(pbxSGMacShoeGazePackageRef) /* \(shoegazeRefLabel) */; + \t\t\tproductName = LyrebirdShoeGaze; + \t\t}; + \t\t\(pbxSGMacShoeGazeUIDep) /* LyrebirdShoeGazeUI */ = { + \t\t\tisa = XCSwiftPackageProductDependency; + \t\t\tpackage = \(pbxSGMacShoeGazePackageRef) /* \(shoegazeRefLabel) */; + \t\t\tproductName = LyrebirdShoeGazeUI; + \t\t}; + /* End XCSwiftPackageProductDependency section */ + \t}; + \trootObject = \(pbxRootObject) /* Project object */; + } + """ + } + + // MARK: - ShoeGaze macOS package reference helpers + + /// pbxproj snippet for the ShoeGaze SPM package reference in the macOS template. + /// Uses the macOS-specific `pbxSGMacShoeGazePackageRef` UUID so it doesn't + /// collide with the iOS template's `pbxSGShoeGazePackageRef`. + static func shoegazeMacOSPackageReferenceSection(shoegazePath: String?) -> String { + if let path: String = shoegazePath { + let escaped: String = pbxQuoteEscape(path) + return """ + /* Begin XCLocalSwiftPackageReference section */ + \t\t\(pbxSGMacShoeGazePackageRef) /* XCLocalSwiftPackageReference "shoegaze" */ = { + \t\t\tisa = XCLocalSwiftPackageReference; + \t\t\trelativePath = "\(escaped)"; + \t\t}; + /* End XCLocalSwiftPackageReference section */ + """ + } else { + return """ + /* Begin XCRemoteSwiftPackageReference section */ + \t\t\(pbxSGMacShoeGazePackageRef) /* XCRemoteSwiftPackageReference "shoegaze" */ = { + \t\t\tisa = XCRemoteSwiftPackageReference; + \t\t\trepositoryURL = "\(shoegazePackageURL)"; + \t\t\trequirement = { + \t\t\t\tkind = upToNextMajorVersion; + \t\t\t\tminimumVersion = \(shoegazeMinimumVersion); + \t\t\t}; + \t\t}; + /* End XCRemoteSwiftPackageReference section */ + """ + } + } + + /// Comment label used in pbxproj for the ShoeGaze package reference (macOS variant). + static func shoegazeMacOSPackageReferenceLabel(shoegazePath: String?) -> String { + shoegazePath == nil + ? #"XCRemoteSwiftPackageReference "shoegaze""# + : #"XCLocalSwiftPackageReference "shoegaze""# + } + + // MARK: - shoegaze macOS PBX UUID constants + // + // All UUIDs in the `0x03Cxx` range — no collision with ios-ui (`0x02xx`), + // macos-ui-xcode (`0x01xx`), auv3 (`0x03Axx`), or shoegaze-ios (`0x03Bxx`). + + /// `App.swift` file reference UUID. + static let pbxSGMacAppFileRef: String = "AABB000000000000000003C0" + /// `App.swift` build file UUID. + static let pbxSGMacAppFileBuild: String = "AABB000000000000000003C1" + /// `AppModel.swift` file reference UUID. + static let pbxSGMacAppModelRef: String = "AABB000000000000000003C2" + /// `AppModel.swift` build file UUID. + static let pbxSGMacAppModelBuild: String = "AABB000000000000000003C3" + /// Package reference UUID for the ShoeGaze SPM package (macOS variant). + static let pbxSGMacShoeGazePackageRef: String = "AABB000000000000000003C4" + /// Product dependency UUID for `Lyrebird` (macOS shoegaze needs the core module). + static let pbxSGMacLyrebirdDep: String = "AABB000000000000000003C5" + /// Build file UUID for `Lyrebird` in Frameworks. + static let pbxSGMacLyrebirdBuild: String = "AABB000000000000000003C6" + /// Product dependency UUID for `LyrebirdShoeGaze`. + static let pbxSGMacShoeGazeDep: String = "AABB000000000000000003C7" + /// Build file UUID for `LyrebirdShoeGaze` in Frameworks. + static let pbxSGMacShoeGazeBuild: String = "AABB000000000000000003C8" + /// Product dependency UUID for `LyrebirdShoeGazeUI`. + static let pbxSGMacShoeGazeUIDep: String = "AABB000000000000000003C9" + /// Build file UUID for `LyrebirdShoeGazeUI` in Frameworks. + static let pbxSGMacShoeGazeUIBuild: String = "AABB000000000000000003CA" +} diff --git a/Sources/LyrebirdCLI/ProjectScaffolder+XcodeTemplates.swift b/Sources/LyrebirdCLI/ProjectScaffolder+XcodeTemplates.swift index 44b0bb7..6b028ec 100644 --- a/Sources/LyrebirdCLI/ProjectScaffolder+XcodeTemplates.swift +++ b/Sources/LyrebirdCLI/ProjectScaffolder+XcodeTemplates.swift @@ -17,6 +17,14 @@ extension ProjectScaffolder { /// Lower bound on the Lyrebird version range — `upToNextMajorVersion`. public static let lyrebirdMinimumVersion: String = "1.0.0" + /// SPM URL placeholder for the ShoeGaze package. Substituted into + /// generated `Package.swift` when `--shoegaze-path` is omitted. + /// Replace with the real published URL once ShoeGaze is released. + public static let shoegazePackageURL: String = "https://github.com/realizedsound/LyrebirdShoeGaze" + + /// Lower bound on the ShoeGaze version range — `upToNextMajorVersion`. + public static let shoegazeMinimumVersion: String = "1.0.0" + /// Bundle identifier prefix used in `PRODUCT_BUNDLE_IDENTIFIER`. The /// scaffolded value is `.`. Users typically rewrite this /// to their own reverse-DNS before shipping. diff --git a/Sources/LyrebirdCLI/ProjectScaffolder.swift b/Sources/LyrebirdCLI/ProjectScaffolder.swift index 361273a..211aeaf 100644 --- a/Sources/LyrebirdCLI/ProjectScaffolder.swift +++ b/Sources/LyrebirdCLI/ProjectScaffolder.swift @@ -30,6 +30,20 @@ public enum ProjectTemplate: String, CaseIterable, Equatable { /// AUv3 host `.app` + `aumu` plugin extension wrapping a Lyrebird synth. /// Generates a full `.xcodeproj` with two targets and entitlements files. case auv3 = "auv3" + /// macOS guitar-pedalboard starter app built on `LyrebirdShoeGaze`. + /// Generates a full `.xcodeproj` with a SwiftUI `@main App` entry + /// point, an `@Observable` app model wiring `CoreAudioDriver` + `ShoeGaze`, + /// a root `ShoeGazeView`, and an **Audio ▸ Mute ⌘M** menu command. + /// Requires `--shoegaze-path` (or a published ShoeGaze URL) in addition to + /// the normal `--lyrebird-path`. + case shoegaze = "shoegaze" + /// iOS guitar-pedalboard starter app built on `LyrebirdShoeGaze`. + /// Generates a full `.xcodeproj` with a SwiftUI `@main App` entry + /// point, an `@Observable` app model wiring `iOSAudioDriver` + + /// `AVAudioSession` + `ShoeGaze`, and a root `ShoeGazeView`. + /// Requires `--shoegaze-path` (or a published ShoeGaze URL) in addition to + /// the normal `--lyrebird-path`. + case shoegazeIOS = "shoegaze-ios" /// Case-insensitive init from a raw string. Accepts hyphen-free aliases too. public init?(string: String) { @@ -46,19 +60,24 @@ public enum ProjectTemplate: String, CaseIterable, Equatable { self = .iosUI case "auv3", "au-v3", "au_v3": self = .auv3 + case "shoegaze", "shoe-gaze", "shoe_gaze": + self = .shoegaze + case "shoegaze-ios", "shoegazeios", "shoegaze_ios": + self = .shoegazeIOS default: return nil } } /// True when the template emits a full `.xcodeproj` skeleton in addition - /// to the Swift Package. The simpler four templates (basic/demo/ui-demo/nrt) - /// rely on Xcode's "Open Package.swift" path; these three need a real - /// `.xcodeproj` because they ship an `.app` bundle, app entitlements, or - /// (auv3) an `.appex` extension target — none of which SwiftPM can express. + /// to the Swift Package. The simpler templates (basic/demo/ui-demo/nrt/score) + /// rely on Xcode's "Open Package.swift" path; the Xcode-bearing templates + /// need a real `.xcodeproj` because they ship an `.app` bundle, app + /// entitlements, or (auv3) an `.appex` extension target — none of which + /// SwiftPM can express. public var shipsXcodeProject: Bool { switch self { case .basic, .demo, .uiDemo, .nrt, .score: return false - case .macosUIXcode, .iosUI, .auv3: return true + case .shoegaze, .macosUIXcode, .iosUI, .auv3, .shoegazeIOS: return true } } } @@ -152,12 +171,16 @@ public enum ProjectScaffolder { /// *before* calling this (see `LyrebirdCLI.runNew`), so default /// scaffolds track current `main`; direct library callers get the /// documented `nil` → remote behaviour. + /// - shoegazePath: Absolute path to a local ShoeGaze checkout. Only + /// consumed by the `shoegaze` template. `nil` → emit a remote-URL + /// placeholder in the generated `Package.swift`. /// - Throws: `ProjectScaffolder.Error` on name validation failure or file system errors. public static func scaffold( name: String, template: ProjectTemplate = .basic, in parentDirectory: String = FileManager.default.currentDirectoryPath, - lyrebirdPath: String? = nil + lyrebirdPath: String? = nil, + shoegazePath: String? = nil ) throws { try validateName(name) @@ -182,12 +205,14 @@ public enum ProjectScaffolder { template: template, projectRoot: projectRoot, lyrebirdPath: lyrebirdPath, + shoegazePath: shoegazePath, fm: fm) } else { try scaffoldSwiftPackage(name: name, template: template, projectRoot: projectRoot, lyrebirdPath: lyrebirdPath, + shoegazePath: shoegazePath, fm: fm) } } @@ -199,6 +224,7 @@ public enum ProjectScaffolder { template: ProjectTemplate, projectRoot: String, lyrebirdPath: String?, + shoegazePath: String? = nil, fm: FileManager ) throws { let sourcesDir: String = (projectRoot as NSString) @@ -223,7 +249,12 @@ public enum ProjectScaffolder { var files: [(path: String, content: String)] = [ ( (projectRoot as NSString).appendingPathComponent("Package.swift"), - packageManifest(name: name, template: template, lyrebirdPath: lyrebirdPath) + packageManifest( + name: name, + template: template, + lyrebirdPath: lyrebirdPath, + shoegazePath: shoegazePath + ) ), ( (sourcesDir as NSString).appendingPathComponent("main.swift"), @@ -263,6 +294,7 @@ public enum ProjectScaffolder { template: ProjectTemplate, projectRoot: String, lyrebirdPath: String?, + shoegazePath: String? = nil, fm: FileManager ) throws { // Every xcode-bearing template ships an `.xcworkspace` that @@ -289,6 +321,10 @@ public enum ProjectScaffolder { fm: fm, projectRoot: projectRoot) switch template { + case .shoegaze: + try writeShoeGazeMacOSFiles(name: name, projectRoot: projectRoot, + lyrebirdPath: lyrebirdPath, + shoegazePath: shoegazePath, fm: fm) case .macosUIXcode: try writeMacOSUIXcodeFiles(name: name, projectRoot: projectRoot, lyrebirdPath: lyrebirdPath, fm: fm) @@ -298,6 +334,10 @@ public enum ProjectScaffolder { case .auv3: try writeAUv3Files(name: name, projectRoot: projectRoot, lyrebirdPath: lyrebirdPath, fm: fm) + case .shoegazeIOS: + try writeShoeGazeIOSFiles(name: name, projectRoot: projectRoot, + lyrebirdPath: lyrebirdPath, + shoegazePath: shoegazePath, fm: fm) case .basic, .demo, .uiDemo, .nrt, .score: // Unreachable — shipsXcodeProject filters these out at dispatch. try? fm.removeItem(atPath: projectRoot) @@ -359,10 +399,14 @@ public enum ProjectScaffolder { /// nil, falls back to the published Git URL (``lyrebirdPackageURL``). /// Used by `lyrebird new --lyrebird-path` for users who don't yet /// have access to the public repository. + /// - shoegazePath: When non-nil and template is `.shoegaze`, the + /// ShoeGaze package is declared as a local SPM dependency at this + /// absolute path. When nil, a remote-URL placeholder is emitted. public static func packageManifest( name: String, template: ProjectTemplate = .basic, - lyrebirdPath: String? = nil + lyrebirdPath: String? = nil, + shoegazePath: String? = nil ) -> String { // byName resolves only when the product name matches the package // name (`Lyrebird`). Sibling products (`LyrebirdUI`) need the @@ -374,12 +418,12 @@ public enum ProjectScaffolder { targetDeps = #""Lyrebird""# case .uiDemo: targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"# - case .macosUIXcode, .iosUI, .auv3: + case .shoegaze, .macosUIXcode, .iosUI, .auv3, .shoegazeIOS: // Xcode-bearing templates don't emit a `Package.swift` — dispatch // never reaches this function for them. Defensive fallthrough. targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"# } - let depLine: String + let lyrebirdDepLine: String if let path: String = lyrebirdPath { // `name:` is required so byName target deps (e.g. `"Lyrebird"`) // resolve — SPM otherwise uses the directory basename as the @@ -388,10 +432,13 @@ public enum ProjectScaffolder { // Path escaped for safe embedding in a Swift string literal — // same `\\` then `"` escape semantics as `pbxQuoteEscape`. let escapedPath: String = pbxQuoteEscape(path) - depLine = #".package(name: "Lyrebird", path: "\#(escapedPath)"),"# + lyrebirdDepLine = #".package(name: "Lyrebird", path: "\#(escapedPath)"),"# } else { - depLine = #".package(url: "\#(lyrebirdPackageURL)", from: "\#(lyrebirdMinimumVersion)"),"# + lyrebirdDepLine = #".package(url: "\#(lyrebirdPackageURL)", from: "\#(lyrebirdMinimumVersion)"),"# } + + let dependenciesBlock: String = lyrebirdDepLine + return """ // swift-tools-version: 6.0 import PackageDescription @@ -400,7 +447,7 @@ public enum ProjectScaffolder { name: "\(name)", platforms: [.macOS(.v15)], dependencies: [ - \(depLine) + \(dependenciesBlock) ], targets: [ .executableTarget( @@ -424,12 +471,12 @@ public enum ProjectScaffolder { template: ProjectTemplate = .basic ) -> String { switch template { - case .basic: return mainSwiftBasic(name: name) - case .demo: return mainSwiftDemo(name: name) - case .uiDemo: return mainSwiftUIDemo(name: name) - case .nrt: return mainSwiftNRT(name: name) - case .score: return mainSwiftScore(name: name) - case .macosUIXcode, .iosUI, .auv3: + case .basic: return mainSwiftBasic(name: name) + case .demo: return mainSwiftDemo(name: name) + case .uiDemo: return mainSwiftUIDemo(name: name) + case .nrt: return mainSwiftNRT(name: name) + case .score: return mainSwiftScore(name: name) + case .shoegaze, .macosUIXcode, .iosUI, .auv3, .shoegazeIOS: // Xcode-bearing templates don't emit a `main.swift` under // `Sources//`. Dispatch never reaches this function for // them. Defensive fallthrough to the basic skeleton. @@ -759,6 +806,98 @@ public enum ProjectScaffolder { """ } + // MARK: shoegaze + + private static func mainSwiftShoegaze(name: String) -> String { + """ + // \(name) — ShoeGaze guitar pedalboard + import AppKit + + // Program entry runs on the main thread; assert main-actor isolation for the + // AppKit bootstrap rather than hopping asynchronously. + MainActor.assumeIsolated { + let app: NSApplication = NSApplication.shared + let delegate: AppDelegate = AppDelegate() + app.setActivationPolicy(.regular) + app.delegate = delegate + app.activate(ignoringOtherApps: true) + app.run() + } + """ + } + + /// `AppDelegate.swift` content for a shoegaze project. + public static func shoegazeAppDelegateSwift(name: String) -> String { + let blockSize: Int = scaffoldDefaultBlockSize + let sampleRate: Double = 48_000.0 + let outputChannels: Int = scaffoldDefaultOutputChannels + let inputChannels: Int = 0 + let windowWidth: Int = 980 + let windowHeight: Int = 520 + return """ + import AppKit + import LyrebirdSynth + import LyrebirdUI + import LyrebirdShoeGaze + import LyrebirdShoeGazeUI + + /// Application delegate for \(name). + /// + /// Builds a `SynthesisEngine`, a `ShoeGaze` manager, and a default board of + /// four pedals (Overdrive → Delay → Reverb → Modulation) fed by the built-in + /// test loop, then opens a `LyrebirdWindow` hosting `ShoeGazeView`. + @MainActor + final class AppDelegate: NSObject, NSApplicationDelegate { + + private let engine: SynthesisEngine + private let shoeGaze: ShoeGaze + private let window: LyrebirdWindow + + override init() { + let engine: SynthesisEngine = SynthesisEngine( + blockSize: \(blockSize), + sampleRate: \(sampleRate), + numOutputChannels: \(outputChannels), + numInputChannels: \(inputChannels), + driver: CoreAudioDriver() + ) + self.engine = engine + self.shoeGaze = ShoeGaze(engine: engine) + self.window = LyrebirdWindow( + title: "\(name)", + width: \(windowWidth), + height: \(windowHeight) + ) + super.init() + } + + func applicationDidFinishLaunching(_ notification: Notification) { + do { + let board: PedalBoard = try shoeGaze.addBoard() + try board.add(OverdrivePedal()) + try board.add(DelayPedal()) + try board.add(ReverbPedal()) + try board.add(ModulationPedal()) + try shoeGaze.finalizeBoard(board) + } catch { + print("[\(name)] board build failed: \\(error)") + } + window.open { + ShoeGazeView(shoeGaze: shoeGaze) + } + } + + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + true + } + + func applicationWillTerminate(_ notification: Notification) { + engine.stop() + } + } + """ + } + // MARK: - ui-demo additional files /// `AppDelegate.swift` content for a ui-demo project. diff --git a/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdShoeGazePedal.xctemplate/TemplateInfo.plist b/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdShoeGazePedal.xctemplate/TemplateInfo.plist new file mode 100644 index 0000000..7b1f0bd --- /dev/null +++ b/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdShoeGazePedal.xctemplate/TemplateInfo.plist @@ -0,0 +1,44 @@ + + + + + Kind + Xcode.IDEKit.TextSubstitutionFileTemplateKind + Platforms + + com.apple.platform.macosx + com.apple.platform.iphoneos + + Description + A ShoeGaze guitar pedal subclassing Pedal. Override effect(_:) to build the processed mono signal and effectKnobs to publish its knobs; the base class handles wet/dry mix, click-free bypass, and output level. Add it to a PedalBoard with board.add(_:). + Summary + ShoeGaze Pedal (Pedal subclass) + SortOrder + 13 + AllowedTypes + + public.swift-source + + DefaultCompletionName + MyPedal + MainTemplateFile + ___FILEBASENAME___.swift + Options + + + Identifier + productName + Required + + Name + Pedal name: + Description + Name of the Pedal subclass (also used as the file name). + Type + text + Default + MyPedal + + + + diff --git a/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdShoeGazePedal.xctemplate/___FILEBASENAME___.swift b/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdShoeGazePedal.xctemplate/___FILEBASENAME___.swift new file mode 100644 index 0000000..72cd7f6 --- /dev/null +++ b/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdShoeGazePedal.xctemplate/___FILEBASENAME___.swift @@ -0,0 +1,63 @@ +//___FILEHEADER___ + +import LyrebirdSynth +import LyrebirdUI +import LyrebirdShoeGaze + +// MARK: - ___FILEBASENAMEASIDENTIFIER___ + +/// One-line description of the ___FILEBASENAMEASIDENTIFIER___ pedal. +/// +/// Subclasses `Pedal`: reads a mono dry signal from its input bus, processes it +/// in `effect(_:)`, and lets the base class apply the wet/dry `mix`, click-free +/// `bypass`, and output `level`. Publish the effect's knobs via `effectKnobs` +/// so `PedalView` renders a control for each one. +/// +/// ## Usage +/// ```swift +/// let board = try shoeGaze.addBoard() +/// try board.add(___FILEBASENAMEASIDENTIFIER___()) +/// try shoeGaze.finalizeBoard(board) +/// ``` +final class ___FILEBASENAMEASIDENTIFIER___: Pedal { + + // MARK: - Parameters + + /// Effect amount. Range [0, 1]. + @UIParam var amount: Double = 0.5 + + // MARK: - Constants + + /// Knob range for `amount`. + private let amountRange: ClosedRange = 0.0 ... 1.0 + + // MARK: - Init + + init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init(name: "___FILEBASENAMEASIDENTIFIER___", inputBus: inputBus, outputBus: outputBus) + } + + // MARK: - Effect + + /// Build and return the processed **mono** signal. Replace the passthrough below. + /// + /// Fold any stereo generator (reverb, chorus) to mono with `SumChannels` before + /// returning. Do not pre-blend with the dry signal — the base class `mix` does that. + override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + // TODO: wire your DSP here, e.g.: + // return SoftClip.Audio(dry, drive: $amount * 10.0 + 1.0) + dry + } + + // MARK: - UI knobs + + /// Effect-specific knobs shown by `PedalView` before the common Mix / Level knobs. + override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Amount", node: $amount, range: amountRange), + ] + } +} diff --git a/Tests/LyrebirdCLITests/CLICommandTests.swift b/Tests/LyrebirdCLITests/CLICommandTests.swift index 217161c..85d07f8 100644 --- a/Tests/LyrebirdCLITests/CLICommandTests.swift +++ b/Tests/LyrebirdCLITests/CLICommandTests.swift @@ -47,27 +47,27 @@ struct CLICommandTests { // MARK: - new @Test func newSubcommandParsed() { - #expect(CLICommand.parse(["lyrebird", "new", "MySynth"]) == .new(name: "MySynth", template: .basic, lyrebirdPath: nil)) + #expect(CLICommand.parse(["lyrebird", "new", "MySynth"]) == .new(name: "MySynth", template: .basic, lyrebirdPath: nil, shoegazePath: nil)) } @Test func newWithTemplateDemoParsed() { #expect(CLICommand.parse(["lyrebird", "new", "MySynth", "--template", "demo"]) - == .new(name: "MySynth", template: .demo, lyrebirdPath: nil)) + == .new(name: "MySynth", template: .demo, lyrebirdPath: nil, shoegazePath: nil)) } @Test func newWithTemplateUIDemoParsed() { #expect(CLICommand.parse(["lyrebird", "new", "MySynth", "--template", "ui-demo"]) - == .new(name: "MySynth", template: .uiDemo, lyrebirdPath: nil)) + == .new(name: "MySynth", template: .uiDemo, lyrebirdPath: nil, shoegazePath: nil)) } @Test func newWithTemplateNRTParsed() { #expect(CLICommand.parse(["lyrebird", "new", "MySynth", "--template", "nrt"]) - == .new(name: "MySynth", template: .nrt, lyrebirdPath: nil)) + == .new(name: "MySynth", template: .nrt, lyrebirdPath: nil, shoegazePath: nil)) } @Test func newWithUnknownTemplateFallsBackToBasic() { #expect(CLICommand.parse(["lyrebird", "new", "MySynth", "--template", "bogus"]) - == .new(name: "MySynth", template: .basic, lyrebirdPath: nil)) + == .new(name: "MySynth", template: .basic, lyrebirdPath: nil, shoegazePath: nil)) } @Test func newWithoutNameParsesToHelp() { @@ -89,7 +89,8 @@ struct CLICommandTests { "--lyrebird-path", "/Users/josh/Documents/LyrebirdII" ]) == .new(name: "MyPiece", template: .basic, - lyrebirdPath: "/Users/josh/Documents/LyrebirdII")) + lyrebirdPath: "/Users/josh/Documents/LyrebirdII", + shoegazePath: nil)) } @Test func newWithTemplateAndLyrebirdPathParsed() { @@ -99,13 +100,70 @@ struct CLICommandTests { "--lyrebird-path", "/abs/path" ]) == .new(name: "MyApp", template: .macosUIXcode, - lyrebirdPath: "/abs/path")) + lyrebirdPath: "/abs/path", + shoegazePath: nil)) } @Test func newWithoutLyrebirdPathReportsNil() { #expect(CLICommand.parse([ "lyrebird", "new", "MyPiece" - ]) == .new(name: "MyPiece", template: .basic, lyrebirdPath: nil)) + ]) == .new(name: "MyPiece", template: .basic, lyrebirdPath: nil, shoegazePath: nil)) + } + + // MARK: - shoegaze template + + @Test func newWithTemplateShoegaze() { + let cmd: CLICommand = CLICommand.parse(["lyrebird", "new", "MyRig", "--template", "shoegaze"]) + #expect(cmd == .new(name: "MyRig", template: .shoegaze, lyrebirdPath: nil, shoegazePath: nil)) + } + + @Test func newWithShoegazePathParsed() { + let cmd: CLICommand = CLICommand.parse([ + "lyrebird", "new", "MyRig", + "--template", "shoegaze", + "--lyrebird-path", "/abs/Lyrebird", + "--shoegaze-path", "/abs/ShoeGaze", + ]) + #expect(cmd == .new( + name: "MyRig", + template: .shoegaze, + lyrebirdPath: "/abs/Lyrebird", + shoegazePath: "/abs/ShoeGaze" + )) + } + + @Test func newShoegazeWithoutShoegazePathHasNilShoegazePath() { + let cmd: CLICommand = CLICommand.parse([ + "lyrebird", "new", "MyRig", + "--template", "shoegaze", + "--lyrebird-path", "/abs/Lyrebird", + ]) + #expect(cmd == .new( + name: "MyRig", + template: .shoegaze, + lyrebirdPath: "/abs/Lyrebird", + shoegazePath: nil + )) + } + + @Test func shoegazePathValueNotConsumedWhenFlagToken() { + // `--shoegaze-path --lyrebird-path /abs/Lyrebird` — the value slot for + // `--shoegaze-path` is `--lyrebird-path` (starts with "-") → shoegazePath = nil. + // `firstIndex(of: "--lyrebird-path")` finds the first occurrence (index 6) + // whose next token is also "--lyrebird-path" (starts with "-") → lyrebirdPath = nil too. + let args: [String] = [ + "lyrebird", "new", "MyRig", + "--template", "shoegaze", + "--shoegaze-path", "--lyrebird-path", + "--lyrebird-path", "/abs/Lyrebird", + ] + let cmd: CLICommand = CLICommand.parse(args) + #expect(cmd == .new( + name: "MyRig", + template: .shoegaze, + lyrebirdPath: nil, + shoegazePath: nil + )) } // MARK: - run diff --git a/Tests/LyrebirdCLITests/ProjectScaffolderTests.swift b/Tests/LyrebirdCLITests/ProjectScaffolderTests.swift index 0402a09..238e9f4 100644 --- a/Tests/LyrebirdCLITests/ProjectScaffolderTests.swift +++ b/Tests/LyrebirdCLITests/ProjectScaffolderTests.swift @@ -237,6 +237,12 @@ struct ProjectScaffolderTests { #expect(ProjectTemplate(string: "iosui") == .iosUI) #expect(ProjectTemplate(string: "auv3") == .auv3) #expect(ProjectTemplate(string: "AUV3") == .auv3) + #expect(ProjectTemplate(string: "shoegaze") == .shoegaze) + #expect(ProjectTemplate(string: "shoe-gaze") == .shoegaze) + #expect(ProjectTemplate(string: "SHOEGAZE") == .shoegaze) + #expect(ProjectTemplate(string: "shoegaze-ios") == .shoegazeIOS) + #expect(ProjectTemplate(string: "shoegazeios") == .shoegazeIOS) + #expect(ProjectTemplate(string: "SHOEGAZE-IOS") == .shoegazeIOS) } @Test func shipsXcodeProjectClassification() { @@ -245,9 +251,244 @@ struct ProjectScaffolderTests { #expect(ProjectTemplate.uiDemo.shipsXcodeProject == false) #expect(ProjectTemplate.nrt.shipsXcodeProject == false) #expect(ProjectTemplate.score.shipsXcodeProject == false) + // shoegaze is now an Xcode-bearing template (macOS .app bundle). + #expect(ProjectTemplate.shoegaze.shipsXcodeProject == true) #expect(ProjectTemplate.macosUIXcode.shipsXcodeProject == true) #expect(ProjectTemplate.iosUI.shipsXcodeProject == true) #expect(ProjectTemplate.auv3.shipsXcodeProject == true) + #expect(ProjectTemplate.shoegazeIOS.shipsXcodeProject == true) + } + + // MARK: - shoegaze template (macOS Xcode app) + + @Test func shoegazeMacOSScaffoldCreatesAllFiles() throws { + let fm: FileManager = FileManager.default + let tmp: String = fm.temporaryDirectory + .appendingPathComponent("LyrebirdScaffolderTest_\(UUID().uuidString)").path + try fm.createDirectory(atPath: tmp, withIntermediateDirectories: true, attributes: nil) + defer { try? fm.removeItem(atPath: tmp) } + + try ProjectScaffolder.scaffold(name: "MyRig", template: .shoegaze, in: tmp) + + let root: String = (tmp as NSString).appendingPathComponent("MyRig") + let expected: [String] = [ + "MyRig.xcodeproj/project.pbxproj", + "MyRig.xcodeproj/xcshareddata/xcschemes/MyRig.xcscheme", + "MyRig.xcworkspace/contents.xcworkspacedata", + "MyRig/MyRigApp.swift", + "MyRig/MyRigAppModel.swift", + "MyRig/Info.plist", + ] + for rel: String in expected { + let path: String = (root as NSString).appendingPathComponent(rel) + #expect(fm.fileExists(atPath: path), + "missing shoegaze macOS file: \(rel)") + } + } + + @Test func shoegazeMacOSWorkspaceReferencesXcodeproj() throws { + let fm: FileManager = FileManager.default + let tmp: String = fm.temporaryDirectory + .appendingPathComponent("LyrebirdScaffolderTest_\(UUID().uuidString)").path + try fm.createDirectory(atPath: tmp, withIntermediateDirectories: true, attributes: nil) + defer { try? fm.removeItem(atPath: tmp) } + + try ProjectScaffolder.scaffold(name: "MyRig", template: .shoegaze, in: tmp) + + let workspacePath: String = (tmp as NSString) + .appendingPathComponent("MyRig/MyRig.xcworkspace/contents.xcworkspacedata") + let contents: String = try String(contentsOfFile: workspacePath, encoding: .utf8) + #expect(contents.contains("group:MyRig.xcodeproj")) + } + + @Test func shoegazeMacOSAppSwiftContainsShoeGazeView() { + let src: String = ProjectScaffolder.shoegazeMacOSAppSwift(name: "MyRig") + #expect(src.contains("ShoeGazeView")) + #expect(src.contains("import LyrebirdShoeGazeUI")) + #expect(src.contains("@main")) + #expect(src.contains("toggleMute")) + #expect(src.contains(".keyboardShortcut")) + // Must not embed the Lyrebird copyright in emitted user source. + #expect(!src.contains("Joshua Parmenter")) + } + + @Test func shoegazeMacOSAppSwiftSubstitutesName() { + let src: String = ProjectScaffolder.shoegazeMacOSAppSwift(name: "GuitarPedals") + #expect(src.contains("GuitarPedalsApp")) + #expect(src.contains("GuitarPedalsAppModel")) + } + + @Test func shoegazeMacOSAppModelContainsEngineAndBoard() { + let src: String = ProjectScaffolder.shoegazeMacOSAppModelSwift(name: "MyRig") + #expect(src.contains("import LyrebirdShoeGaze")) + #expect(src.contains("CoreAudioDriver")) + #expect(src.contains("ShoeGaze(engine:")) + #expect(src.contains("OverdrivePedal")) + #expect(src.contains("DelayPedal")) + #expect(src.contains("ReverbPedal")) + #expect(src.contains("ModulationPedal")) + #expect(src.contains("@Observable")) + #expect(src.contains("toggleMute")) + // Must not embed the Lyrebird copyright in emitted user source. + #expect(!src.contains("Joshua Parmenter")) + } + + @Test func shoegazeMacOSAppModelSubstitutesName() { + let src: String = ProjectScaffolder.shoegazeMacOSAppModelSwift(name: "GuitarPedals") + #expect(src.contains("GuitarPedalsAppModel")) + #expect(src.contains("GuitarPedals")) + } + + @Test func shoegazeMacOSInfoPlistContainsMicrophoneKey() { + let plist: String = ProjectScaffolder.shoegazeMacOSInfoPlist(name: "MyRig") + #expect(plist.contains("NSMicrophoneUsageDescription")) + #expect(plist.contains("LSMinimumSystemVersion")) + #expect(plist.contains("NSHighResolutionCapable")) + #expect(plist.contains("public.app-category.music")) + #expect(plist.contains("NSPrincipalClass")) + } + + @Test func shoegazeMacOSPBXProjReferencesMacOSXAndShoeGaze() { + let pbx: String = ProjectScaffolder.shoegazeMacOSPBXProj(name: "MyRig") + #expect(pbx.contains("SDKROOT = macosx")) + #expect(pbx.contains("MACOSX_DEPLOYMENT_TARGET = 15.0")) + #expect(pbx.contains("ENABLE_HARDENED_RUNTIME = YES")) + #expect(pbx.contains("LyrebirdShoeGaze")) + #expect(pbx.contains("LyrebirdShoeGazeUI")) + #expect(pbx.contains("LyrebirdUI")) + #expect(pbx.contains("Lyrebird")) + #expect(pbx.contains(ProjectScaffolder.shoegazePackageURL)) + #expect(pbx.contains("MyRig.app")) + } + + @Test func shoegazeMacOSPBXProjUsesLocalRefsWhenPathsSet() { + let pbx: String = ProjectScaffolder.shoegazeMacOSPBXProj( + name: "MyRig", + lyrebirdPath: "/abs/Lyrebird", + shoegazePath: "/abs/ShoeGaze" + ) + #expect(pbx.contains("XCLocalSwiftPackageReference")) + #expect(pbx.contains(#"relativePath = "/abs/ShoeGaze""#)) + #expect(pbx.contains(#"relativePath = "/abs/Lyrebird""#)) + #expect(!pbx.contains("XCRemoteSwiftPackageReference")) + } + + @Test func shoegazeMacOSPBXProjUsesRemoteRefsWhenPathsNil() { + let pbx: String = ProjectScaffolder.shoegazeMacOSPBXProj(name: "MyRig") + #expect(pbx.contains("XCRemoteSwiftPackageReference")) + #expect(pbx.contains(ProjectScaffolder.shoegazePackageURL)) + #expect(pbx.contains(ProjectScaffolder.lyrebirdPackageURL)) + } + + // MARK: - shoegaze-ios template + + @Test func shoegazeIOSScaffoldCreatesAllFiles() throws { + let fm: FileManager = FileManager.default + let tmp: String = fm.temporaryDirectory + .appendingPathComponent("LyrebirdScaffolderTest_\(UUID().uuidString)").path + try fm.createDirectory(atPath: tmp, withIntermediateDirectories: true, attributes: nil) + defer { try? fm.removeItem(atPath: tmp) } + + try ProjectScaffolder.scaffold(name: "MyRig", template: .shoegazeIOS, in: tmp) + + let root: String = (tmp as NSString).appendingPathComponent("MyRig") + let expected: [String] = [ + "MyRig.xcodeproj/project.pbxproj", + "MyRig.xcodeproj/xcshareddata/xcschemes/MyRig.xcscheme", + "MyRig.xcworkspace/contents.xcworkspacedata", + "MyRig/MyRigApp.swift", + "MyRig/MyRigAppModel.swift", + "MyRig/Info.plist", + ] + for rel: String in expected { + let path: String = (root as NSString).appendingPathComponent(rel) + #expect(fm.fileExists(atPath: path), + "missing shoegaze-ios file: \(rel)") + } + } + + @Test func shoegazeIOSAppSwiftContainsShoeGazeView() { + let src: String = ProjectScaffolder.shoegazeIOSAppSwift(name: "MyRig") + #expect(src.contains("ShoeGazeView")) + #expect(src.contains("import LyrebirdShoeGazeUI")) + #expect(src.contains("@main")) + #expect(src.contains("NavigationStack")) + #expect(src.contains("ScrollView")) + // Must not embed the Lyrebird copyright in emitted user source. + #expect(!src.contains("Joshua Parmenter")) + } + + @Test func shoegazeIOSAppSwiftSubstitutesName() { + let src: String = ProjectScaffolder.shoegazeIOSAppSwift(name: "GuitarPedals") + #expect(src.contains("GuitarPedalsApp")) + #expect(src.contains("GuitarPedalsAppModel")) + } + + @Test func shoegazeIOSAppModelContainsEngineAndBoard() { + let src: String = ProjectScaffolder.shoegazeIOSAppModelSwift(name: "MyRig") + #expect(src.contains("import LyrebirdShoeGaze")) + #expect(src.contains("iOSAudioDriver")) + #expect(src.contains("AVAudioSession")) + #expect(src.contains("ShoeGaze(engine:")) + #expect(src.contains("OverdrivePedal")) + #expect(src.contains("DelayPedal")) + #expect(src.contains("ReverbPedal")) + #expect(src.contains("ModulationPedal")) + #expect(src.contains("@Observable")) + // Must not embed the Lyrebird copyright in emitted user source. + #expect(!src.contains("Joshua Parmenter")) + } + + @Test func shoegazeIOSAppModelSubstitutesName() { + let src: String = ProjectScaffolder.shoegazeIOSAppModelSwift(name: "GuitarPedals") + #expect(src.contains("GuitarPedalsAppModel")) + #expect(src.contains("GuitarPedals")) + } + + @Test func shoegazeIOSPBXProjReferencesIPhoneOSAndShoeGaze() { + let pbx: String = ProjectScaffolder.shoegazeIOSPBXProj(name: "MyRig") + #expect(pbx.contains("SDKROOT = iphoneos")) + #expect(pbx.contains("IPHONEOS_DEPLOYMENT_TARGET = 18.0")) + #expect(pbx.contains("TARGETED_DEVICE_FAMILY")) + #expect(pbx.contains("LyrebirdShoeGaze")) + #expect(pbx.contains("LyrebirdShoeGazeUI")) + #expect(pbx.contains("LyrebirdUI")) + #expect(pbx.contains(ProjectScaffolder.shoegazePackageURL)) + #expect(pbx.contains("MyRig.app")) + } + + @Test func shoegazeIOSPBXProjUsesLocalShoegazeRefWhenPathSet() { + let pbx: String = ProjectScaffolder.shoegazeIOSPBXProj( + name: "MyRig", + lyrebirdPath: "/abs/Lyrebird", + shoegazePath: "/abs/ShoeGaze" + ) + #expect(pbx.contains("XCLocalSwiftPackageReference")) + #expect(pbx.contains(#"relativePath = "/abs/ShoeGaze""#)) + #expect(pbx.contains(#"relativePath = "/abs/Lyrebird""#)) + #expect(!pbx.contains("XCRemoteSwiftPackageReference")) + } + + @Test func shoegazeIOSPBXProjUsesRemoteRefWhenPathsNil() { + let pbx: String = ProjectScaffolder.shoegazeIOSPBXProj(name: "MyRig") + #expect(pbx.contains("XCRemoteSwiftPackageReference")) + #expect(pbx.contains(ProjectScaffolder.shoegazePackageURL)) + #expect(pbx.contains(ProjectScaffolder.lyrebirdPackageURL)) + } + + @Test func shoegazeIOSWorkspaceReferencesXcodeproj() throws { + let fm: FileManager = FileManager.default + let tmp: String = fm.temporaryDirectory + .appendingPathComponent("LyrebirdScaffolderTest_\(UUID().uuidString)").path + try fm.createDirectory(atPath: tmp, withIntermediateDirectories: true, attributes: nil) + defer { try? fm.removeItem(atPath: tmp) } + + try ProjectScaffolder.scaffold(name: "MyRig", template: .shoegazeIOS, in: tmp) + + let workspacePath: String = (tmp as NSString) + .appendingPathComponent("MyRig/MyRig.xcworkspace/contents.xcworkspacedata") + let contents: String = try String(contentsOfFile: workspacePath, encoding: .utf8) + #expect(contents.contains("group:MyRig.xcodeproj")) } // MARK: - Xcode-bearing templates: structure diff --git a/Tests/LyrebirdCLITests/TemplateInstallerTests.swift b/Tests/LyrebirdCLITests/TemplateInstallerTests.swift index df0ae60..6cb2f13 100644 --- a/Tests/LyrebirdCLITests/TemplateInstallerTests.swift +++ b/Tests/LyrebirdCLITests/TemplateInstallerTests.swift @@ -37,6 +37,13 @@ struct TemplateInstallerTests { #expect(names.contains("LyrebirdGenerator.xctemplate")) } + @Test func availableTemplatesIncludesShoeGazePedal() throws { + let names: [String] = try TemplateInstaller.availableTemplates() + // The ShoeGaze Pedal template scaffolds a `Pedal` subclass for the + // guitar-pedalboard sample project. + #expect(names.contains("LyrebirdShoeGazePedal.xctemplate")) + } + // MARK: - Destination URL @Test func destinationURLIsInHomeLibrary() { diff --git a/Tests/LyrebirdCLITests/WorkflowIntegrationTests.swift b/Tests/LyrebirdCLITests/WorkflowIntegrationTests.swift index 16d7938..39d4ac1 100644 --- a/Tests/LyrebirdCLITests/WorkflowIntegrationTests.swift +++ b/Tests/LyrebirdCLITests/WorkflowIntegrationTests.swift @@ -185,4 +185,28 @@ struct WorkflowIntegrationTests { #expect(try parseCheck(source: source, fileName: "main.swift"), "nrt template main.swift must pass swiftc -parse") } + + @Test func shoegazeIOSAppSwiftIsValidSwiftSyntax() throws { + let source: String = ProjectScaffolder.shoegazeIOSAppSwift(name: "MyRig") + #expect(try parseCheck(source: source, fileName: "MyRigApp.swift"), + "shoegaze-ios App.swift must pass swiftc -parse") + } + + @Test func shoegazeIOSAppModelSwiftIsValidSwiftSyntax() throws { + let source: String = ProjectScaffolder.shoegazeIOSAppModelSwift(name: "MyRig") + #expect(try parseCheck(source: source, fileName: "MyRigAppModel.swift"), + "shoegaze-ios AppModel.swift must pass swiftc -parse") + } + + @Test func shoegazeMacOSAppSwiftIsValidSwiftSyntax() throws { + let source: String = ProjectScaffolder.shoegazeMacOSAppSwift(name: "MyRig") + #expect(try parseCheck(source: source, fileName: "MyRigApp.swift"), + "shoegaze macOS App.swift must pass swiftc -parse") + } + + @Test func shoegazeMacOSAppModelSwiftIsValidSwiftSyntax() throws { + let source: String = ProjectScaffolder.shoegazeMacOSAppModelSwift(name: "MyRig") + #expect(try parseCheck(source: source, fileName: "MyRigAppModel.swift"), + "shoegaze macOS AppModel.swift must pass swiftc -parse") + } } diff --git a/Tests/LyrebirdTests/Generators/Analysis/BeatTrackFeatureTests.swift b/Tests/LyrebirdTests/Generators/Analysis/BeatTrackFeatureTests.swift new file mode 100644 index 0000000..b821311 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Analysis/BeatTrackFeatureTests.swift @@ -0,0 +1,111 @@ +// BeatTrackFeatureTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +@MainActor +@Suite("BeatTrack.Control — feature-fed (feature)") +struct BeatTrackFeatureTests { + + let engine: SynthesisEngine + var graph: SynthGraph { makeSynthGraph(engine: engine) } + let blockSize: Int = 512 + let sampleRate: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 512, sampleRate: 44100) + try engine.start() + } + + @Test func rateIsControl() { + let gen: BeatTrack.Control = BeatTrack.Control(feature: 0.0) + #expect(gen.rate == .control) + } + + @Test func fourOutputRows() { + let gen: BeatTrack.Control = BeatTrack.Control(feature: 0.0) + #expect(gen.outputChannelCount == 4) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(out.count == 4) + for row: Int in 0..<4 { + #expect(Array(out[row].prefix(blockSize)).count == blockSize) + } + } + + /// Each output row is flat across the block (block-quantised triggers / tempo). + @Test func rowsAreFlat() { + let gen: BeatTrack.Control = BeatTrack.Control(feature: 0.5) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + for row: Int in 0..<4 { + let first: Double = out[row][0] + for i: Int in 0.. SynthesisEngine { + let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100) + try engine.start() + return engine + } + + @Test func rateIsControl() throws { + let engine: SynthesisEngine = try makeEngine() + defer { engine.stop() } + let chain: SpectralChain.Audio = SpectralChain.Audio( + input: Double(0.0), fftSize: fftSize, hopSize: hopSize, analyzeOnly: true) + let gen: BeatTrack.Control = BeatTrack.Control(analysis: chain) + #expect(gen.rate == .control) + #expect(gen.outputChannelCount == 4) + } + + /// The `odf:` enum init and the `analysis:` convenience init are equivalent. + @Test func enumInitMatchesConvenience() throws { + let engine: SynthesisEngine = try makeEngine() + defer { engine.stop() } + let chain: SpectralChain.Audio = SpectralChain.Audio( + input: Double(0.0), fftSize: fftSize, hopSize: hopSize, analyzeOnly: true) + let gen: BeatTrack.Control = BeatTrack.Control(odf: .spectralFlux(analysis: chain)) + #expect(gen.rate == .control) + #expect(gen.outputChannelCount == 4) + } + + /// FFT-fed path: a 2 Hz click track (120 BPM) drives spectral flux that locks + /// the tempo near 120. Looser tolerance than the feature-fed path due to FFT + /// time-smearing of the onset. + @Test func locksToClickTrack() throws { + let engine: SynthesisEngine = try makeEngine() + defer { engine.stop() } + + // Broadband clicks at 2 Hz → spectral flux spikes at the beat rate. + let clicks: Impulse.Audio = Impulse.Audio(freq: 2.0) + let chain: SpectralChain.Audio = SpectralChain.Audio( + input: clicks, fftSize: fftSize, hopSize: hopSize, analyzeOnly: true) + let gen: BeatTrack.Control = BeatTrack.Control(analysis: chain) + + var lastTempo: Double = 0.0 + for _ in 0..<900 { + let g: SynthGraph = makeSynthGraph(engine: engine) + let out: [[Double]] = gen.calculatedSamples(graph: g, count: blockSize) + lastTempo = out[3][0] + advanceBlock(engine) + } + #expect(abs(lastTempo - 120.0) < 120.0 * 0.15, + "expected ≈120 BPM from click track, got \(lastTempo)") + } + + /// Silent input: no NaN/Inf, tempo finite (holds the default). + @Test func silenceProducesNoNaN() throws { + let engine: SynthesisEngine = try makeEngine() + defer { engine.stop() } + let chain: SpectralChain.Audio = SpectralChain.Audio( + input: Double(0.0), fftSize: fftSize, hopSize: hopSize, analyzeOnly: true) + let gen: BeatTrack.Control = BeatTrack.Control(analysis: chain) + for _ in 0..<200 { + let g: SynthGraph = makeSynthGraph(engine: engine) + let out: [[Double]] = gen.calculatedSamples(graph: g, count: blockSize) + for row: Int in 0..<4 { + for i: Int in 0.. BeatTrackerCore { + BeatTrackerCore( + minBPM: minBPM, + maxBPM: maxBPM, + preferredBPM: preferredBPM, + windowSeconds: beatTrackMaxWindowSeconds, + featureRateHz: beatTrackFeatureRateHz + ) + } + + /// Feed `features` features (one per block), firing an impulse ODF every + /// `periodFeatures`-th feature. Returns counts of each trigger. + @discardableResult + private func driveImpulseTrain( + _ core: BeatTrackerCore, + periodFeatures: Int, + features: Int + ) -> (beats: Int, eighths: Int, sixteenths: Int) { + var beats: Int = 0 + var eighths: Int = 0 + var sixteenths: Int = 0 + for f: Int in 0.. slow.tempoBPM + 30.0, + "fast \(fast.tempoBPM) should clearly exceed slow \(slow.tempoBPM)") + } + + // MARK: - Beat spacing / subdivisions + + @Test func beatCountMatchesPeriod() { + let core: BeatTrackerCore = makeCore() + let period: Int = 43 // ≈120 BPM + let features: Int = 860 // ~20 beats + let counts: (beats: Int, eighths: Int, sixteenths: Int) = + driveImpulseTrain(core, periodFeatures: period, features: features) + let expectedBeats: Double = Double(features) / Double(period) + #expect(abs(Double(counts.beats) - expectedBeats) <= 2.0, + "expected ≈\(expectedBeats) beats, got \(counts.beats)") + } + + @Test func subdivisionsFireFasterThanBeat() { + let core: BeatTrackerCore = makeCore() + let counts: (beats: Int, eighths: Int, sixteenths: Int) = + driveImpulseTrain(core, periodFeatures: 43, features: 860) + // Eighth ≈ 2×, sixteenth ≈ 4× the beat rate. + #expect(abs(Double(counts.eighths) - 2.0 * Double(counts.beats)) <= 3.0, + "eighths \(counts.eighths) ≉ 2× beats \(counts.beats)") + #expect(abs(Double(counts.sixteenths) - 4.0 * Double(counts.beats)) <= 5.0, + "sixteenths \(counts.sixteenths) ≉ 4× beats \(counts.beats)") + } + + // MARK: - Edge cases + + /// Silence: tempo holds the pre-lock default, stays finite, and the phase + /// free-runs (beats still fire). + @Test func silenceHoldsTempoAndFreeRuns() { + let core: BeatTrackerCore = makeCore() + var beats: Int = 0 + for _ in 0..<800 { + core.processBlock(odf: 0.0, sampleCount: featureHop, sampleRate: sampleRate) + if core.beatTriggered { beats += 1 } + } + #expect(core.tempoBPM.isFinite) + #expect(abs(core.tempoBPM - beatTrackPreferredBPM) < 1e-9, + "silence should hold the preferred tempo, got \(core.tempoBPM)") + #expect(beats > 0, "phase should free-run at the default tempo") + } + + /// Constant (DC) ODF: whitening removes the offset, so no NaN/Inf and tempo + /// stays finite and sane (no degenerate lock). + @Test func dcInputStaysFinite() { + let core: BeatTrackerCore = makeCore() + for _ in 0..<800 { + core.processBlock(odf: 0.5, sampleCount: featureHop, sampleRate: sampleRate) + } + #expect(core.tempoBPM.isFinite) + #expect(core.tempoBPM >= beatTrackMinBPM && core.tempoBPM <= beatTrackMaxBPM, + "tempo \(core.tempoBPM) out of bounds for DC input") + } + + /// Blocks longer than one feature hop still advance the tracker (multiple + /// features per block) and lock tempo. Each big block spans 4 feature hops; + /// an onset every 11 big blocks → 44 features ≈ 117 BPM. + @Test func longBlockEmitsMultipleFeaturesAndLocks() { + let core: BeatTrackerCore = makeCore() + let bigBlock: Int = featureHop * 4 + let periodBlocks: Int = 11 + for b: Int in 0..<260 { + let odf: Double = (b % periodBlocks == 0) ? 1.0 : 0.0 + core.processBlock(odf: odf, sampleCount: bigBlock, sampleRate: sampleRate) + } + let expected: Double = 60.0 * beatTrackFeatureRateHz / Double(periodBlocks * 4) + #expect(core.tempoBPM.isFinite) + #expect(abs(core.tempoBPM - expected) < expected * 0.08, + "expected ≈\(expected) BPM, got \(core.tempoBPM)") + } +} diff --git a/Tests/LyrebirdTests/Generators/Analysis/LoudnessControlTests.swift b/Tests/LyrebirdTests/Generators/Analysis/LoudnessControlTests.swift new file mode 100644 index 0000000..c30357c --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Analysis/LoudnessControlTests.swift @@ -0,0 +1,179 @@ +// LoudnessControlTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +@MainActor +@Suite("Loudness.Control") +struct LoudnessControlTests { + + let engine: SynthesisEngine + var graph: SynthGraph { makeSynthGraph(engine: engine) } + let blockSize: Int = 512 + let sampleRate: Double = 44100 + let fftSize: Int = 2048 + + init() throws { + engine = makeTestEngine(blockSize: 512, sampleRate: 44100) + try engine.start() + } + + /// A spectral buffer holding a single tone (one bin) at `freqHz` with the + /// given magnitude; every other bin is zero. + private func toneBuffer(freqHz: Double, magnitude: Float) -> SpectralBuffer { + let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize) + let binHz: Double = sampleRate / Double(fftSize) + let bin: Int = Int((freqHz / binHz).rounded()) + buf.setMagnitude(magnitude, at: bin) + return buf + } + + /// dB offset so a unit-magnitude tone bin reads `targetDB` SPL. + /// `bandLevel = 20·log10(mag) + calibrationDB`; with `mag = 1` → `calibrationDB`. + private func calibrationFor(targetDB: Double, magnitude: Float) -> Double { + targetDB - 20.0 * Foundation.log10(Double(magnitude)) + } + + private func readLoudness(_ gen: Loudness.Control) -> Double { + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + return out[0][blockSize - 1] + } + + private let models: [LoudnessModel] = [ + .barkEstimate, + .realtimeZwicker(smask: loudnessDefaultSMask, tmask: loudnessDefaultTMask), + .iso532b(field: .free) + ] + + // MARK: - Shape + + @Test func rateIsControlSingleRow() { + let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize) + let gen: Loudness.Control = Loudness.Control(spectral: buf, sampleRate: sampleRate) + #expect(gen.rate == .control) + #expect(gen.outputChannelCount == 1) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(out.count == 1) + #expect(Array(out[0].prefix(blockSize)).count == blockSize) + } + + // MARK: - Silence + + @Test func silenceIsZeroAndFinite() { + for model: LoudnessModel in models { + let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize) + let gen: Loudness.Control = Loudness.Control( + model: model, spectral: buf, sampleRate: sampleRate) + let n: Double = readLoudness(gen) + #expect(n.isFinite, "silence not finite for \(model)") + #expect(n < 0.05, "silence should be ~0 sones, got \(n) for \(model)") + } + } + + // MARK: - Monotonic + + @Test func louderToneGivesMoreSones() { + for model: LoudnessModel in models { + let quiet: Loudness.Control = Loudness.Control( + model: model, spectral: toneBuffer(freqHz: 1000, magnitude: 1.0), + sampleRate: sampleRate, calibrationDB: 70) + let loud: Loudness.Control = Loudness.Control( + model: model, spectral: toneBuffer(freqHz: 1000, magnitude: 10.0), + sampleRate: sampleRate, calibrationDB: 70) + let nQuiet: Double = readLoudness(quiet) + let nLoud: Double = readLoudness(loud) + #expect(nLoud > nQuiet, + "louder tone should be louder for \(model): \(nLoud) vs \(nQuiet)") + } + } + + // MARK: - Stevens doubling (barkEstimate is exact power-law) + + @Test func tenDBRoughlyDoublesBarkEstimate() { + // +10 dB = magnitude × sqrt(10). + let m0: Float = 1.0 + let m1: Float = Float(Foundation.pow(10.0, 0.5)) + let lo: Loudness.Control = Loudness.Control( + model: .barkEstimate, spectral: toneBuffer(freqHz: 1000, magnitude: m0), + sampleRate: sampleRate, calibrationDB: 60) + let hi: Loudness.Control = Loudness.Control( + model: .barkEstimate, spectral: toneBuffer(freqHz: 1000, magnitude: m1), + sampleRate: sampleRate, calibrationDB: 60) + let ratio: Double = readLoudness(hi) / max(1e-9, readLoudness(lo)) + #expect(abs(ratio - 2.0) < 0.2, "expected ≈2× per +10 dB, got \(ratio)") + } + + // MARK: - Calibration anchor: 1 kHz @ 40 dB ≈ 1 sone + + @Test func anchorBarkEstimate() { + let cal: Double = calibrationFor(targetDB: 40, magnitude: 1.0) + let gen: Loudness.Control = Loudness.Control( + model: .barkEstimate, spectral: toneBuffer(freqHz: 1000, magnitude: 1.0), + sampleRate: sampleRate, calibrationDB: cal) + let n: Double = readLoudness(gen) + #expect(abs(n - 1.0) < 0.3, "barkEstimate 1 kHz@40 dB expected ≈1 sone, got \(n)") + } + + @Test func anchorISO532B() { + let cal: Double = calibrationFor(targetDB: 40, magnitude: 1.0) + let gen: Loudness.Control = Loudness.Control( + model: .iso532b(field: .free), spectral: toneBuffer(freqHz: 1000, magnitude: 1.0), + sampleRate: sampleRate, calibrationDB: cal) + let n: Double = readLoudness(gen) + #expect(n > 0.5 && n < 1.7, "iso532b 1 kHz@40 dB expected ≈1 sone, got \(n)") + } + + @Test func anchorRealtimeZwicker() { + let cal: Double = calibrationFor(targetDB: 40, magnitude: 1.0) + let gen: Loudness.Control = Loudness.Control( + model: .realtimeZwicker(smask: loudnessDefaultSMask, tmask: loudnessDefaultTMask), + spectral: toneBuffer(freqHz: 1000, magnitude: 1.0), + sampleRate: sampleRate, calibrationDB: cal) + let n: Double = readLoudness(gen) + #expect(n > 0.5 && n < 2.0, "realtimeZwicker 1 kHz@40 dB expected ≈1 sone, got \(n)") + } + + // MARK: - Field + + @Test func diffuseDiffersFromFreeForHighTone() { + // 5 kHz: DDF correction is large (+4 dB), so diffuse ≠ free. + let cal: Double = calibrationFor(targetDB: 60, magnitude: 1.0) + let free: Loudness.Control = Loudness.Control( + model: .iso532b(field: .free), spectral: toneBuffer(freqHz: 5000, magnitude: 1.0), + sampleRate: sampleRate, calibrationDB: cal) + let diffuse: Loudness.Control = Loudness.Control( + model: .iso532b(field: .diffuse), spectral: toneBuffer(freqHz: 5000, magnitude: 1.0), + sampleRate: sampleRate, calibrationDB: cal) + #expect(abs(readLoudness(free) - readLoudness(diffuse)) > 0.05, + "free vs diffuse should differ for a 5 kHz tone") + } + + // MARK: - Live chain integration + + @Test func runsOverLiveChainFinite() throws { + let osc: OscSin.Audio = OscSin.Audio(freq: 1000.0, mul: 0.5) + let chain: SpectralChain.Audio = SpectralChain.Audio( + input: osc, fftSize: fftSize, hopSize: 512, analyzeOnly: true) + let gen: Loudness.Control = Loudness.Control( + model: .iso532b(field: .free), analysis: chain, sampleRate: sampleRate) + for _ in 0..<60 { + let g: SynthGraph = makeSynthGraph(engine: engine) + let out: [[Double]] = gen.calculatedSamples(graph: g, count: blockSize) + for i: Int in 0.. 0.0, "a 1 kHz tone through the chain should read > 0 sones") + } + + @Test func floatValueReturnsLatest() { + let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize) + let gen: Loudness.Control = Loudness.Control(spectral: buf, sampleRate: sampleRate) + _ = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(gen.floatValue(graph: graph) == gen.previousOutputValue) + } +} diff --git a/Tests/LyrebirdTests/Generators/Analysis/RunningMaxAudioTests.swift b/Tests/LyrebirdTests/Generators/Analysis/RunningMaxAudioTests.swift new file mode 100644 index 0000000..89fc08b --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Analysis/RunningMaxAudioTests.swift @@ -0,0 +1,144 @@ +// RunningMaxAudioTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +@MainActor +@Suite("RunningMax.Audio") +struct RunningMaxAudioTests { + + let engine: SynthesisEngine + var graph: SynthGraph { makeSynthGraph(engine: engine) } + let blockSize: Int = 64 + let sampleRate: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func rateIsAudio() { + let gen: RunningMax.Audio = RunningMax.Audio(input: 0.0) + #expect(gen.rate == .audio) + } + + /// Output count matches request. + @Test func outputCountMatchesRequest() { + let gen: RunningMax.Audio = RunningMax.Audio(input: 0.5) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(Array(out[0].prefix(blockSize)).count == blockSize) + } + + /// First sample initializes extreme to the first input value. + @Test func firstSampleInitializesToFirstInput() { + let inputVal: Double = 0.3 + let gen: RunningMax.Audio = RunningMax.Audio(input: inputVal) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(abs(out[0][0] - inputVal) < 1e-12, + "first sample should equal first input \(inputVal), got \(out[0][0])") + } + + /// Tracks increasing extreme over a varying input. + /// + /// Input starts at 0.0 and increases by 0.01 per sample. + /// The running maximum should track every new maximum. + @Test func tracksIncreasingExtreme() { + let inputSignal: Closure = Closure { _, i in Double(i) * 0.01 } + let gen: RunningMax.Audio = RunningMax.Audio(input: inputSignal) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0.. 0.3). + let firstSerial: UInt64 = engine.segmentSerial + let inputSignal: Closure = Closure { graph, _ in + graph.engine.segmentSerial == firstSerial ? 0.3 : 0.5 + } + let gen: RunningMin.Audio = RunningMin.Audio(input: inputSignal) + _ = gen.calculatedSamples(graph: graph, count: blockSize) + advanceBlock(engine) + let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + // The minimum from block 1 (0.3) should persist in block 2 since input is 0.5. + for i: Int in 0.. 0.2)") + } + + /// mul/add: output is original*2+1. + @Test func mulAdd() { + let inputSignal: Closure = Closure { _, i in 1.0 - Double(i) * 0.01 } + let genBase: RunningMin.Control = RunningMin.Control(input: inputSignal) + let genScaled: RunningMin.Control = RunningMin.Control( + input: inputSignal, + mul: 2.0, + add: 1.0 + ) + let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize) + let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0..= 1. + /// + /// x[n] = n*k, x[n-1] = (n-1)*k → slope = (n*k - (n-1)*k)*sr = k*sr. + @Test func linearRampProducesConstantSlope() { + let k: Double = 0.001 // increment per sample + let expectedSlope: Double = k * sampleRate + let inputSignal: Closure = Closure { _, i in Double(i) * k } + let gen: Slope.Audio = Slope.Audio(input: inputSignal) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + // Sample 0: lazy-init (output 0). + #expect(abs(out[0][0] - 0.0) < 1e-12) + // Samples 1..blockSize-1: slope = k * sampleRate. + for i: Int in 1.. 0` is never satisfied. SuperCollider `ZeroCrossing` + /// exhibits identical behaviour (`m_previn = ZIN0(0)`). + @Test func constantPositiveDCInputYieldsZeroFreq() { + let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: 1.0) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0..0 is false). Freq stays 0. + @Test func constantNegativeInputNoZeroCrossing() { + let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: -1.0) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0..0) fires every P + /// samples from the second crossing onward. `_prevSample` is lazy-initialised to the + /// first input sample (-1), so no spurious crossing fires on sample 0. The first + /// crossing at sample 8 has a count of 9 (incremented for samples 0..8); the second + /// and subsequent crossings measure exactly P = 16. + @Test func squareWaveKnownPeriodYieldsExpectedFreq() { + // Period = 16 samples. Signal: -1 for samples 0..7, +1 for 8..15, -1 for 16..23, +1 for 24..31 ... + // Sample 0: lazy-init sets prevSample=-1. count=1. No crossing (x=-1). + // Sample 8: count=9 (>4). prevSample=-1<=0, x=+1>0 → crossing fires. freq=sr/9. count=0. + // Sample 24: count=16 (>4). prev=-1<=0, x=+1>0 → crossing. freq=sr/16. + // From sample 24 onward, freq is sr/16. + let period: Int = 16 + let halfPeriod: Int = period / 2 + let expectedFreq: Double = sampleRate / Double(period) + + let inputSignal: Closure = Closure { _, i in + ((i / halfPeriod) % 2 == 0) ? -1.0 : 1.0 + } + let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + + // The second rising crossing is at sample 24 (period=16, half=8: -1 @ 0..7, +1 @ 8..15, + // -1 @ 16..23, +1 @ 24..31). From sample 24 onward, freq should be sr/16. + let secondCrossingAt: Int = period + halfPeriod // 24 + for i: Int in secondCrossingAt.. zeroCrossingMinCount). Freq = sr/11. Count resets. + /// Second rising crossing fires at sample 30 with count = halfPeriod*2 = 20. Freq = sr/20. + /// Between crossings the output holds the last measured freq. + @Test func freqHeldBetweenCrossings() { + let halfPeriod: Int = 10 + // Start with -1 for first half-period so lazy-init sets prevSample=-1 (no crossing). + let inputSignal: Closure = Closure { _, i in + ((i / halfPeriod) % 2 == 0) ? -1.0 : 1.0 + } + let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + + // Samples 0..9: no crossing yet (count stays below threshold or x never >0), freq = 0. + for i: Int in 0..4). Freq = sr/11. + let firstCrossingCount: Int = halfPeriod + 1 + let freqAfterFirstCrossing: Double = sampleRate / Double(firstCrossingCount) + // Samples 10..29: freq held at freqAfterFirstCrossing (next crossing not until sample 30). + for i: Int in halfPeriod..<(halfPeriod * 3) { + #expect(abs(out[0][i] - freqAfterFirstCrossing) < 1e-9, + "sample \(i): expected \(freqAfterFirstCrossing) (held after 1st crossing), got \(out[0][i])") + } + // Sample 30: second rising crossing. Count since reset = halfPeriod*2 = 20 (>4). Freq = sr/20. + let secondCrossingCount: Int = halfPeriod * 2 + let freqAfterSecondCrossing: Double = sampleRate / Double(secondCrossingCount) + // Samples 30..49: freq held at freqAfterSecondCrossing. + for i: Int in (halfPeriod * 3)..<(halfPeriod * 5) { + #expect(abs(out[0][i] - freqAfterSecondCrossing) < 1e-9, + "sample \(i): expected \(freqAfterSecondCrossing) (held after 2nd crossing), got \(out[0][i])") + } + } + + /// Cross-block continuity: state (counter) carries across audio blocks. + @Test func crossBlockContinuity() { + // Square wave with period 32: crossing happens at sample 16 and 32 (=0 of block 2). + // Block 1 measures 32 samples between crossings (at sample 16 the count includes samples + // from the previous block which starts at 0, so count = 16+prev if counter carried). + // This test verifies counter survives block boundary — non-zero freq in block 2. + let halfPeriod: Int = 16 + let inputSignal: Closure = Closure { _, i in + ((i / halfPeriod) % 2 == 0) ? 1.0 : -1.0 + } + let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal) + _ = gen.calculatedSamples(graph: graph, count: blockSize) + advanceBlock(engine) + + let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + // Block 2 should still detect crossings and emit a non-zero freq. + var hasNonZero: Bool = false + for i: Int in 0.. 0.0 { + hasNonZero = true + break + } + } + #expect(hasNonZero, "expected non-zero freq in block 2 (counter should carry across blocks)") + } + + /// Fan-out: two calls same segment return identical first channel. + @Test func fanOut() { + let inputSignal: Closure = Closure { _, i in i % 8 < 4 ? 1.0 : -1.0 } + let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal) + let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0..0` is false). Freq stays 0 throughout the block. + @Test func constantNegativeInputNoZeroCrossing() { + let gen: ZeroCrossing.Control = ZeroCrossing.Control(input: -1.0) + _ = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(gen.previousOutputValue == 0.0, + "constant negative input: freq should remain 0, got \(gen.previousOutputValue)") + } + + /// Square wave with period P samples yields freq = sampleRate / P (measured + /// over the full audio block at audio rate, reported as flat block-final value). + /// + /// Signal starts at -1, so lazy-init sets `_prevSample = -1` on sample 0 and no + /// spurious crossing fires. The first crossing fires at sample 8 (count=9>4, freq=sr/9); + /// subsequent crossings measure exactly P=16 (count=16>4, freq=sr/16). Block-final + /// value after 64 samples is sr/16. + @Test func squareWaveKnownPeriodYieldsExpectedFreq() { + // Period = 16 samples → expected freq = 44100 / 16 = 2756.25 Hz. + let period: Int = 16 + let expectedFreq: Double = sampleRate / Double(period) + // -1 for first half, +1 for second half, repeating. + let inputSignal: Closure = Closure { _, i in + ((i / (period / 2)) % 2 == 0) ? -1.0 : 1.0 + } + let gen: ZeroCrossing.Control = ZeroCrossing.Control(input: inputSignal) + _ = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(abs(gen.previousOutputValue - expectedFreq) < 1e-9, + "expected freq \(expectedFreq), got \(gen.previousOutputValue)") + } + + /// Output block is flat: all samples equal the block-final freq. + @Test func outputBlockIsFlat() { + let period: Int = 8 + let inputSignal: Closure = Closure { _, i in + ((i / (period / 2)) % 2 == 0) ? -1.0 : 1.0 + } + let gen: ZeroCrossing.Control = ZeroCrossing.Control(input: inputSignal) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + let expected: Double = out[0][blockSize - 1] + for i: Int in 0.. 0.0, + "freq should be non-zero in block 2 (state carries across blocks)") + } + + /// mul/add: output is original*2+1. + @Test func mulAdd() { + let period: Int = 16 + let inputSignal: Closure = Closure { _, i in + ((i / (period / 2)) % 2 == 0) ? -1.0 : 1.0 + } + let genBase: ZeroCrossing.Control = ZeroCrossing.Control(input: inputSignal) + let genScaled: ZeroCrossing.Control = ZeroCrossing.Control( + input: inputSignal, + mul: 2.0, + add: 1.0 + ) + let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize) + let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize) + // Both should have a consistent relationship: scaled[i] = base[i]*2+1. + for i: Int in 0.. 10) + } + + @Test func allInterpolationModesFinite() { + for mode: TableInterpolation in [.none, .linear, .cubic] { + let m: CuspStepped.Audio = CuspStepped.Audio(freq: 4000.0, interpolation: mode) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 20) + #expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite") + } + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let a1: CuspStepped.Audio = CuspStepped.Audio(freq: 8000.0) + let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 10) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let a2: CuspStepped.Audio = CuspStepped.Audio(freq: 8000.0) + let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 10) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let m: CuspStepped.Audio = CuspStepped.Audio(freq: 8000.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } + + @Test func mulAddScalesAndOffsets() { + let plain: CuspStepped.Audio = CuspStepped.Audio(freq: 0.0) + let g1: SynthGraph = makeSynthGraph(engine: engine) + let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0] + let scaled: CuspStepped.Audio = CuspStepped.Audio(freq: 0.0, mul: 0.5, add: 1.0) + let g2: SynthGraph = makeSynthGraph(engine: engine) + let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0] + #expect(abs(s - (p * 0.5 + 1.0)) < 1e-12) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/CuspSteppedControlTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/CuspSteppedControlTests.swift new file mode 100644 index 0000000..1e6b122 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/CuspSteppedControlTests.swift @@ -0,0 +1,56 @@ +// CuspSteppedControlTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - CuspSteppedControlTests + +@MainActor +@Suite("CuspStepped.Control") +struct CuspSteppedControlTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func freqZeroRampsToPrimedValue() { + let m: CuspStepped.Control = CuspStepped.Control(freq: 0.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][engine.blockSize - 1] - (-0.9)) < 1e-9) + } + + @Test func finiteBoundedOutput() { + let m: CuspStepped.Control = CuspStepped.Control(freq: 200.0) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 40) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { abs($0) < 1.5 }) + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let a1: CuspStepped.Control = CuspStepped.Control(freq: 500.0) + let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 20) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let a2: CuspStepped.Control = CuspStepped.Control(freq: 500.0) + let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 20) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let m: CuspStepped.Control = CuspStepped.Control(freq: 500.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/FBSineSteppedAudioTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/FBSineSteppedAudioTests.swift new file mode 100644 index 0000000..74313bc --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/FBSineSteppedAudioTests.swift @@ -0,0 +1,83 @@ +// FBSineSteppedAudioTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - FBSineSteppedAudioTests + +@MainActor +@Suite("FBSineStepped.Audio") +struct FBSineSteppedAudioTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func deterministicSteppedIterations() { + // freq == sampleRate, .none → held outputs are the warm-up iterates 2,3,… + let m: FBSineStepped.Audio = FBSineStepped.Audio(freq: sr, interpolation: .none) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][0] - (0.5818307174710479)) < 1e-9) + #expect(abs(s[0][1] - (0.9422154392244042)) < 1e-9) + } + + @Test func freqZeroHoldsSecondIteration() { + let m: FBSineStepped.Audio = FBSineStepped.Audio(freq: 0.0) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 4) + #expect(samples.allSatisfy { abs($0 - (0.5818307174710479)) < 1e-9 }) + } + + @Test func chaoticOrbitStaysBounded() { + let m: FBSineStepped.Audio = FBSineStepped.Audio(freq: sr) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 50) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { abs($0) <= 1.0 + 1e-12 }) // x = sin in [-1,1] + #expect(Set(samples.map { ($0 * 1e4).rounded() }).count > 10) + } + + @Test func allInterpolationModesFinite() { + for mode: TableInterpolation in [.none, .linear, .cubic] { + let m: FBSineStepped.Audio = FBSineStepped.Audio(freq: 4000.0, interpolation: mode) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 20) + #expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite") + } + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let a1: FBSineStepped.Audio = FBSineStepped.Audio(freq: 8000.0) + let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 10) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let a2: FBSineStepped.Audio = FBSineStepped.Audio(freq: 8000.0) + let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 10) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let m: FBSineStepped.Audio = FBSineStepped.Audio(freq: 8000.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } + + @Test func mulAddScalesAndOffsets() { + let plain: FBSineStepped.Audio = FBSineStepped.Audio(freq: 0.0) + let g1: SynthGraph = makeSynthGraph(engine: engine) + let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0] + let scaled: FBSineStepped.Audio = FBSineStepped.Audio(freq: 0.0, mul: 0.5, add: 1.0) + let g2: SynthGraph = makeSynthGraph(engine: engine) + let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0] + #expect(abs(s - (p * 0.5 + 1.0)) < 1e-12) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/FBSineSteppedControlTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/FBSineSteppedControlTests.swift new file mode 100644 index 0000000..c6bd828 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/FBSineSteppedControlTests.swift @@ -0,0 +1,56 @@ +// FBSineSteppedControlTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - FBSineSteppedControlTests + +@MainActor +@Suite("FBSineStepped.Control") +struct FBSineSteppedControlTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func freqZeroRampsToPrimedValue() { + let m: FBSineStepped.Control = FBSineStepped.Control(freq: 0.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][engine.blockSize - 1] - (0.5818307174710479)) < 1e-9) + } + + @Test func finiteBoundedOutput() { + let m: FBSineStepped.Control = FBSineStepped.Control(freq: 200.0) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 40) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { abs($0) <= 1.0 + 1e-12 }) + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let a1: FBSineStepped.Control = FBSineStepped.Control(freq: 500.0) + let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 20) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let a2: FBSineStepped.Control = FBSineStepped.Control(freq: 500.0) + let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 20) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let m: FBSineStepped.Control = FBSineStepped.Control(freq: 500.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/GbmanSteppedAudioTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/GbmanSteppedAudioTests.swift new file mode 100644 index 0000000..e1b14a0 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/GbmanSteppedAudioTests.swift @@ -0,0 +1,85 @@ +// GbmanSteppedAudioTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - GbmanSteppedAudioTests + +@MainActor +@Suite("GbmanStepped.Audio") +struct GbmanSteppedAudioTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func deterministicSteppedIterations() { + // freq == sampleRate, .none. xi=1.2, yi=2.1: iterates 0.1, -0.1, 1.0, 2.1, … + // → held outputs -0.1, 1.0, 2.1, … + let gb: GbmanStepped.Audio = GbmanStepped.Audio(freq: sr, interpolation: .none) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = gb.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][0] - (-0.1)) < 1e-9) + #expect(abs(s[0][1] - 1.0) < 1e-9) + #expect(abs(s[0][2] - 2.1) < 1e-9) + } + + @Test func freqZeroHoldsSecondIteration() { + let gb: GbmanStepped.Audio = GbmanStepped.Audio(freq: 0.0) + let samples: [Double] = collectBlocks(gb, engine: engine, blocks: 4) + #expect(samples.allSatisfy { abs($0 - (-0.1)) < 1e-9 }) + } + + @Test func chaoticOrbitStaysBounded() { + let gb: GbmanStepped.Audio = GbmanStepped.Audio(freq: sr) + let samples: [Double] = collectBlocks(gb, engine: engine, blocks: 50) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { abs($0) < 10.0 }) + #expect(Set(samples.map { ($0 * 1e4).rounded() }).count > 10) + } + + @Test func allInterpolationModesFinite() { + for mode: TableInterpolation in [.none, .linear, .cubic] { + let gb: GbmanStepped.Audio = GbmanStepped.Audio(freq: 4000.0, interpolation: mode) + let samples: [Double] = collectBlocks(gb, engine: engine, blocks: 20) + #expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite") + } + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let a1: GbmanStepped.Audio = GbmanStepped.Audio(freq: 8000.0) + let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 10) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let a2: GbmanStepped.Audio = GbmanStepped.Audio(freq: 8000.0) + let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 10) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let gb: GbmanStepped.Audio = GbmanStepped.Audio(freq: 8000.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = gb.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = gb.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } + + @Test func mulAddScalesAndOffsets() { + let plain: GbmanStepped.Audio = GbmanStepped.Audio(freq: 0.0) + let g1: SynthGraph = makeSynthGraph(engine: engine) + let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0] + let scaled: GbmanStepped.Audio = GbmanStepped.Audio(freq: 0.0, mul: 0.5, add: 1.0) + let g2: SynthGraph = makeSynthGraph(engine: engine) + let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0] + #expect(abs(s - (p * 0.5 + 1.0)) < 1e-12) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/GbmanSteppedControlTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/GbmanSteppedControlTests.swift new file mode 100644 index 0000000..ea10ebf --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/GbmanSteppedControlTests.swift @@ -0,0 +1,56 @@ +// GbmanSteppedControlTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - GbmanSteppedControlTests + +@MainActor +@Suite("GbmanStepped.Control") +struct GbmanSteppedControlTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func freqZeroRampsToPrimedValue() { + let gb: GbmanStepped.Control = GbmanStepped.Control(freq: 0.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = gb.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][engine.blockSize - 1] - (-0.1)) < 1e-9) + } + + @Test func finiteBoundedOutput() { + let gb: GbmanStepped.Control = GbmanStepped.Control(freq: 200.0) + let samples: [Double] = collectBlocks(gb, engine: engine, blocks: 40) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { abs($0) < 10.0 }) + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let a1: GbmanStepped.Control = GbmanStepped.Control(freq: 500.0) + let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 20) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let a2: GbmanStepped.Control = GbmanStepped.Control(freq: 500.0) + let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 20) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let gb: GbmanStepped.Control = GbmanStepped.Control(freq: 500.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = gb.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = gb.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/HenonSteppedAudioTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/HenonSteppedAudioTests.swift new file mode 100644 index 0000000..29373e7 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/HenonSteppedAudioTests.swift @@ -0,0 +1,94 @@ +// HenonSteppedAudioTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - HenonSteppedAudioTests + +@MainActor +@Suite("HenonStepped.Audio") +struct HenonSteppedAudioTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func deterministicSteppedIterations() { + // freq == sampleRate → dphase = 1, one iteration per sample, .none holds the + // segment start. With a=1.4, b=0.3, x0=x1=0 the warm-up iterations are + // 1, -0.4, 1.076, -0.7408864; after 4-iteration priming the held outputs are + // -0.4, 1.076, -0.7408864, ... + let henon: HenonStepped.Audio = HenonStepped.Audio(freq: sr, a: 1.4, b: 0.3, + x0: 0.0, x1: 0.0, interpolation: .none) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = henon.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][0] - (-0.4)) < 1e-9) + #expect(abs(s[0][1] - 1.076) < 1e-9) + #expect(abs(s[0][2] - (-0.7408864)) < 1e-9) + } + + @Test func chaoticOrbitStaysBounded() { + let henon: HenonStepped.Audio = HenonStepped.Audio(freq: sr) // canonical a/b + let samples: [Double] = collectBlocks(henon, engine: engine, blocks: 50) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { abs($0) < 2.0 }) + // Not a constant — the orbit visits distinct values. + #expect(Set(samples.map { ($0 * 1e6).rounded() }).count > 10) + } + + @Test func allInterpolationModesFinite() { + for mode: TableInterpolation in [.none, .linear, .cubic] { + let henon: HenonStepped.Audio = HenonStepped.Audio(freq: 4000.0, interpolation: mode) + let samples: [Double] = collectBlocks(henon, engine: engine, blocks: 20) + #expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite") + } + } + + @Test func freqZeroHoldsConstant() { + // dphase = 0 → never iterates past priming → constant held output. + let henon: HenonStepped.Audio = HenonStepped.Audio(freq: 0.0, interpolation: .linear) + let samples: [Double] = collectBlocks(henon, engine: engine, blocks: 4) + let first: Double = samples.first ?? .nan + #expect(samples.allSatisfy { $0 == first }) + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let h1: HenonStepped.Audio = HenonStepped.Audio(freq: 8000.0) + let s1: [Double] = collectBlocks(h1, engine: engine, blocks: 10) + + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let h2: HenonStepped.Audio = HenonStepped.Audio(freq: 8000.0) + let s2: [Double] = collectBlocks(h2, engine: engine2, blocks: 10) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let henon: HenonStepped.Audio = HenonStepped.Audio(freq: 8000.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = henon.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = henon.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } + + @Test func mulAddScalesAndOffsets() { + let plain: HenonStepped.Audio = HenonStepped.Audio(freq: sr, interpolation: .none) + let g1: SynthGraph = makeSynthGraph(engine: engine) + let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0] + + let scaled: HenonStepped.Audio = HenonStepped.Audio(freq: sr, interpolation: .none, + mul: 2.0, add: 1.0) + let g2: SynthGraph = makeSynthGraph(engine: engine) + let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0] + #expect(abs(s - (p * 2.0 + 1.0)) < 1e-12) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/HenonSteppedControlTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/HenonSteppedControlTests.swift new file mode 100644 index 0000000..db92292 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/HenonSteppedControlTests.swift @@ -0,0 +1,60 @@ +// HenonSteppedControlTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - HenonSteppedControlTests + +@MainActor +@Suite("HenonStepped.Control") +struct HenonSteppedControlTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func finiteBoundedOutput() { + let henon: HenonStepped.Control = HenonStepped.Control(freq: 200.0) + let samples: [Double] = collectBlocks(henon, engine: engine, blocks: 40) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { abs($0) < 2.0 }) + } + + @Test func freqZeroRampsToPrimedValue() { + // dphase = 0 → no iteration past priming; .none holds h0 = -0.4 (2nd Hénon + // iterate for a=1.4, b=0.3, x0=x1=0). The block ramps 0 → -0.4, so the last + // sample equals the target exactly. + let henon: HenonStepped.Control = HenonStepped.Control(freq: 0.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = henon.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][engine.blockSize - 1] - (-0.4)) < 1e-12) + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let h1: HenonStepped.Control = HenonStepped.Control(freq: 500.0) + let s1: [Double] = collectBlocks(h1, engine: engine, blocks: 20) + + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let h2: HenonStepped.Control = HenonStepped.Control(freq: 500.0) + let s2: [Double] = collectBlocks(h2, engine: engine2, blocks: 20) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let henon: HenonStepped.Control = HenonStepped.Control(freq: 500.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = henon.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = henon.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/LatoocarfianSteppedAudioTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/LatoocarfianSteppedAudioTests.swift new file mode 100644 index 0000000..23c2e2c --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/LatoocarfianSteppedAudioTests.swift @@ -0,0 +1,83 @@ +// LatoocarfianSteppedAudioTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - LatoocarfianSteppedAudioTests + +@MainActor +@Suite("LatoocarfianStepped.Audio") +struct LatoocarfianSteppedAudioTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func deterministicSteppedIterations() { + // freq == sampleRate, .none → held outputs are the warm-up iterates 2,3,… + let m: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: sr, interpolation: .none) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][0] - (0.34527127964613574)) < 1e-9) + #expect(abs(s[0][1] - (-0.31328745455281626)) < 1e-9) + } + + @Test func freqZeroHoldsSecondIteration() { + let m: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 0.0) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 4) + #expect(samples.allSatisfy { abs($0 - (0.34527127964613574)) < 1e-9 }) + } + + @Test func chaoticOrbitStaysBounded() { + let m: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: sr) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 50) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { abs($0) < 2.0 }) // x in ~[-1.5,1.5] + #expect(Set(samples.map { ($0 * 1e4).rounded() }).count > 10) + } + + @Test func allInterpolationModesFinite() { + for mode: TableInterpolation in [.none, .linear, .cubic] { + let m: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 4000.0, interpolation: mode) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 20) + #expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite") + } + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let a1: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 8000.0) + let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 10) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let a2: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 8000.0) + let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 10) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let m: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 8000.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } + + @Test func mulAddScalesAndOffsets() { + let plain: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 0.0) + let g1: SynthGraph = makeSynthGraph(engine: engine) + let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0] + let scaled: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 0.0, mul: 0.5, add: 1.0) + let g2: SynthGraph = makeSynthGraph(engine: engine) + let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0] + #expect(abs(s - (p * 0.5 + 1.0)) < 1e-12) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/LatoocarfianSteppedControlTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/LatoocarfianSteppedControlTests.swift new file mode 100644 index 0000000..434a7cb --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/LatoocarfianSteppedControlTests.swift @@ -0,0 +1,56 @@ +// LatoocarfianSteppedControlTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - LatoocarfianSteppedControlTests + +@MainActor +@Suite("LatoocarfianStepped.Control") +struct LatoocarfianSteppedControlTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func freqZeroRampsToPrimedValue() { + let m: LatoocarfianStepped.Control = LatoocarfianStepped.Control(freq: 0.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][engine.blockSize - 1] - (0.34527127964613574)) < 1e-9) + } + + @Test func finiteBoundedOutput() { + let m: LatoocarfianStepped.Control = LatoocarfianStepped.Control(freq: 200.0) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 40) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { abs($0) < 2.0 }) + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let a1: LatoocarfianStepped.Control = LatoocarfianStepped.Control(freq: 500.0) + let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 20) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let a2: LatoocarfianStepped.Control = LatoocarfianStepped.Control(freq: 500.0) + let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 20) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let m: LatoocarfianStepped.Control = LatoocarfianStepped.Control(freq: 500.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/LinCongSteppedAudioTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/LinCongSteppedAudioTests.swift new file mode 100644 index 0000000..f4e6805 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/LinCongSteppedAudioTests.swift @@ -0,0 +1,83 @@ +// LinCongSteppedAudioTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - LinCongSteppedAudioTests + +@MainActor +@Suite("LinCongStepped.Audio") +struct LinCongSteppedAudioTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func deterministicSteppedIterations() { + // freq == sampleRate, .none. a=1.1, c=0.13, m=1, xi=0: iterates + // 0.13, 0.273, 0.4303, … → held outputs 0.273, 0.4303, … + let lc: LinCongStepped.Audio = LinCongStepped.Audio(freq: sr, interpolation: .none) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = lc.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][0] - 0.273) < 1e-9) + #expect(abs(s[0][1] - 0.4303) < 1e-9) + } + + @Test func freqZeroHoldsSecondIteration() { + let lc: LinCongStepped.Audio = LinCongStepped.Audio(freq: 0.0) + let samples: [Double] = collectBlocks(lc, engine: engine, blocks: 4) + #expect(samples.allSatisfy { abs($0 - 0.273) < 1e-12 }) + } + + @Test func staysInZeroToModulusRange() { + let lc: LinCongStepped.Audio = LinCongStepped.Audio(freq: sr) + let samples: [Double] = collectBlocks(lc, engine: engine, blocks: 60) + #expect(samples.allSatisfy { $0 >= 0.0 && $0 < 1.0 }) + #expect(Set(samples.map { ($0 * 1e6).rounded() }).count > 10) + } + + @Test func allInterpolationModesFinite() { + for mode: TableInterpolation in [.none, .linear, .cubic] { + let lc: LinCongStepped.Audio = LinCongStepped.Audio(freq: 4000.0, interpolation: mode) + let samples: [Double] = collectBlocks(lc, engine: engine, blocks: 20) + #expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite") + } + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let a1: LinCongStepped.Audio = LinCongStepped.Audio(freq: 8000.0) + let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 10) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let a2: LinCongStepped.Audio = LinCongStepped.Audio(freq: 8000.0) + let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 10) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let lc: LinCongStepped.Audio = LinCongStepped.Audio(freq: 8000.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = lc.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = lc.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } + + @Test func mulAddScalesAndOffsets() { + let plain: LinCongStepped.Audio = LinCongStepped.Audio(freq: 0.0) + let g1: SynthGraph = makeSynthGraph(engine: engine) + let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0] + let scaled: LinCongStepped.Audio = LinCongStepped.Audio(freq: 0.0, mul: 2.0, add: -1.0) + let g2: SynthGraph = makeSynthGraph(engine: engine) + let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0] + #expect(abs(s - (p * 2.0 - 1.0)) < 1e-12) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/LinCongSteppedControlTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/LinCongSteppedControlTests.swift new file mode 100644 index 0000000..a6c6bc7 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/LinCongSteppedControlTests.swift @@ -0,0 +1,56 @@ +// LinCongSteppedControlTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - LinCongSteppedControlTests + +@MainActor +@Suite("LinCongStepped.Control") +struct LinCongSteppedControlTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func freqZeroRampsToPrimedValue() { + let lc: LinCongStepped.Control = LinCongStepped.Control(freq: 0.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = lc.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][engine.blockSize - 1] - 0.273) < 1e-12) + } + + @Test func finiteBoundedOutput() { + let lc: LinCongStepped.Control = LinCongStepped.Control(freq: 200.0) + let samples: [Double] = collectBlocks(lc, engine: engine, blocks: 40) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { $0 >= 0.0 && $0 < 1.0 }) + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let a1: LinCongStepped.Control = LinCongStepped.Control(freq: 500.0) + let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 20) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let a2: LinCongStepped.Control = LinCongStepped.Control(freq: 500.0) + let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 20) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let lc: LinCongStepped.Control = LinCongStepped.Control(freq: 500.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = lc.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = lc.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/LorenzLinearAudioTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/LorenzLinearAudioTests.swift new file mode 100644 index 0000000..b049219 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/LorenzLinearAudioTests.swift @@ -0,0 +1,80 @@ +// LorenzLinearAudioTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - LorenzLinearAudioTests + +@MainActor +@Suite("LorenzLinear.Audio") +struct LorenzLinearAudioTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func freqZeroHoldsSecondIterationValue() { + // dphase = 0 → output stays at the primed segment start h0 (= the 2nd Euler + // iteration). With s=10, r=28, b=2.667, h=0.02, xi=0.1: iterations are + // x1 = 0.08, x2 = 0.0752, so h0 = 0.0752. + let lorenz: LorenzLinear.Audio = LorenzLinear.Audio(freq: 0.0) + let samples: [Double] = collectBlocks(lorenz, engine: engine, blocks: 4) + #expect(samples.allSatisfy { abs($0 - 0.0752) < 1e-12 }) + } + + @Test func orbitFiniteAndEvolves() { + let lorenz: LorenzLinear.Audio = LorenzLinear.Audio(freq: sr) + let samples: [Double] = collectBlocks(lorenz, engine: engine, blocks: 200) + #expect(samples.allSatisfy { $0.isFinite }) + // Canonical Lorenz x stays bounded to roughly ±25. + #expect(samples.allSatisfy { abs($0) < 30.0 }) + #expect(Set(samples.map { ($0 * 1e4).rounded() }).count > 50) + } + + @Test func allInterpolationModesFinite() { + for mode: TableInterpolation in [.none, .linear, .cubic] { + let lorenz: LorenzLinear.Audio = LorenzLinear.Audio(freq: 6000.0, interpolation: mode) + let samples: [Double] = collectBlocks(lorenz, engine: engine, blocks: 20) + #expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite") + } + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let l1: LorenzLinear.Audio = LorenzLinear.Audio(freq: 9000.0) + let s1: [Double] = collectBlocks(l1, engine: engine, blocks: 30) + + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let l2: LorenzLinear.Audio = LorenzLinear.Audio(freq: 9000.0) + let s2: [Double] = collectBlocks(l2, engine: engine2, blocks: 30) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let lorenz: LorenzLinear.Audio = LorenzLinear.Audio(freq: 9000.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = lorenz.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = lorenz.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } + + @Test func mulAddScalesAndOffsets() { + let plain: LorenzLinear.Audio = LorenzLinear.Audio(freq: 0.0) + let g1: SynthGraph = makeSynthGraph(engine: engine) + let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0] + + let scaled: LorenzLinear.Audio = LorenzLinear.Audio(freq: 0.0, mul: 0.05, add: 0.5) + let g2: SynthGraph = makeSynthGraph(engine: engine) + let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0] + #expect(abs(s - (p * 0.05 + 0.5)) < 1e-12) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/LorenzLinearControlTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/LorenzLinearControlTests.swift new file mode 100644 index 0000000..ef821b9 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/LorenzLinearControlTests.swift @@ -0,0 +1,60 @@ +// LorenzLinearControlTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - LorenzLinearControlTests + +@MainActor +@Suite("LorenzLinear.Control") +struct LorenzLinearControlTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func finiteBoundedOutput() { + let lorenz: LorenzLinear.Control = LorenzLinear.Control(freq: 200.0, mul: 0.05) + let samples: [Double] = collectBlocks(lorenz, engine: engine, blocks: 40) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { abs($0) < 2.0 }) + } + + @Test func freqZeroRampsToPrimedValue() { + // dphase = 0 → no iteration past priming. The block ramps from the initial + // _rampTarget (0) to h0 = 0.0752 (2nd Euler iterate, h=0.02), so the block's + // last sample equals the target exactly. + let lorenz: LorenzLinear.Control = LorenzLinear.Control(freq: 0.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = lorenz.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][engine.blockSize - 1] - 0.0752) < 1e-12) + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let l1: LorenzLinear.Control = LorenzLinear.Control(freq: 600.0) + let s1: [Double] = collectBlocks(l1, engine: engine, blocks: 20) + + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let l2: LorenzLinear.Control = LorenzLinear.Control(freq: 600.0) + let s2: [Double] = collectBlocks(l2, engine: engine2, blocks: 20) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let lorenz: LorenzLinear.Control = LorenzLinear.Control(freq: 600.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = lorenz.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = lorenz.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/QuadSteppedAudioTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/QuadSteppedAudioTests.swift new file mode 100644 index 0000000..452f9b3 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/QuadSteppedAudioTests.swift @@ -0,0 +1,85 @@ +// QuadSteppedAudioTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - QuadSteppedAudioTests + +@MainActor +@Suite("QuadStepped.Audio") +struct QuadSteppedAudioTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func deterministicSteppedIterations() { + // freq == sampleRate → one iteration per sample, .none holds the segment start. + // a=1, b=-1, c=-0.75, xi=0: warm-up iterates -0.75, 0.5625, -0.99609375, …; + // after 4-iteration priming the held outputs are 0.5625, -0.99609375, … + let q: QuadStepped.Audio = QuadStepped.Audio(freq: sr, interpolation: .none) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = q.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][0] - 0.5625) < 1e-9) + #expect(abs(s[0][1] - (-0.99609375)) < 1e-9) + } + + @Test func freqZeroHoldsSecondIteration() { + let q: QuadStepped.Audio = QuadStepped.Audio(freq: 0.0) + let samples: [Double] = collectBlocks(q, engine: engine, blocks: 4) + #expect(samples.allSatisfy { abs($0 - 0.5625) < 1e-12 }) + } + + @Test func chaoticOrbitStaysBounded() { + let q: QuadStepped.Audio = QuadStepped.Audio(freq: sr) + let samples: [Double] = collectBlocks(q, engine: engine, blocks: 50) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { abs($0) < 2.0 }) + #expect(Set(samples.map { ($0 * 1e6).rounded() }).count > 10) + } + + @Test func allInterpolationModesFinite() { + for mode: TableInterpolation in [.none, .linear, .cubic] { + let q: QuadStepped.Audio = QuadStepped.Audio(freq: 4000.0, interpolation: mode) + let samples: [Double] = collectBlocks(q, engine: engine, blocks: 20) + #expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite") + } + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let q1: QuadStepped.Audio = QuadStepped.Audio(freq: 8000.0) + let s1: [Double] = collectBlocks(q1, engine: engine, blocks: 10) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let q2: QuadStepped.Audio = QuadStepped.Audio(freq: 8000.0) + let s2: [Double] = collectBlocks(q2, engine: engine2, blocks: 10) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let q: QuadStepped.Audio = QuadStepped.Audio(freq: 8000.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = q.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = q.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } + + @Test func mulAddScalesAndOffsets() { + let plain: QuadStepped.Audio = QuadStepped.Audio(freq: 0.0) + let g1: SynthGraph = makeSynthGraph(engine: engine) + let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0] + let scaled: QuadStepped.Audio = QuadStepped.Audio(freq: 0.0, mul: 2.0, add: 1.0) + let g2: SynthGraph = makeSynthGraph(engine: engine) + let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0] + #expect(abs(s - (p * 2.0 + 1.0)) < 1e-12) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/QuadSteppedControlTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/QuadSteppedControlTests.swift new file mode 100644 index 0000000..c47b68b --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/QuadSteppedControlTests.swift @@ -0,0 +1,56 @@ +// QuadSteppedControlTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - QuadSteppedControlTests + +@MainActor +@Suite("QuadStepped.Control") +struct QuadSteppedControlTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func freqZeroRampsToPrimedValue() { + let q: QuadStepped.Control = QuadStepped.Control(freq: 0.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = q.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][engine.blockSize - 1] - 0.5625) < 1e-12) + } + + @Test func finiteBoundedOutput() { + let q: QuadStepped.Control = QuadStepped.Control(freq: 200.0) + let samples: [Double] = collectBlocks(q, engine: engine, blocks: 40) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { abs($0) < 2.0 }) + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let q1: QuadStepped.Control = QuadStepped.Control(freq: 500.0) + let s1: [Double] = collectBlocks(q1, engine: engine, blocks: 20) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let q2: QuadStepped.Control = QuadStepped.Control(freq: 500.0) + let s2: [Double] = collectBlocks(q2, engine: engine2, blocks: 20) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let q: QuadStepped.Control = QuadStepped.Control(freq: 500.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = q.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = q.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/StandardSteppedAudioTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/StandardSteppedAudioTests.swift new file mode 100644 index 0000000..30989c7 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/StandardSteppedAudioTests.swift @@ -0,0 +1,83 @@ +// StandardSteppedAudioTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - StandardSteppedAudioTests + +@MainActor +@Suite("StandardStepped.Audio") +struct StandardSteppedAudioTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func deterministicSteppedIterations() { + // freq == sampleRate, .none → held outputs are the warm-up iterates 2,3,… + let m: StandardStepped.Audio = StandardStepped.Audio(freq: sr, interpolation: .none) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][0] - (2.2890283227337602)) < 1e-9) + #expect(abs(s[0][1] - (4.351601455163474)) < 1e-9) + } + + @Test func freqZeroHoldsSecondIteration() { + let m: StandardStepped.Audio = StandardStepped.Audio(freq: 0.0) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 4) + #expect(samples.allSatisfy { abs($0 - (2.2890283227337602)) < 1e-9 }) + } + + @Test func chaoticOrbitStaysBounded() { + let m: StandardStepped.Audio = StandardStepped.Audio(freq: sr) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 50) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { $0 >= 0.0 && $0 < lyrebirdTwoPi }) // x in [0, 2pi) + #expect(Set(samples.map { ($0 * 1e4).rounded() }).count > 10) + } + + @Test func allInterpolationModesFinite() { + for mode: TableInterpolation in [.none, .linear, .cubic] { + let m: StandardStepped.Audio = StandardStepped.Audio(freq: 4000.0, interpolation: mode) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 20) + #expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite") + } + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let a1: StandardStepped.Audio = StandardStepped.Audio(freq: 8000.0) + let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 10) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let a2: StandardStepped.Audio = StandardStepped.Audio(freq: 8000.0) + let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 10) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let m: StandardStepped.Audio = StandardStepped.Audio(freq: 8000.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } + + @Test func mulAddScalesAndOffsets() { + let plain: StandardStepped.Audio = StandardStepped.Audio(freq: 0.0) + let g1: SynthGraph = makeSynthGraph(engine: engine) + let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0] + let scaled: StandardStepped.Audio = StandardStepped.Audio(freq: 0.0, mul: 0.5, add: 1.0) + let g2: SynthGraph = makeSynthGraph(engine: engine) + let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0] + #expect(abs(s - (p * 0.5 + 1.0)) < 1e-12) + } +} diff --git a/Tests/LyrebirdTests/Generators/Chaotic/StandardSteppedControlTests.swift b/Tests/LyrebirdTests/Generators/Chaotic/StandardSteppedControlTests.swift new file mode 100644 index 0000000..1adf3d1 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Chaotic/StandardSteppedControlTests.swift @@ -0,0 +1,56 @@ +// StandardSteppedControlTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - StandardSteppedControlTests + +@MainActor +@Suite("StandardStepped.Control") +struct StandardSteppedControlTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func freqZeroRampsToPrimedValue() { + let m: StandardStepped.Control = StandardStepped.Control(freq: 0.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(s[0][engine.blockSize - 1] - (2.2890283227337602)) < 1e-9) + } + + @Test func finiteBoundedOutput() { + let m: StandardStepped.Control = StandardStepped.Control(freq: 200.0) + let samples: [Double] = collectBlocks(m, engine: engine, blocks: 40) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { $0 >= 0.0 && $0 < lyrebirdTwoPi }) + } + + @Test func twoInstancesProduceIdenticalOutput() throws { + let a1: StandardStepped.Control = StandardStepped.Control(freq: 500.0) + let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 20) + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let a2: StandardStepped.Control = StandardStepped.Control(freq: 500.0) + let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 20) + #expect(s1 == s2) + } + + @Test func participatesInFanOutCache() { + let m: StandardStepped.Control = StandardStepped.Control(freq: 500.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } +} diff --git a/Tests/LyrebirdTests/Generators/Delays/DelayLineCubicTests.swift b/Tests/LyrebirdTests/Generators/Delays/DelayLineCubicTests.swift new file mode 100644 index 0000000..c5b7489 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Delays/DelayLineCubicTests.swift @@ -0,0 +1,93 @@ +// DelayLineCubicTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - DelayLineCubicTests + +@MainActor +@Suite("DelayLine cubic") +struct DelayLineCubicTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + /// A unit impulse through a fractional pure delay reproduces the interpolation + /// kernel's impulse response directly (no feedback to entangle the math). + /// Delay = 3.5 samples → integer part 3, frac 0.5. The impulse is written at + /// buffer index 0 (frame 0); reads happen before writes, so it surfaces across + /// the four cubic taps at frames 2…5. + + @Test func cubicImpulseResponseMatchesCatmullRomAtHalfSample() { + // catmullRomCubic basis at t = 0.5: pM1 → -0.0625, p0 → 0.5625, + // p1 → 0.5625, p2 → -0.0625. As the lone impulse passes through taps + // (i0,i1,i2,i3) = (writePos-intD+1 … -2), output[2..5] trace that basis. + let dl: DelayLine = DelayLine(input: Impulse.Audio(freq: 1.0), + maxDelay: 16.0 / sr, delay: 3.5 / sr, + sampleRate: sr, interpolation: .cubic) + let g: SynthGraph = makeSynthGraph(engine: engine) + let s: [Double] = dl.calculatedSamples(graph: g, count: engine.blockSize)[0] + + #expect(abs(s[0]) < 1e-12) + #expect(abs(s[1]) < 1e-12) + #expect(abs(s[2] - (-0.0625)) < 1e-12) + #expect(abs(s[3] - 0.5625) < 1e-12) + #expect(abs(s[4] - 0.5625) < 1e-12) + #expect(abs(s[5] - (-0.0625)) < 1e-12) + for i: Int in 6.. 1. With a gain + // lag the early output rises more slowly, so its early-window RMS is lower; both + // converge to the same tail level. + let unsmoothed: Balance = Balance(in: OscSin.Audio(freq: 200.0, mul: 0.2), + test: OscSin.Audio(freq: 200.0, mul: 0.5), smooth: 0.0) + let smoothed: Balance = Balance(in: OscSin.Audio(freq: 200.0, mul: 0.2), + test: OscSin.Audio(freq: 200.0, mul: 0.5), smooth: 0.1) + let u: [Double] = collectBlocks(unsmoothed, engine: engine, blocks: 300) + let s: [Double] = collectBlocks(smoothed, engine: engine, blocks: 300) + + let earlyWin: Int = engine.blockSize * 15 + #expect(rmsValue(Array(u.prefix(earlyWin))) > rmsValue(Array(s.prefix(earlyWin)))) + + let target: Double = 0.5 / 2.0.squareRoot() + #expect(abs(rmsValue(Array(u.suffix(engine.blockSize * 100))) - target) < 0.02) + #expect(abs(rmsValue(Array(s.suffix(engine.blockSize * 100))) - target) < 0.02) + } + + // MARK: - logDomain (decibel-domain gain glide) + + @Test func logDomainDCSteadyStateMatchesTestLevel() { + let bal: Balance = Balance(in: ConstantGeneratorInput(0.25), + test: ConstantGeneratorInput(0.5), smooth: 0.02, logDomain: true) + let all: [Double] = collectBlocks(bal, engine: engine, blocks: 500) + let tail: [Double] = Array(all.suffix(engine.blockSize * 50)) + let avg: Double = tail.reduce(0.0, +) / Double(tail.count) + #expect(abs(avg - 0.5) < 0.01) + } + + @Test func logDomainQuietSineMatchedUpToTestRMS() { + let quiet: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.2) + let loud: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.5) + let bal: Balance = Balance(in: quiet, test: loud, smooth: 0.02, logDomain: true) + let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 500) + let tail: [Double] = Array(samples.suffix(engine.blockSize * 100)) + let expected: Double = 0.5 / 2.0.squareRoot() + #expect(abs(rmsValue(tail) - expected) < 0.02) + } + + @Test func logDomainSilenceStaysSilentAndFinite() { + let bal: Balance = Balance(in: ConstantGeneratorInput(0.0), + test: ConstantGeneratorInput(0.0), logDomain: true) + let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 50) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(rmsValue(samples) < 1e-9) + } + + @Test func logDomainSilentInputStaysSilent() { + let bal: Balance = Balance(in: ConstantGeneratorInput(0.0), + test: OscSin.Audio(freq: 200.0, mul: 0.8), logDomain: true) + let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 100) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(rmsValue(samples) < 1e-9) + } + + @Test func logDomainSilentTestDrivesInputDown() { + let bal: Balance = Balance(in: OscSin.Audio(freq: 200.0, mul: 0.5), + test: ConstantGeneratorInput(0.0), smooth: 0.02, logDomain: true) + let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 300) + let tail: [Double] = Array(samples.suffix(engine.blockSize * 50)) + #expect(rmsValue(tail) < 0.01) + #expect(samples.allSatisfy { $0.isFinite }) + } + + @Test func logDomainMulScalesOutput() { + let plain: Balance = Balance(in: ConstantGeneratorInput(0.25), + test: ConstantGeneratorInput(0.5), smooth: 0.02, logDomain: true) + let scaled: Balance = Balance(in: ConstantGeneratorInput(0.25), + test: ConstantGeneratorInput(0.5), smooth: 0.02, logDomain: true, mul: 0.5) + let p: [Double] = Array(collectBlocks(plain, engine: engine, blocks: 500).suffix(engine.blockSize * 50)) + let s: [Double] = Array(collectBlocks(scaled, engine: engine, blocks: 500).suffix(engine.blockSize * 50)) + let pAvg: Double = p.reduce(0.0, +) / Double(p.count) + let sAvg: Double = s.reduce(0.0, +) / Double(s.count) + #expect(abs(sAvg - 0.5 * pAvg) < 0.01) + } + + @Test func logDomainFiniteWithNoise() { + let bal: Balance = Balance(in: WhiteNoise.Audio(mul: 0.1), + test: WhiteNoise.Audio(mul: 0.5), logDomain: true) + let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 200) + #expect(samples.allSatisfy { $0.isFinite }) + } +} diff --git a/Tests/LyrebirdTests/CompressorParameterRampingTests.swift b/Tests/LyrebirdTests/Generators/Dynamics/CompressorParameterRampingTests.swift similarity index 100% rename from Tests/LyrebirdTests/CompressorParameterRampingTests.swift rename to Tests/LyrebirdTests/Generators/Dynamics/CompressorParameterRampingTests.swift diff --git a/Tests/LyrebirdTests/DynamicsTests.swift b/Tests/LyrebirdTests/Generators/Dynamics/DynamicsTests.swift similarity index 100% rename from Tests/LyrebirdTests/DynamicsTests.swift rename to Tests/LyrebirdTests/Generators/Dynamics/DynamicsTests.swift diff --git a/Tests/LyrebirdTests/ExpanderParameterRampingTests.swift b/Tests/LyrebirdTests/Generators/Dynamics/ExpanderParameterRampingTests.swift similarity index 100% rename from Tests/LyrebirdTests/ExpanderParameterRampingTests.swift rename to Tests/LyrebirdTests/Generators/Dynamics/ExpanderParameterRampingTests.swift diff --git a/Tests/LyrebirdTests/Generators/Dynamics/NormalizerTests.swift b/Tests/LyrebirdTests/Generators/Dynamics/NormalizerTests.swift new file mode 100644 index 0000000..51a1209 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Dynamics/NormalizerTests.swift @@ -0,0 +1,136 @@ +// NormalizerTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +private func peak(_ samples: [Double]) -> Double { + samples.map { abs($0) }.max() ?? 0 +} + +@MainActor +@Suite("Normalizer") +struct NormalizerTests { + + let engine: SynthesisEngine + let sr: Double = 44100.0 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func quietSineNormalizedUpToLevel() { + // A sine well below `level` is scaled UP so its steady-state peak ≈ level. + let level: Double = 0.8 + let sine: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.2) + let norm: Normalizer = Normalizer(in: sine, level: level, dur: 0.01, sampleRate: sr) + let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 300) + let tail: [Double] = Array(samples.suffix(engine.blockSize * 100)) + let p: Double = peak(tail) + #expect(p > level - 0.05) + #expect(p < level + 0.02) + } + + @Test func loudSineNormalizedDownToLevel() { + // A sine above `level` is scaled DOWN; steady-state peak ≈ level, no overshoot. + let level: Double = 0.5 + let sine: OscSin.Audio = OscSin.Audio(freq: 220.0, mul: 2.0) + let norm: Normalizer = Normalizer(in: sine, level: level, dur: 0.01, sampleRate: sr) + let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 200) + let tail: [Double] = Array(samples.suffix(engine.blockSize * 100)) + let p: Double = peak(tail) + #expect(p > level - 0.05) + #expect(p < level + 0.001) + } + + @Test func peakNeverExceedsLevelOnTransient() { + // Look-ahead must pre-emptively reduce gain so a sudden loud burst never + // overshoots `level`. + let level: Double = 0.5 + let sine: OscSin.Audio = OscSin.Audio(freq: 110.0, mul: 3.0) + let norm: Normalizer = Normalizer(in: sine, level: level, dur: 0.01, sampleRate: sr) + let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 200) + let violators: [Double] = samples.filter { abs($0) > level + 0.001 } + #expect(violators.isEmpty) + } + + @Test func delayedByDurSamples() { + // An impulse at sample 0 appears delayed by Int(dur·sr); the first dur·sr + // output samples are zero. + let dur: Double = 0.003 + let delaySamples: Int = Int(dur * sr) + let impulse: Impulse.Audio = Impulse.Audio(freq: 0.0) + let norm: Normalizer = Normalizer(in: impulse, level: 1.0, dur: dur, sampleRate: sr) + let blocks: Int = (delaySamples / engine.blockSize) + 5 + let samples: [Double] = collectBlocks(norm, engine: engine, blocks: blocks) + let prefix: [Double] = Array(samples.prefix(delaySamples)) + #expect(prefix.allSatisfy { abs($0) < 0.001 }) + } + + @Test func levelParamScales() { + // Doubling `level` doubles the normalized steady-state peak. + let sine: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.3) + let low: Normalizer = Normalizer(in: sine, level: 0.3, dur: 0.01, sampleRate: sr) + let lowSamples: [Double] = collectBlocks(low, engine: engine, blocks: 300) + + let sine2: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.3) + let high: Normalizer = Normalizer(in: sine2, level: 0.6, dur: 0.01, sampleRate: sr) + let highSamples: [Double] = collectBlocks(high, engine: engine, blocks: 300) + + let pLow: Double = peak(Array(lowSamples.suffix(engine.blockSize * 100))) + let pHigh: Double = peak(Array(highSamples.suffix(engine.blockSize * 100))) + #expect(abs(pHigh - 2.0 * pLow) < 0.05) + } + + @Test func silenceStaysSilentAndFinite() { + // Zero input must not blow up (no level/0 division producing NaN/Inf). + let silence: ConstantGeneratorInput = ConstantGeneratorInput(0.0) + let norm: Normalizer = Normalizer(in: silence, level: 1.0, dur: 0.01, sampleRate: sr) + let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 50) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(peak(samples) < 1e-9) + } + + @Test func dcConvergesToLevel() { + // Constant DC v with level L → gain converges to L/v, output → L. + let level: Double = 0.5 + let dc: ConstantGeneratorInput = ConstantGeneratorInput(0.25) + let norm: Normalizer = Normalizer(in: dc, level: level, dur: 0.01, sampleRate: sr) + let all: [Double] = collectBlocks(norm, engine: engine, blocks: 300) + let tail: [Double] = Array(all.suffix(engine.blockSize * 50)) + let avg: Double = tail.reduce(0.0, +) / Double(tail.count) + #expect(abs(avg - level) < 0.01) + } + + @Test func zeroDelayNormalizesDownExactly() { + // dur == 0 fast path: releaseCoeff == 0, attackComp == 1 → gain reaches + // level/|x| within one sample. DC 2.0 at level 1.0 → every output == 1.0. + let dc: ConstantGeneratorInput = ConstantGeneratorInput(2.0) + let norm: Normalizer = Normalizer(in: dc, level: 1.0, dur: 0.0, sampleRate: sr) + let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 2) + #expect(samples.allSatisfy { abs($0 - 1.0) < 1e-12 }) + } + + @Test func zeroDelayScalesUpExactly() { + // dur == 0 fast path scaling up: DC 0.25 at level 1.0 → gain 4, output 1.0. + let dc: ConstantGeneratorInput = ConstantGeneratorInput(0.25) + let norm: Normalizer = Normalizer(in: dc, level: 1.0, dur: 0.0, sampleRate: sr) + let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 2) + #expect(samples.allSatisfy { abs($0 - 1.0) < 1e-12 }) + } + + @Test func finiteWithNoise() { + let norm: Normalizer = Normalizer(in: WhiteNoise.Audio(mul: 0.4), + level: 0.9, dur: 0.005, sampleRate: sr) + let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 200) + #expect(samples.allSatisfy { $0.isFinite }) + // Peak should be bounded near level once settled. + let tail: [Double] = Array(samples.suffix(engine.blockSize * 100)) + #expect(peak(tail) < 0.9 + 0.01) + } +} diff --git a/Tests/LyrebirdTests/ExponentialLineTests.swift b/Tests/LyrebirdTests/Generators/Envelopes/ExponentialLineTests.swift similarity index 100% rename from Tests/LyrebirdTests/ExponentialLineTests.swift rename to Tests/LyrebirdTests/Generators/Envelopes/ExponentialLineTests.swift diff --git a/Tests/LyrebirdTests/LineTests.swift b/Tests/LyrebirdTests/Generators/Envelopes/LineTests.swift similarity index 100% rename from Tests/LyrebirdTests/LineTests.swift rename to Tests/LyrebirdTests/Generators/Envelopes/LineTests.swift diff --git a/Tests/LyrebirdTests/RateRampTests.swift b/Tests/LyrebirdTests/Generators/Envelopes/RateRampTests.swift similarity index 100% rename from Tests/LyrebirdTests/RateRampTests.swift rename to Tests/LyrebirdTests/Generators/Envelopes/RateRampTests.swift diff --git a/Tests/LyrebirdTests/ButterworthFilterTests.swift b/Tests/LyrebirdTests/Generators/Filters/ButterworthFilterTests.swift similarity index 100% rename from Tests/LyrebirdTests/ButterworthFilterTests.swift rename to Tests/LyrebirdTests/Generators/Filters/ButterworthFilterTests.swift diff --git a/Tests/LyrebirdTests/Decay2Tests.swift b/Tests/LyrebirdTests/Generators/Filters/Decay2Tests.swift similarity index 100% rename from Tests/LyrebirdTests/Decay2Tests.swift rename to Tests/LyrebirdTests/Generators/Filters/Decay2Tests.swift diff --git a/Tests/LyrebirdTests/DecayTests.swift b/Tests/LyrebirdTests/Generators/Filters/DecayTests.swift similarity index 100% rename from Tests/LyrebirdTests/DecayTests.swift rename to Tests/LyrebirdTests/Generators/Filters/DecayTests.swift diff --git a/Tests/LyrebirdTests/Generators/Filters/FormletAudioTests.swift b/Tests/LyrebirdTests/Generators/Filters/FormletAudioTests.swift new file mode 100644 index 0000000..357b8b9 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Filters/FormletAudioTests.swift @@ -0,0 +1,144 @@ +// FormletAudioTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - Local DFT helper + +private func dftMag(samples: [Double], freq: Double, sampleRate: Double) -> Double { + let n: Int = samples.count + guard n > 0 else { return 0 } + var re: Double = 0.0, im: Double = 0.0 + for i: Int in 0.. magAbove) + #expect(samples.allSatisfy { $0.isFinite }) + } + + @Test func longerDecayTimeDecaysSlower() throws { + let impulse1: Impulse.Audio = Impulse.Audio(freq: 1.0) + let f1: Formlet.Audio = Formlet.Audio(input: impulse1, freq: 440.0, + attackTime: 0.002, decayTime: 0.05) + let s1: [Double] = collectBlocks(f1, engine: engine, blocks: 40) + let rms1: Double = rmsValue(Array(s1.suffix(10 * engine.blockSize))) + + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let impulse2: Impulse.Audio = Impulse.Audio(freq: 1.0) + let f2: Formlet.Audio = Formlet.Audio(input: impulse2, freq: 440.0, + attackTime: 0.002, decayTime: 0.5) + let s2: [Double] = collectBlocks(f2, engine: engine2, blocks: 40) + let rms2: Double = rmsValue(Array(s2.suffix(10 * engine2.blockSize))) + + #expect(rms2 > rms1) + } + + @Test func dcInputDecaysFinite() { + let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0) + let formlet: Formlet.Audio = Formlet.Audio(input: dc, freq: 440.0, + attackTime: 0.005, decayTime: 0.1) + let samples: [Double] = collectBlocks(formlet, engine: engine, blocks: 50) + #expect(samples.allSatisfy { $0.isFinite }) + } + + @Test func audioRateFreqModNoCrash() { + let lfo: OscSin.Audio = OscSin.Audio(freq: 2.0) + let freqGen: BinaryOpGenerator = lfo * 200.0 + 440.0 + let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) + let formlet: Formlet.Audio = Formlet.Audio(input: impulse, freq: freqGen, + attackTime: 0.002, decayTime: 0.2) + let samples: [Double] = collectBlocks(formlet, engine: engine, blocks: 20) + #expect(samples.allSatisfy { $0.isFinite }) + } + + @Test func audioRateTimeModNoCrash() { + let lfoA: OscSin.Audio = OscSin.Audio(freq: 0.7) + let attackGen: BinaryOpGenerator = lfoA * 0.001 + 0.003 + let lfoD: OscSin.Audio = OscSin.Audio(freq: 0.5) + let decayGen: BinaryOpGenerator = lfoD * 0.1 + 0.2 + let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) + let formlet: Formlet.Audio = Formlet.Audio(input: impulse, freq: 440.0, + attackTime: attackGen, decayTime: decayGen) + let samples: [Double] = collectBlocks(formlet, engine: engine, blocks: 20) + #expect(samples.allSatisfy { $0.isFinite }) + } + + @Test func participatesInFanOutCache() { + let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) + let formlet: Formlet.Audio = Formlet.Audio(input: impulse, freq: 440.0, + attackTime: 0.002, decayTime: 0.2) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = formlet.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = formlet.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } + + @Test func denormalsDoNotAccumulate() { + let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) + let formlet: Formlet.Audio = Formlet.Audio(input: impulse, freq: 440.0, + attackTime: 0.001, decayTime: 0.01) + let samples: [Double] = collectBlocks(formlet, engine: engine, blocks: 200) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { !$0.isSubnormal }) + } + + @Test func deterministicFirstSampleMatchesFormula() { + // Step input, zero state: out[0] = (1−R_decay)·1 − (1−R_attack)·1 = R_attack − R_decay. + let attackTime: Double = 0.005 + let decayTime: Double = 0.2 + let log0001: Double = log(0.001) + let rDecay: Double = exp(log0001 / (decayTime * sr)) + let rAttack: Double = exp(log0001 / (attackTime * sr)) + let expectedFirstSample: Double = rAttack - rDecay + + let input: ConstantGeneratorInput = ConstantGeneratorInput(1.0) + let formlet: Formlet.Audio = Formlet.Audio(input: input, freq: 440.0, + attackTime: attackTime, decayTime: decayTime) + let g: SynthGraph = makeSynthGraph(engine: engine) + let samples: [[Double]] = formlet.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(samples[0][0] - expectedFirstSample) < 1e-10) + } + + @Test func equalAttackDecayCancelsToSilence() { + // attackTime == decayTime → the two Ringz are identical, difference is exactly zero. + let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0) + let formlet: Formlet.Audio = Formlet.Audio(input: dc, freq: 440.0, + attackTime: 0.1, decayTime: 0.1) + let samples: [Double] = collectBlocks(formlet, engine: engine, blocks: 10) + #expect(samples.allSatisfy { abs($0) < 1e-12 }) + } +} diff --git a/Tests/LyrebirdTests/Generators/Filters/FormletControlTests.swift b/Tests/LyrebirdTests/Generators/Filters/FormletControlTests.swift new file mode 100644 index 0000000..e168d9a --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Filters/FormletControlTests.swift @@ -0,0 +1,53 @@ +// FormletControlTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - FormletControlTests + +@MainActor +@Suite("Formlet.Control") +struct FormletControlTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func finiteOutput() { + let trig: Impulse.Control = Impulse.Control(freq: 4.0) + let formlet: Formlet.Control = Formlet.Control(input: trig, freq: 60.0, + attackTime: 0.01, decayTime: 0.3) + let samples: [Double] = collectBlocks(formlet, engine: engine, blocks: 40) + #expect(samples.allSatisfy { $0.isFinite }) + } + + @Test func deterministicFirstBlockMatchesFormula() { + // Control rate: resonators step once per block at sampleRate/blockSize. + // out = (1−R_decay)·x − (1−R_attack)·x = (R_attack − R_decay)·x, x=1, zero state. + let attackTime: Double = 0.05 + let decayTime: Double = 0.5 + let controlRate: Double = sr / Double(engine.blockSize) + let log0001: Double = log(0.001) + let rDecay: Double = exp(log0001 / (decayTime * controlRate)) + let rAttack: Double = exp(log0001 / (attackTime * controlRate)) + let expected: Double = rAttack - rDecay + + let input: ConstantGeneratorInput = ConstantGeneratorInput(1.0) + let formlet: Formlet.Control = Formlet.Control(input: input, freq: 50.0, + attackTime: attackTime, decayTime: decayTime) + let g: SynthGraph = makeSynthGraph(engine: engine) + let samples: [[Double]] = formlet.calculatedSamples(graph: g, count: engine.blockSize) + // Constant fill across the block. + #expect(abs(samples[0][0] - expected) < 1e-10) + #expect(abs(samples[0][engine.blockSize - 1] - expected) < 1e-10) + } +} diff --git a/Tests/LyrebirdTests/HilbertTests.swift b/Tests/LyrebirdTests/Generators/Filters/HilbertTests.swift similarity index 100% rename from Tests/LyrebirdTests/HilbertTests.swift rename to Tests/LyrebirdTests/Generators/Filters/HilbertTests.swift diff --git a/Tests/LyrebirdTests/Generators/Filters/KlankTests.swift b/Tests/LyrebirdTests/Generators/Filters/KlankTests.swift new file mode 100644 index 0000000..a301986 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Filters/KlankTests.swift @@ -0,0 +1,164 @@ +// KlankTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - Local DFT helper + +private func dftMag(samples: [Double], freq: Double, sampleRate: Double) -> Double { + let n: Int = samples.count + guard n > 0 else { return 0 } + var re: Double = 0.0 + var im: Double = 0.0 + for i: Int in 0.. LyrebirdBuffer { + let buf: LyrebirdBuffer = LyrebirdBuffer(count: triplets.count, channelCount: klankSpecChannelCount) + for (i, t) in triplets.enumerated() { + buf.setValue(t.0, frame: i, channel: klankFreqChannel) + buf.setValue(t.1, frame: i, channel: klankAmpChannel) + buf.setValue(t.2, frame: i, channel: klankDecayChannel) + } + return buf +} + +@MainActor +@Suite("Klank") +struct KlankTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func dftPeaksAtAllModes() { + let spec: LyrebirdBuffer = makeSpec([ + (440.0, 1.0, 0.5), + (1320.0, 1.0, 0.5), + ]) + let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) + let voice: Klank.Audio = Klank.Audio(input: impulse, buffer: spec) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 200) + let tail: [Double] = Array(samples.suffix(100 * engine.blockSize)) + + let mag440: Double = dftMag(samples: tail, freq: 440, sampleRate: sr) + let mag1320: Double = dftMag(samples: tail, freq: 1320, sampleRate: sr) + let mag200: Double = dftMag(samples: tail, freq: 200, sampleRate: sr) + let mag800: Double = dftMag(samples: tail, freq: 800, sampleRate: sr) + + #expect(mag440 > mag200) + #expect(mag440 > mag800) + #expect(mag1320 > mag200) + #expect(mag1320 > mag800) + #expect(samples.allSatisfy { $0.isFinite }) + } + + @Test func freqscaleShiftsAllModesUp() { + // With freqscale 2.0 the energy should move from 440 to 880 Hz. + let spec: LyrebirdBuffer = makeSpec([(440.0, 1.0, 0.5)]) + let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) + let voice: Klank.Audio = Klank.Audio(input: impulse, buffer: spec, freqscale: 2.0) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 200) + let tail: [Double] = Array(samples.suffix(100 * engine.blockSize)) + + let mag440: Double = dftMag(samples: tail, freq: 440, sampleRate: sr) + let mag880: Double = dftMag(samples: tail, freq: 880, sampleRate: sr) + #expect(mag880 > mag440) + #expect(samples.allSatisfy { $0.isFinite }) + } + + @Test func freqoffsetShiftsMode() { + // 200 Hz mode + 600 Hz offset → resonance at 800 Hz. + let spec: LyrebirdBuffer = makeSpec([(200.0, 1.0, 0.5)]) + let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) + let voice: Klank.Audio = Klank.Audio(input: impulse, buffer: spec, freqoffset: 600.0) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 200) + let tail: [Double] = Array(samples.suffix(100 * engine.blockSize)) + + let mag200: Double = dftMag(samples: tail, freq: 200, sampleRate: sr) + let mag800: Double = dftMag(samples: tail, freq: 800, sampleRate: sr) + #expect(mag800 > mag200) + } + + @Test func decayscaleLengthensRing() { + // Same spec, two decayscale values: the longer ring keeps more late energy. + let triplet: [(Double, Double, Double)] = [(440.0, 1.0, 0.3)] + let shortVoice: Klank.Audio = Klank.Audio( + input: Impulse.Audio(freq: 0.0), buffer: makeSpec(triplet), decayscale: 0.3) + let longVoice: Klank.Audio = Klank.Audio( + input: Impulse.Audio(freq: 0.0), buffer: makeSpec(triplet), decayscale: 3.0) + + // Each voice is a fresh instance; collectBlocks evaluates them independently + // (its own Impulse(freq: 0) fires at that voice's first-block sample 0). + let shortSamples: [Double] = collectBlocks(shortVoice, engine: engine, blocks: 120) + let longSamples: [Double] = collectBlocks(longVoice, engine: engine, blocks: 120) + + // Compare energy in the late window (after the impulse fires at sample 0). + let lateWindow: Int = 80 * engine.blockSize + let shortLate: Double = rmsValue(Array(shortSamples.suffix(shortSamples.count - lateWindow))) + let longLate: Double = rmsValue(Array(longSamples.suffix(longSamples.count - lateWindow))) + #expect(longLate > shortLate) + } + + @Test func setBufferNilSilencesBank() { + let spec: LyrebirdBuffer = makeSpec([(440.0, 1.0, 0.5)]) + let voice: Klank.Audio = Klank.Audio(input: Impulse.Audio(freq: 200.0), buffer: spec) + _ = collectBlocks(voice, engine: engine, blocks: 4) + voice.setBuffer(nil, engine: engine) + let after: [Double] = collectBlocks(voice, engine: engine, blocks: 20) + // Filter state rings briefly, then with no spec the bank produces silence. + let tail: [Double] = Array(after.suffix(8 * engine.blockSize)) + #expect(rmsValue(tail) < 1e-6) + } + + @Test func mulScalesOutput() { + let spec: LyrebirdBuffer = makeSpec([(440.0, 1.0, 0.5)]) + let plain: Klank.Audio = Klank.Audio(input: Impulse.Audio(freq: 0.0), buffer: makeSpec([(440.0, 1.0, 0.5)])) + let scaled: Klank.Audio = Klank.Audio(input: Impulse.Audio(freq: 0.0), buffer: spec, mul: 0.5) + let p: [Double] = collectBlocks(plain, engine: engine, blocks: 40) + let s: [Double] = collectBlocks(scaled, engine: engine, blocks: 40) + #expect(abs(rmsValue(s) - 0.5 * rmsValue(p)) < 1e-9 + 1e-3 * rmsValue(p)) + #expect(s.allSatisfy { $0.isFinite }) + } + + @Test func finiteAndStable() { + let spec: LyrebirdBuffer = makeSpec([ + (110.0, 1.0, 2.0), + (220.0, 0.5, 1.0), + (330.0, 0.25, 0.5), + ]) + let voice: Klank.Audio = Klank.Audio(input: WhiteNoise.Audio(mul: 0.1), buffer: spec) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 100) + #expect(samples.allSatisfy { $0.isFinite }) + } + + @Test func deterministicFirstSampleMatchesRingzFormula() { + // With a DC-1 input and zeroed filter state, the first output sample of a + // single resonator equals b0 = (1 − R)·amp, R = exp(log(0.001)/(decay·sr)). + let freq: Double = 440.0 + let amp: Double = 0.8 + let decay: Double = 0.5 + let spec: LyrebirdBuffer = makeSpec([(freq, amp, decay)]) + let voice: Klank.Audio = Klank.Audio(input: 1.0, buffer: spec) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 1) + let r: Double = exp(log(0.001) / (decay * sr)) + let expected: Double = (1.0 - r) * amp + #expect(abs(samples[0] - expected) < 1e-10) + } +} + diff --git a/Tests/LyrebirdTests/Lag2Tests.swift b/Tests/LyrebirdTests/Generators/Filters/Lag2Tests.swift similarity index 100% rename from Tests/LyrebirdTests/Lag2Tests.swift rename to Tests/LyrebirdTests/Generators/Filters/Lag2Tests.swift diff --git a/Tests/LyrebirdTests/Lag2UpDownTests.swift b/Tests/LyrebirdTests/Generators/Filters/Lag2UpDownTests.swift similarity index 100% rename from Tests/LyrebirdTests/Lag2UpDownTests.swift rename to Tests/LyrebirdTests/Generators/Filters/Lag2UpDownTests.swift diff --git a/Tests/LyrebirdTests/LagTests.swift b/Tests/LyrebirdTests/Generators/Filters/LagTests.swift similarity index 100% rename from Tests/LyrebirdTests/LagTests.swift rename to Tests/LyrebirdTests/Generators/Filters/LagTests.swift diff --git a/Tests/LyrebirdTests/LagUpDownTests.swift b/Tests/LyrebirdTests/Generators/Filters/LagUpDownTests.swift similarity index 100% rename from Tests/LyrebirdTests/LagUpDownTests.swift rename to Tests/LyrebirdTests/Generators/Filters/LagUpDownTests.swift diff --git a/Tests/LyrebirdTests/LeakDCTests.swift b/Tests/LyrebirdTests/Generators/Filters/LeakDCTests.swift similarity index 100% rename from Tests/LyrebirdTests/LeakDCTests.swift rename to Tests/LyrebirdTests/Generators/Filters/LeakDCTests.swift diff --git a/Tests/LyrebirdTests/MoogLadderTests.swift b/Tests/LyrebirdTests/Generators/Filters/MoogLadderTests.swift similarity index 100% rename from Tests/LyrebirdTests/MoogLadderTests.swift rename to Tests/LyrebirdTests/Generators/Filters/MoogLadderTests.swift diff --git a/Tests/LyrebirdTests/MuTronIIITests.swift b/Tests/LyrebirdTests/Generators/Filters/MuTronIIITests.swift similarity index 100% rename from Tests/LyrebirdTests/MuTronIIITests.swift rename to Tests/LyrebirdTests/Generators/Filters/MuTronIIITests.swift diff --git a/Tests/LyrebirdTests/RBJFilterTests.swift b/Tests/LyrebirdTests/Generators/Filters/RBJFilterTests.swift similarity index 100% rename from Tests/LyrebirdTests/RBJFilterTests.swift rename to Tests/LyrebirdTests/Generators/Filters/RBJFilterTests.swift diff --git a/Tests/LyrebirdTests/ResonatingFilterTests.swift b/Tests/LyrebirdTests/Generators/Filters/ResonatingFilterTests.swift similarity index 100% rename from Tests/LyrebirdTests/ResonatingFilterTests.swift rename to Tests/LyrebirdTests/Generators/Filters/ResonatingFilterTests.swift diff --git a/Tests/LyrebirdTests/ResonatorBankTests.swift b/Tests/LyrebirdTests/Generators/Filters/ResonatorBankTests.swift similarity index 100% rename from Tests/LyrebirdTests/ResonatorBankTests.swift rename to Tests/LyrebirdTests/Generators/Filters/ResonatorBankTests.swift diff --git a/Tests/LyrebirdTests/SVFTests.swift b/Tests/LyrebirdTests/Generators/Filters/SVFTests.swift similarity index 100% rename from Tests/LyrebirdTests/SVFTests.swift rename to Tests/LyrebirdTests/Generators/Filters/SVFTests.swift diff --git a/Tests/LyrebirdTests/Generators/Filters/SlewAudioTests.swift b/Tests/LyrebirdTests/Generators/Filters/SlewAudioTests.swift new file mode 100644 index 0000000..a0c3f6f --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Filters/SlewAudioTests.swift @@ -0,0 +1,180 @@ +// SlewAudioTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +@MainActor +@Suite("Slew.Audio") +struct SlewAudioTests { + + let engine: SynthesisEngine + var graph: SynthGraph { makeSynthGraph(engine: engine) } + let blockSize: Int = 64 + let sampleRate: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func rateIsAudio() { + let gen: Slew.Audio = Slew.Audio(input: 0.0) + #expect(gen.rate == .audio) + } + + /// Output count correct. + @Test func outputCountMatchesRequest() { + let gen: Slew.Audio = Slew.Audio(input: 0.5) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(Array(out[0].prefix(blockSize)).count == blockSize) + } + + /// First sample initializes to the first input value (no slew on sample 0). + @Test func firstSampleInitializesToInput() { + let inputVal: Double = 0.8 + let gen: Slew.Audio = Slew.Audio(input: inputVal, up: 0.001, dn: 0.001) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(abs(out[0][0] - inputVal) < 1e-12, + "sample 0 should equal first input \(inputVal), got \(out[0][0])") + } + + /// Step up clamped to up/sr per sample: input 0→1 with up=sr reaches 1.0 in one sample. + @Test func stepUpClampedToUpPerSampleReachesTargetInOneSample() { + // up = sampleRate → upStep = sampleRate / sampleRate = 1.0 per sample. + // Input goes to 1.0 at sample 1, state starts at 0.0 (init'd to sample 0 = 0). + // At sample 1: x=1.0, state=0.0+1.0=1.0 (exactly). + let upRate: Double = sampleRate + let inputSignal: Closure = Closure { _, i in i == 0 ? 0.0 : 1.0 } + let gen: Slew.Audio = Slew.Audio(input: inputSignal, up: upRate, dn: 0.001) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + // Sample 0: initialized to 0.0. + #expect(abs(out[0][0] - 0.0) < 1e-12) + // Sample 1: x=1.0, upStep=1.0 → state reaches 1.0 in one step. + #expect(abs(out[0][1] - 1.0) < 1e-12, + "with up=sampleRate, should reach 1.0 in one step, got \(out[0][1])") + // Samples 2+: stays at 1.0 (input stays at 1.0). + for i: Int in 2.. Double { + let n: Int = samples.count + guard n > 0 else { return 0 } + var re: Double = 0.0 + var im: Double = 0.0 + for i: Int in 0.. LyrebirdBuffer { + let buf: LyrebirdBuffer = LyrebirdBuffer(count: triplets.count, channelCount: klangSpecChannelCount) + for (i, t) in triplets.enumerated() { + buf.setValue(t.0, frame: i, channel: klangFreqChannel) + buf.setValue(t.1, frame: i, channel: klangAmpChannel) + buf.setValue(t.2, frame: i, channel: klangPhaseChannel) + } + return buf +} + +@MainActor +@Suite("Klang") +struct KlangTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func dftPeaksAtAllPartials() { + let spec: LyrebirdBuffer = makeSpec([ + (300.0, 1.0, 0.0), + (900.0, 0.7, 0.0), + ]) + let voice: Klang.Audio = Klang.Audio(buffer: spec) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 200) + + let mag300: Double = dftMag(samples: samples, freq: 300, sampleRate: sr) + let mag900: Double = dftMag(samples: samples, freq: 900, sampleRate: sr) + let mag600: Double = dftMag(samples: samples, freq: 600, sampleRate: sr) + #expect(mag300 > mag600) + #expect(mag900 > mag600) + #expect(samples.allSatisfy { $0.isFinite }) + } + + @Test func ampWeightsPartials() { + // Louder partial at 300 should have larger DFT magnitude than the quiet 900. + let spec: LyrebirdBuffer = makeSpec([ + (300.0, 1.0, 0.0), + (900.0, 0.1, 0.0), + ]) + let voice: Klang.Audio = Klang.Audio(buffer: spec) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 200) + let mag300: Double = dftMag(samples: samples, freq: 300, sampleRate: sr) + let mag900: Double = dftMag(samples: samples, freq: 900, sampleRate: sr) + #expect(mag300 > mag900 * 2.0) + } + + @Test func freqscaleShiftsPartial() { + let spec: LyrebirdBuffer = makeSpec([(300.0, 1.0, 0.0)]) + let voice: Klang.Audio = Klang.Audio(buffer: spec, freqscale: 2.0) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 200) + let mag300: Double = dftMag(samples: samples, freq: 300, sampleRate: sr) + let mag600: Double = dftMag(samples: samples, freq: 600, sampleRate: sr) + #expect(mag600 > mag300) + } + + @Test func freqoffsetShiftsPartial() { + let spec: LyrebirdBuffer = makeSpec([(300.0, 1.0, 0.0)]) + let voice: Klang.Audio = Klang.Audio(buffer: spec, freqoffset: 200.0) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 200) + let mag300: Double = dftMag(samples: samples, freq: 300, sampleRate: sr) + let mag500: Double = dftMag(samples: samples, freq: 500, sampleRate: sr) + #expect(mag500 > mag300) + } + + @Test func singlePartialApproximatesSine() { + // One partial, amp 1 → output amplitude should be near 1.0 RMS·√2. + let spec: LyrebirdBuffer = makeSpec([(440.0, 1.0, 0.0)]) + let voice: Klang.Audio = Klang.Audio(buffer: spec) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 100) + let peak: Double = samples.map { abs($0) }.max() ?? 0 + #expect(peak > 0.98) + #expect(peak < 1.02) + } + + @Test func initialPhaseAffectsFirstSample() { + // Quarter-cycle phase offset → first sample near sin(2π·0.25) = 1.0. + let spec: LyrebirdBuffer = makeSpec([(100.0, 1.0, 0.25)]) + let voice: Klang.Audio = Klang.Audio(buffer: spec, interpolation: .none) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 1) + #expect(abs(samples[0] - 1.0) < 0.05) + } + + @Test func setBufferNilSilences() { + let spec: LyrebirdBuffer = makeSpec([(300.0, 1.0, 0.0)]) + let voice: Klang.Audio = Klang.Audio(buffer: spec) + _ = collectBlocks(voice, engine: engine, blocks: 2) + voice.setBuffer(nil, engine: engine) + let after: [Double] = collectBlocks(voice, engine: engine, blocks: 10) + #expect(rmsValue(after) < 1e-9) + } + + @Test func setBufferRetunesBank() { + let spec: LyrebirdBuffer = makeSpec([(300.0, 1.0, 0.0)]) + let voice: Klang.Audio = Klang.Audio(buffer: spec) + _ = collectBlocks(voice, engine: engine, blocks: 2) + let newSpec: LyrebirdBuffer = makeSpec([(700.0, 1.0, 0.0)]) + voice.setBuffer(newSpec, engine: engine) + let after: [Double] = collectBlocks(voice, engine: engine, blocks: 200) + let mag300: Double = dftMag(samples: after, freq: 300, sampleRate: sr) + let mag700: Double = dftMag(samples: after, freq: 700, sampleRate: sr) + #expect(mag700 > mag300) + } + + @Test func mulScalesOutput() { + let spec: LyrebirdBuffer = makeSpec([(440.0, 1.0, 0.0)]) + let plain: Klang.Audio = Klang.Audio(buffer: makeSpec([(440.0, 1.0, 0.0)])) + let scaled: Klang.Audio = Klang.Audio(buffer: spec, mul: 0.5) + let p: [Double] = collectBlocks(plain, engine: engine, blocks: 40) + let s: [Double] = collectBlocks(scaled, engine: engine, blocks: 40) + #expect(abs(rmsValue(s) - 0.5 * rmsValue(p)) < 1e-9 + 1e-3 * rmsValue(p)) + #expect(s.allSatisfy { $0.isFinite }) + } + + @Test func deterministicFirstSampleMatchesTableLookup() { + // Single partial, .none interpolation, initial phase 0.25 cycle. The phase + // accumulator seeds at table index tableSize/4 (a power-of-two table makes this + // exact), where the sine table holds sin(π/2) = 1.0. So sample 0 = amp · 1.0. + let amp: Double = 0.7 + let spec: LyrebirdBuffer = makeSpec([(100.0, amp, 0.25)]) + let voice: Klang.Audio = Klang.Audio(buffer: spec, interpolation: .none) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 1) + #expect(abs(samples[0] - amp) < 1e-9) + } + + @Test func phaseZeroFirstSampleIsZero() { + // sin(0) = 0 → a single partial starting at phase 0 emits 0 on sample 0. + let spec: LyrebirdBuffer = makeSpec([(440.0, 1.0, 0.0)]) + let voice: Klang.Audio = Klang.Audio(buffer: spec, interpolation: .none) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 1) + #expect(abs(samples[0]) < 1e-12) + } + + @Test func finiteWithManyPartials() { + var triplets: [(Double, Double, Double)] = [] + for h: Int in 1...16 { + triplets.append((110.0 * Double(h), 1.0 / Double(h), 0.0)) + } + let voice: Klang.Audio = Klang.Audio(buffer: makeSpec(triplets), mul: 0.1) + let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 100) + #expect(samples.allSatisfy { $0.isFinite }) + } +} diff --git a/Tests/LyrebirdTests/LFDutyCycleTests.swift b/Tests/LyrebirdTests/Generators/Oscillators/LFDutyCycleTests.swift similarity index 100% rename from Tests/LyrebirdTests/LFDutyCycleTests.swift rename to Tests/LyrebirdTests/Generators/Oscillators/LFDutyCycleTests.swift diff --git a/Tests/LyrebirdTests/Generators/Oscillators/LFGaussAudioTests.swift b/Tests/LyrebirdTests/Generators/Oscillators/LFGaussAudioTests.swift new file mode 100644 index 0000000..6bfe47e --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Oscillators/LFGaussAudioTests.swift @@ -0,0 +1,110 @@ +// LFGaussAudioTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - LFGaussAudioTests + +@MainActor +@Suite("LFGauss.Audio") +struct LFGaussAudioTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func outputWithinUnitRange() { + let gauss: LFGauss.Audio = LFGauss.Audio(period: 0.02, width: 0.15) + let samples: [Double] = collectBlocks(gauss, engine: engine, blocks: 50) + #expect(samples.allSatisfy { $0 > 0.0 && $0 <= 1.0 + 1e-12 }) + #expect(samples.allSatisfy { $0.isFinite }) + } + + @Test func peakReachesOneAtMidPeriod() { + // One full period long enough to land a sample near phase 0.5 (peak). + let gauss: LFGauss.Audio = LFGauss.Audio(period: 0.05, width: 0.2) + let samples: [Double] = collectBlocks(gauss, engine: engine, blocks: 40) + let maxVal: Double = samples.max() ?? 0 + #expect(maxVal > 0.999) + } + + @Test func narrowerWidthSpendsMoreTimeNearZero() throws { + let wide: LFGauss.Audio = LFGauss.Audio(period: 0.02, width: 0.4) + let sWide: [Double] = collectBlocks(wide, engine: engine, blocks: 60) + let meanWide: Double = sWide.reduce(0, +) / Double(sWide.count) + + let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) + try engine2.start() + let narrow: LFGauss.Audio = LFGauss.Audio(period: 0.02, width: 0.05) + let sNarrow: [Double] = collectBlocks(narrow, engine: engine2, blocks: 60) + let meanNarrow: Double = sNarrow.reduce(0, +) / Double(sNarrow.count) + + // Narrower bell → lower average level (more of the cycle near zero). + #expect(meanNarrow < meanWide) + } + + @Test func deterministicValueAtPeakPhase() { + // phase 0.5 → x = 0 → exp(0) = 1.0 on the first sample. + let gauss: LFGauss.Audio = LFGauss.Audio(period: 0.1, width: 0.2, phase: 0.5) + let g: SynthGraph = makeSynthGraph(engine: engine) + let samples: [[Double]] = gauss.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(samples[0][0] - 1.0) < 1e-12) + } + + @Test func deterministicValueAtTroughPhase() { + // phase 0 → x = -1 → exp(-0.5 · (1/width)²). + let width: Double = 0.2 + let a: Double = -1.0 / width + let expected: Double = exp(-0.5 * a * a) + let gauss: LFGauss.Audio = LFGauss.Audio(period: 0.1, width: width, phase: 0.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let samples: [[Double]] = gauss.calculatedSamples(graph: g, count: engine.blockSize) + #expect(abs(samples[0][0] - expected) < 1e-12) + } + + @Test func audioRatePeriodModNoCrash() { + let lfo: OscSin.Audio = OscSin.Audio(freq: 3.0) + let periodGen: BinaryOpGenerator = lfo * 0.005 + 0.02 // sweeps 15–25 ms + let gauss: LFGauss.Audio = LFGauss.Audio(period: periodGen, width: 0.2) + let samples: [Double] = collectBlocks(gauss, engine: engine, blocks: 20) + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { $0 > 0.0 && $0 <= 1.0 + 1e-12 }) + } + + @Test func audioRateWidthModNoCrash() { + let lfo: OscSin.Audio = OscSin.Audio(freq: 0.5) + let widthGen: BinaryOpGenerator = lfo * 0.1 + 0.2 + let gauss: LFGauss.Audio = LFGauss.Audio(period: 0.02, width: widthGen) + let samples: [Double] = collectBlocks(gauss, engine: engine, blocks: 20) + #expect(samples.allSatisfy { $0.isFinite }) + } + + @Test func participatesInFanOutCache() { + let gauss: LFGauss.Audio = LFGauss.Audio(period: 0.02, width: 0.2) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = gauss.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = gauss.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } + + @Test func mulAddScalesAndOffsets() { + let plain: LFGauss.Audio = LFGauss.Audio(period: 0.05, width: 0.2, phase: 0.5) + let g1: SynthGraph = makeSynthGraph(engine: engine) + let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0] + + let scaled: LFGauss.Audio = LFGauss.Audio(period: 0.05, width: 0.2, phase: 0.5, + mul: 2.0, add: 1.0) + let g2: SynthGraph = makeSynthGraph(engine: engine) + let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0] + #expect(abs(s - (p * 2.0 + 1.0)) < 1e-12) + } +} diff --git a/Tests/LyrebirdTests/Generators/Oscillators/LFGaussControlTests.swift b/Tests/LyrebirdTests/Generators/Oscillators/LFGaussControlTests.swift new file mode 100644 index 0000000..0cb97ee --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Oscillators/LFGaussControlTests.swift @@ -0,0 +1,56 @@ +// LFGaussControlTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - LFGaussControlTests + +@MainActor +@Suite("LFGauss.Control") +struct LFGaussControlTests { + + let engine: SynthesisEngine + let sr: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func outputWithinUnitRange() { + let gauss: LFGauss.Control = LFGauss.Control(period: 0.05, width: 0.2) + let samples: [Double] = collectBlocks(gauss, engine: engine, blocks: 60) + // Linear ramp between bell values stays bounded in [0, 1]. + #expect(samples.allSatisfy { $0.isFinite }) + #expect(samples.allSatisfy { $0 >= -1e-12 && $0 <= 1.0 + 1e-12 }) + } + + @Test func lastSampleMatchesBellValueAtAdvancedPhase() { + // First block: phase advances by dt·count from 0; ramp end == bell value at new phase. + let period: Double = 0.05 + let width: Double = 0.2 + let gauss: LFGauss.Control = LFGauss.Control(period: period, width: width, phase: 0.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let samples: [[Double]] = gauss.calculatedSamples(graph: g, count: engine.blockSize) + + let dt: Double = 1.0 / (period * sr) + let advancedPhase: Double = dt * Double(engine.blockSize) + let x: Double = 2.0 * advancedPhase - 1.0 + let aTerm: Double = x / width + let expected: Double = exp(-0.5 * aTerm * aTerm) + #expect(abs(samples[0][engine.blockSize - 1] - expected) < 1e-10) + } + + @Test func participatesInFanOutCache() { + let gauss: LFGauss.Control = LFGauss.Control(period: 0.05, width: 0.2) + let g: SynthGraph = makeSynthGraph(engine: engine) + let r1: [[Double]] = gauss.calculatedSamples(graph: g, count: engine.blockSize) + let r2: [[Double]] = gauss.calculatedSamples(graph: g, count: engine.blockSize) + #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) + } +} diff --git a/Tests/LyrebirdTests/LFSawtoothTests.swift b/Tests/LyrebirdTests/Generators/Oscillators/LFSawtoothTests.swift similarity index 100% rename from Tests/LyrebirdTests/LFSawtoothTests.swift rename to Tests/LyrebirdTests/Generators/Oscillators/LFSawtoothTests.swift diff --git a/Tests/LyrebirdTests/LFSquareTests.swift b/Tests/LyrebirdTests/Generators/Oscillators/LFSquareTests.swift similarity index 100% rename from Tests/LyrebirdTests/LFSquareTests.swift rename to Tests/LyrebirdTests/Generators/Oscillators/LFSquareTests.swift diff --git a/Tests/LyrebirdTests/LFTriangleTests.swift b/Tests/LyrebirdTests/Generators/Oscillators/LFTriangleTests.swift similarity index 100% rename from Tests/LyrebirdTests/LFTriangleTests.swift rename to Tests/LyrebirdTests/Generators/Oscillators/LFTriangleTests.swift diff --git a/Tests/LyrebirdTests/OscDutyCycleTests.swift b/Tests/LyrebirdTests/Generators/Oscillators/OscDutyCycleTests.swift similarity index 100% rename from Tests/LyrebirdTests/OscDutyCycleTests.swift rename to Tests/LyrebirdTests/Generators/Oscillators/OscDutyCycleTests.swift diff --git a/Tests/LyrebirdTests/OscSawtoothTests.swift b/Tests/LyrebirdTests/Generators/Oscillators/OscSawtoothTests.swift similarity index 100% rename from Tests/LyrebirdTests/OscSawtoothTests.swift rename to Tests/LyrebirdTests/Generators/Oscillators/OscSawtoothTests.swift diff --git a/Tests/LyrebirdTests/OscSquareTests.swift b/Tests/LyrebirdTests/Generators/Oscillators/OscSquareTests.swift similarity index 100% rename from Tests/LyrebirdTests/OscSquareTests.swift rename to Tests/LyrebirdTests/Generators/Oscillators/OscSquareTests.swift diff --git a/Tests/LyrebirdTests/OscTableTests.swift b/Tests/LyrebirdTests/Generators/Oscillators/OscTableTests.swift similarity index 100% rename from Tests/LyrebirdTests/OscTableTests.swift rename to Tests/LyrebirdTests/Generators/Oscillators/OscTableTests.swift diff --git a/Tests/LyrebirdTests/OscTriangleTests.swift b/Tests/LyrebirdTests/Generators/Oscillators/OscTriangleTests.swift similarity index 100% rename from Tests/LyrebirdTests/OscTriangleTests.swift rename to Tests/LyrebirdTests/Generators/Oscillators/OscTriangleTests.swift diff --git a/Tests/LyrebirdTests/Generators/Oscillators/PhasorAudioTests.swift b/Tests/LyrebirdTests/Generators/Oscillators/PhasorAudioTests.swift new file mode 100644 index 0000000..e68444b --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Oscillators/PhasorAudioTests.swift @@ -0,0 +1,203 @@ +// PhasorAudioTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +@MainActor +@Suite("Phasor.Audio") +struct PhasorAudioTests { + + let engine: SynthesisEngine + var graph: SynthGraph { makeSynthGraph(engine: engine) } + let blockSize: Int = 64 + let sampleRate: Double = 44100 + + init() throws { + engine = makeTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + } + + @Test func rateIsAudio() { + let gen: Phasor.Audio = Phasor.Audio() + #expect(gen.rate == .audio) + } + + /// Default range [0, 1), default rate 1.0/sample — output count correct. + @Test func outputCountMatchesRequest() { + let gen: Phasor.Audio = Phasor.Audio() + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(Array(out[0].prefix(blockSize)).count == blockSize) + } + + /// With no trigger, phase should start at `start` (0.0) and ramp by `rate` per sample. + @Test func defaultRampFromZero() { + // rate = 0.01 so 64 samples reaches 0.64 without wrapping. + let rate: Double = 0.01 + let gen: Phasor.Audio = Phasor.Audio(rate: rate) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0..0 at sample 32. + let trigInput: Closure = Closure { _, i in i < 32 ? 0.0 : 1.0 } + let gen: Phasor.Audio = Phasor.Audio(trig: trigInput, rate: rate, resetPos: resetPos) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + // Samples 0..31 ramp from 0 by 0.01 each step. + for i: Int in 0..<32 { + let expected: Double = Double(i) * rate + #expect(abs(out[0][i] - expected) < 1e-12, + "pre-trig sample \(i): expected \(expected) got \(out[0][i])") + } + // At sample 32 the trig fires → phase resets to resetPos before output. + #expect(abs(out[0][32] - resetPos) < 1e-12, + "trig sample 32: expected \(resetPos) got \(out[0][32])") + // Samples 33+ continue from resetPos + rate. + for i: Int in 33.. span wraps via truncatingRemainder without hanging. + @Test func largeRateWrapsWithoutHang() { + // rate = 5.0, span = 1.0 → wraps 5 times per sample; should still produce valid output. + let gen: Phasor.Audio = Phasor.Audio(rate: 5.0, start: 0.0, end: 1.0) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + // All samples should be in [0, 1). + for i: Int in 0..= 0.0, "sample \(i) below start: \(out[0][i])") + #expect(out[0][i] < 1.0, "sample \(i) at or above end: \(out[0][i])") + } + } + + /// Negative rate ramps down and wraps up at start. + @Test func negativeRateRampsDown() { + // Start at 0.5 (via trig), rate = -0.01. Phase decreases each sample and wraps at 0.0. + // Use a rate that is exactly representable in IEEE 754 to avoid FP-drift issues. + // 0.5 - k * 0.01 in IEEE 754 accumulates error; verify monotonic decrease and wrap behaviour + // rather than exact sample-level equality past the first few steps. + let rate: Double = -0.01 + let gen: Phasor.Audio = Phasor.Audio( + trig: Closure { _, i in i == 0 ? 1.0 : 0.0 }, + rate: rate, + start: 0.0, + end: 1.0, + resetPos: 0.5 + ) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + // Sample 0 = resetPos = 0.5 (trig fires at sample 0 resetting to 0.5). + #expect(abs(out[0][0] - 0.5) < 1e-12) + // Subsequent samples are strictly decreasing until a wrap occurs. + var foundWrap: Bool = false + for i: Int in 1.. out[0][i - 1] { + foundWrap = true + // After wrap, output should be in [0, 1). + #expect(out[0][i] >= 0.0 && out[0][i] < 1.0, + "wrapped sample \(i) out of range: \(out[0][i])") + break + } + // Before wrap: still in [0, 1) and decreasing. + #expect(out[0][i] >= 0.0 && out[0][i] < 0.5, + "pre-wrap sample \(i) should be in [0, 0.5): \(out[0][i])") + } + // A wrap must have occurred within 64 samples (0.5 / 0.01 = 50 steps). + #expect(foundWrap, "expected a wrap within \(blockSize) samples with rate=\(rate)") + } + + /// mul/add: with mul=2.0 add=1.0, output equals original*2+1. + @Test func mulAdd() { + let rate: Double = 0.01 + let genBase: Phasor.Audio = Phasor.Audio(rate: rate) + let genScaled: Phasor.Audio = Phasor.Audio(rate: rate, mul: 2.0, add: 1.0) + let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize) + let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0..= N clamps to N-1. + @Test func overflowWhichClampsToLast() { + let gen: Select.Audio = Select.Audio(which: 99.0, inputs: [0.1, 0.2, 0.3]) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0..= N clamps to N-1. + @Test func overflowWhichClampsToLast() { + let gen: Select.Control = Select.Control(which: 99.0, inputs: [0.1, 0.2, 0.3]) + _ = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(abs(gen.previousOutputValue - 0.3) < 1e-12, + "which=99 (clamp→2) target should be 0.3, got \(gen.previousOutputValue)") + } + + // MARK: - Ramp + + /// Last sample of first block equals the selected target. + @Test func rampsToTarget() { + let gen: Select.Control = Select.Control(which: 2, inputs: [0.1, 0.5, 0.9]) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + let lastSample: Double = out[0][blockSize - 1] + #expect(abs(lastSample - 0.9) < 1e-12, + "last sample of ramp should equal target 0.9, got \(lastSample)") + } + + // MARK: - mul/add + + @Test func mulAddApplied() { + // which=0, inputs[0]=0.5 → base target = 0.5 + // mul=2, add=1 → scaled target = 0.5*2+1 = 2.0 + let gen: Select.Control = Select.Control(which: 0, inputs: [0.5, 0.8], mul: 2.0, add: 1.0) + _ = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(abs(gen.previousOutputValue - 2.0) < 1e-12, + "mulAdd: expected 2.0, got \(gen.previousOutputValue)") + } + + // MARK: - Fan-out + + @Test func fanOutSameSegment() { + let gen: Select.Control = Select.Control(which: 1, inputs: [0.3, 0.7]) + let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0.. 0 fires only once (edge-only detection). + @Test func sustainedTrigFiresOnce() { + // Trig goes high at 10 and stays high. + let trig: Closure = Closure { _, i in i >= 10 ? 1.0 : 0.0 } + let gen: PulseCount.Audio = PulseCount.Audio(trig: trig) + let out: [Double] = gen.calculatedSamples(graph: graph, count: blockSize)[0] + for i: Int in 0..<10 { #expect(out[i] == 0.0) } + for i: Int in 10..= 10 { + // At sample 10 input = 0.1 < lo=0.2, state → 0. + if i == 10 { + #expect(out[i] == 0.0, + "sample \(i) after lo-cross expected 0.0 got \(out[i])") + } + } + } + for i: Int in 20.. hi=0.8 → state=1. At sample 0 state already 1. + // (state update then output, so sample 0 = mulAdd(1.0) = 3.0). + for i: Int in 0.. 0 (no falling edge) produces only one pulse. + @Test func sustainedTrigProducesOnePulse() { + let durSamples: Int = 8 + let dur: Double = Double(durSamples) / 44100.0 + // Input stays at 0.5 from sample 10 onwards (no falling edge → no second pulse). + let input: Closure = Closure { _, i in i >= 10 ? 0.5 : 0.0 } + let gen: Trig1.Audio = Trig1.Audio(input: input, dur: dur) + let out: [Double] = gen.calculatedSamples(graph: graph, count: blockSize)[0] + + // Pulse samples: 10..(10+durSamples-1) = 1.0. + for i: Int in 10..<(10 + durSamples) { + #expect(abs(out[i] - 1.0) < 1e-12, + "pulse sample \(i) expected 1.0 got \(out[i])") + } + // After pulse: 0 (trig still high but no new edge — no re-fire). + for i: Int in (10 + durSamples).. 0). + let gen: Trig1.Control = Trig1.Control(input: 0.3, dur: dur) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + let block: [Double] = Array(out[0].prefix(blockSize)) + // After trigger at sample 0, output is unity = 1.0 flat. + for i: Int in 0.. 0 (no falling edge) produces only one capture. + @Test func sustainedTrigProducesOneCapture() { + let durSamples: Int = 8 + let dur: Double = Double(durSamples) / 44100.0 + // Input goes from 0 to 0.10 at sample 10 and stays. + let input: Closure = Closure { _, i in i >= 10 ? 0.10 : 0.0 } + let gen: Trig.Audio = Trig.Audio(input: input, dur: dur) + let out: [Double] = gen.calculatedSamples(graph: graph, count: blockSize)[0] + + // Captured at i=10: level 0.10. + for i: Int in 10..<(10 + durSamples) { + #expect(abs(out[i] - 0.10) < 1e-12, + "sustained sample \(i) expected 0.10 got \(out[i])") + } + // After pulse ends, input still high but no new edge → output = 0. + for i: Int in (10 + durSamples).. 1 block: fire in block 1, still counting in block 2. + let durSamples: Int = 100 + let dur: Double = Double(durSamples) / 44100.0 + let firstSerial: UInt64 = engine.segmentSerial + // Input = 0.5 for sample 0 of block 1 only, 0 elsewhere. + let input: Closure = Closure { graph, i in + graph.engine.segmentSerial == firstSerial && i == 0 ? 0.5 : 0.0 + } + let gen: Trig.Audio = Trig.Audio(input: input, dur: dur) + _ = gen.calculatedSamples(graph: graph, count: blockSize) + advanceBlock(engine) + + // Block 2: 64 more samples consumed from the 100-sample countdown. + // We fired at sample 0 in block 1, consuming 64 of the 100 samples. + // In block 2 the remaining = 100 - 64 = 36 samples should still be high. + let out2: [Double] = gen.calculatedSamples(graph: graph, count: blockSize)[0] + for i: Int in 0..<36 { + #expect(abs(out2[i] - 0.5) < 1e-12, + "block-2 pulse sample \(i) expected 0.5 got \(out2[i])") + } + for i: Int in 36.. 0 for the full dur. Use constant 0.7 after edge. + let input2: Closure = Closure { _, _ in 0.7 } + let gen: Trig.Control = Trig.Control(input: input2, dur: dur) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + let block: [Double] = Array(out[0].prefix(blockSize)) + // After trigger fires at sample 0 (prevTrig=0, x=0.7), captured level = 0.7. + // All block samples should be 0.7. + for i: Int in 0.. 0: output just above the threshold is smaller than the hard-knee value (C1 ease-in). + @Test func smoothKneeIsLessThanHardKneeNearThreshold() { + // amp=0.5, smooth=1.0, x=0.55: over=0.05, kneeWidth=0.5. + // hard knee: out = 0.05 + // smooth ease-in: out = (0.05^2)/(2*0.5) = 0.0025/1.0 = 0.0025 + advanceBlock(engine) + let genHard: CrossoverDistortion.Audio = CrossoverDistortion.Audio(input: 0.55, amp: 0.5, smooth: 0.0) + let genSmooth: CrossoverDistortion.Audio = CrossoverDistortion.Audio(input: 0.55, amp: 0.5, smooth: 1.0) + let outHard: [[Double]] = genHard.calculatedSamples(graph: graph, count: blockSize) + advanceBlock(engine) + let outSmooth: [[Double]] = genSmooth.calculatedSamples(graph: graph, count: blockSize) + // Smooth output should be smaller than hard-knee output (ease-in starts slower). + #expect(outSmooth[0][0] < outHard[0][0], + "smooth should be less than hard at knee entry: smooth=\(outSmooth[0][0]) hard=\(outHard[0][0])") + // Both should be positive. + #expect(outSmooth[0][0] > 0.0, "smooth output should be positive above threshold") + // Verify exact value: over^2/(2*kneeWidth) = 0.05^2 / (2*0.5) = 0.0025 + #expect(abs(outSmooth[0][0] - 0.0025) < 1e-12, "smooth ease-in: expected 0.0025 got \(outSmooth[0][0])") + } + + /// mul/add: with mul=2.0 add=1.0, output is base×2+1. + @Test func mulAddScalesOutput() { + // Use amp=0 (passthrough) so base output = input. + let inputVal: Double = 0.4 + let genBase: CrossoverDistortion.Audio = CrossoverDistortion.Audio(input: inputVal, amp: 0.0) + let genScaled: CrossoverDistortion.Audio = CrossoverDistortion.Audio(input: inputVal, amp: 0.0, mul: 2.0, add: 1.0) + let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize) + let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0.. 0, "expected some disintegrated (zero) samples") + #expect(countInput > 0, "expected some passthrough samples") + } + + /// Determinism: same seed → identical output across two independent instances. + @Test func sameSeedException() { + let inputVal: Double = 0.5 + let gen1: Disintegrator.Audio = Disintegrator.Audio(input: inputVal, probability: 0.5, multiplier: 0.0, seed: 123) + let gen2: Disintegrator.Audio = Disintegrator.Audio(input: inputVal, probability: 0.5, multiplier: 0.0, seed: 123) + let out1: [[Double]] = gen1.calculatedSamples(graph: graph, count: blockSize) + advanceBlock(engine) + let out2: [[Double]] = gen2.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0.. LyrebirdBuffer { + let table: LyrebirdBuffer = LyrebirdBuffer(count: n) + table.fill { i, count in Double(i) / Double(count - 1) * 2.0 - 1.0 } + return table + } + + /// Inverting transfer curve: table maps x ∈ [-1,1] → -x. + func makeInvertingTable(n: Int = 1024) -> LyrebirdBuffer { + let table: LyrebirdBuffer = LyrebirdBuffer(count: n) + table.fill { i, count in -(Double(i) / Double(count - 1) * 2.0 - 1.0) } + return table + } + + /// Absolute-value transfer curve: table maps x ∈ [-1,1] → |x|. + func makeAbsTable(n: Int = 1024) -> LyrebirdBuffer { + let table: LyrebirdBuffer = LyrebirdBuffer(count: n) + table.fill { i, count in + let x: Double = Double(i) / Double(count - 1) * 2.0 - 1.0 + return abs(x) + } + return table + } + + @Test func rateIsAudio() { + let table: LyrebirdBuffer = makeIdentityTable() + let gen: Waveshaper.Audio = Waveshaper.Audio(table: table, input: 0.0) + #expect(gen.rate == .audio) + } + + @Test func outputCountMatchesRequest() { + let table: LyrebirdBuffer = makeIdentityTable() + let gen: Waveshaper.Audio = Waveshaper.Audio(table: table, input: 0.0) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(Array(out[0].prefix(blockSize)).count == blockSize) + } + + /// Identity table with constant input 0.3: output should ≈ 0.3 for all samples. + @Test func identityTableScalarInput() { + let tableSize: Int = 1024 + let table: LyrebirdBuffer = makeIdentityTable(n: tableSize) + let gen: Waveshaper.Audio = Waveshaper.Audio(table: table, input: 0.3) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0.. 1.0 is clamped to table[last] (saturation at +1.0). + @Test func inputAboveOneClampedToTableEnd() { + let tableSize: Int = 1024 + let table: LyrebirdBuffer = makeIdentityTable(n: tableSize) + let gen: Waveshaper.Audio = Waveshaper.Audio(table: table, input: 2.0) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0.. LyrebirdBuffer { + let table: LyrebirdBuffer = LyrebirdBuffer(count: n) + table.fill { i, count in Double(i) / Double(count - 1) * 2.0 - 1.0 } + return table + } + + @Test func rateIsControl() { + let table: LyrebirdBuffer = makeIdentityTable() + let gen: Waveshaper.Control = Waveshaper.Control(table: table, input: 0.0) + #expect(gen.rate == .control) + } + + @Test func outputCountMatchesRequest() { + let table: LyrebirdBuffer = makeIdentityTable() + let gen: Waveshaper.Control = Waveshaper.Control(table: table, input: 0.0) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(Array(out[0].prefix(blockSize)).count == blockSize) + } + + /// Identity table with constant input 0.5: ramp reaches ~0.5 by last sample. + @Test func identityTableConstantInput() { + let table: LyrebirdBuffer = makeIdentityTable() + let gen: Waveshaper.Control = Waveshaper.Control(table: table, input: 0.5) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + // Control ramp: last sample of first block equals target ≈ 0.5. + let lastSample: Double = out[0][blockSize - 1] + #expect(abs(lastSample - 0.5) < 1e-10, "ramp target: expected ~0.5 got \(lastSample)") + } + + /// floatValue returns previousOutputValue (the control-rate target). + @Test func floatValueReturnsPreviousOutputValue() { + let table: LyrebirdBuffer = makeIdentityTable() + let gen: Waveshaper.Control = Waveshaper.Control(table: table, input: 0.7) + // After first block, previousOutputValue should be ~0.7. + let _ = gen.calculatedSamples(graph: graph, count: blockSize) + #expect(abs(gen.floatValue(graph: graph) - 0.7) < 1e-10) + } + + /// Invalidated table produces silence (target = 0 → ramp toward 0). + @Test func invalidTableProduceSilence() { + let table: LyrebirdBuffer = makeIdentityTable() + let gen: Waveshaper.Control = Waveshaper.Control(table: table, input: 0.5) + table.invalidate() + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + // With invalid table target = 0; initial previousOutputValue = 0, so output is flat zero. + #expect(out[0][blockSize - 1] == 0.0) + } + + /// mul/add: with mul=2.0 add=1.0, ramp target is approximately original×2+1. + @Test func mulAddFoldsIntoTarget() { + let tableSize: Int = 1024 + let table: LyrebirdBuffer = makeIdentityTable(n: tableSize) + // identity table at 0.25 → waveshaper output ≈ 0.25; ×2 +1 = 1.5 + let gen: Waveshaper.Control = Waveshaper.Control(table: table, input: 0.25, mul: 2.0, add: 1.0) + let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + let lastSample: Double = out[0][blockSize - 1] + #expect(abs(lastSample - 1.5) < 1e-10, "mulAdd target: expected ~1.5 got \(lastSample)") + } + + /// Fan-out: two calculatedSamples calls on the same graph return identical first channel. + @Test func fanOut() { + let table: LyrebirdBuffer = makeIdentityTable() + let gen: Waveshaper.Control = Waveshaper.Control(table: table, input: 0.3) + let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) + for i: Int in 0.. **Clean-room note.** This is an independent implementation of standard +> autocorrelation-based tempo induction with phase locking (Davies & Plumbley, +> *Context-Dependent Beat Tracking of Musical Audio*, 2007; Ellis, *Beat +> Tracking by Dynamic Programming*, 2007). It is **not** a port of any +> SuperCollider `BeatTrack`/`BeatTrack2` source (which is GPL). Channel +> semantics, parameters, and the internal algorithm are Lyrebird's own; do not +> expect bit-exact parity with SC. + +## Outputs (4 rows) + +`BeatTrack.Control` is a 4-row `ControlGenerator` (`outputChannelCount == 4`): + +| Row | Meaning | Form | +|---|---|---| +| `0` | **beat** trigger | `1.0` for the block on which a beat fires, else `0.0` | +| `1` | **eighth** trigger | fires at 2× the beat rate | +| `2` | **sixteenth** trigger | fires at 4× the beat rate | +| `3` | **tempo** | current estimate in **BPM** (continuous, smoothed) | + +Access individual rows with the channel subscript (`tracker[0]` … `tracker[3]`) +exactly like any multi-row generator. `floatValue` / scalar reads return row 0 +(the beat trigger), per the `ControlGenerator` default. + +Triggers land on **block boundaries** (the analysis is decimated to a feature +rate — see below), so beat timing is quantised to the control block, not +sample-accurate. This is appropriate for a tempo follower driving sequencers, +LFО re-triggers, or visualisation; it is not a sample-accurate clock. + +## Algorithm + +### 1. Onset detection function (ODF) and decimation + +The raw per-block ODF value is reduced to a fixed **feature rate** so the +autocorrelation window stays bounded regardless of block size: + +- A **feature hop** `Hf = round(sampleRate / featureRateHz)` samples groups + consecutive audio blocks. `featureRateHz` defaults to **≈ 86 Hz** + (`beatTrackFeatureRateHz = 86.0`), matching the conventional 512-sample STFT + hop at 44.1 kHz. +- Within one feature hop the per-block ODF values are combined by **max** + (onset energy is impulsive; max preserves the peak regardless of where in the + hop it lands). When the accumulated sample count reaches `Hf`, one ODF + feature is emitted and the accumulator resets. +- **`.spectralFlux` mode**: the per-block ODF is the spectral flux + `sqrt(Σ_k (mag_k − prevMag_k)² / binCount)` read from the chain's + `spectralBuffer` (identical to `SpectralFlux`; flux is ≈0 on blocks where the + FFT frame has not advanced, so the per-hop max captures each new frame's + onset). +- **`.feature` mode**: the per-block ODF is the max of the input feature row over + the block (a scalar feature input yields a constant ODF, with no per-block + heap allocation). + +Each emitted feature is **half-wave rectified and adaptively whitened**: the +running mean of recent features is subtracted and negatives clamped to 0, so a +DC offset or slow drift in the ODF does not bias the autocorrelation. + +### 2. ODF history ring + +Emitted features are pushed into a pre-allocated power-of-two **ring buffer** +sized for `beatTrackMaxWindowSeconds` (default **6 s** → +`Lmax = ceil(6 · featureRateHz) ≈ 516` features, ring rounded up to 1024). The +ring is allocated at `init`; nothing resizes on the RT thread. + +### 3. Tempo induction (autocorrelation) + +Periodically (every `beatTrackAnalysisHopFeatures` features, default **note: a +small power of two so re-analysis cost amortises**; not every feature), the +windowed ODF history is autocorrelated over the lag range corresponding to the +tempo bounds: + +``` +lagMin = featureRateHz · 60 / maxBPM // maxBPM = beatTrackMaxBPM = 200 +lagMax = featureRateHz · 60 / minBPM // minBPM = beatTrackMinBPM = 60 +acf[lag] = Σ_n odf[n] · odf[n − lag] // over the analysis window +``` + +The ACF is multiplied by a **tempo-preference weight** — a log-Gaussian centred +on `beatTrackPreferredBPM` (default **120 BPM**, width ~0.9 octave) — to +resolve octave ambiguity (a strong pulse at 60 BPM and its harmonic at 120 BPM +both peak; the weight biases toward the perceptually preferred range). The lag +with maximum weighted ACF is the **beat period** `P` (feature samples). `P` is +exponentially smoothed across analyses (`beatTrackTempoSmoothing`) so the tempo +output and the phase rate do not jump. + +`tempoBPM = 60 · featureRateHz / P`, clamped to `[minBPM, maxBPM]`. + +### 4. Phase locking + +A continuous **phase accumulator** `φ ∈ [0, 1)` advances by `1/P` per feature. +At each re-analysis the phase is re-aligned by finding the offset `δ ∈ [0, P)` +that maximises the correlation of an impulse train of period `P` with the recent +ODF (equivalently: the recent ODF peak position modulo `P`), then setting `φ` +so the next integer crossing coincides with the predicted next beat. Between +analyses `φ` free-runs at the current tempo, so beats keep firing even through +gaps in the ODF (a held note, a rest). + +Triggers are emitted when `φ` crosses an integer (beat, row 0), a half +(eighth, row 1), or a quarter (sixteenth, row 2) during the feature just +processed. + +### 5. Steady state and edge cases + +- **Silence / zero ODF**: the ACF is ~0, no clear peak; tempo holds its last + estimate (or the default `preferredBPM` before any lock). Phase keeps + free-running so triggers continue at the held tempo. No NaN/Inf — the ACF + normalisation and `P` are guarded against divide-by-zero, and feature state is + denormal-flushed each block. +- **Before first lock**: tempo output is `beatTrackPreferredBPM`; beat triggers + free-run at that tempo. +- **Constant (DC) ODF**: whitening removes the offset → no spurious periodicity. + +## Constants (named, no magic numbers) + +| Constant | Default | Meaning | +|---|---|---| +| `beatTrackFeatureRateHz` | `86.0` | ODF decimation target rate (Hz) | +| `beatTrackMaxWindowSeconds` | `6.0` | ODF history length for autocorrelation | +| `beatTrackMinBPM` | `60.0` | slowest detectable tempo | +| `beatTrackMaxBPM` | `200.0` | fastest detectable tempo | +| `beatTrackPreferredBPM` | `120.0` | centre of the tempo-preference weight + pre-lock default | +| `beatTrackPreferenceWidthOctaves` | `0.9` | log-Gaussian width of the preference weight | +| `beatTrackTempoSmoothing` | `0.9` | one-pole smoothing of the beat period across analyses | +| `beatTrackAnalysisHopFeatures` | `8` | re-run tempo induction every N features | + +## Usage + +```swift +// FFT-fed (.spectralFlux): drop on any audio source. +let chain = SpectralChain.Audio(input: drums, fftSize: 1024, hopSize: 512, analyzeOnly: true) +let bt = BeatTrack.Control(analysis: chain) // == BeatTrack.Control(odf: .spectralFlux(analysis: chain)) +// bt[0] = beat trigger, bt[3] = tempo BPM + +// Feature-fed (.feature): supply your own detection function. +let flux = SpectralFlux.Control(analysis: chain) +let bt2 = BeatTrack.Control(feature: flux) // == BeatTrack.Control(odf: .feature(flux)) +``` + +## Parameters + +### `BeatTrack.Control` + +The designated init takes `odf: BeatTrackODF`; `analysis:` / `feature:` / +`spectral:` are convenience inits that build the corresponding case. + +| Param | Type | Default | Meaning | +|---|---|---|---| +| `odf` | `BeatTrackODF` | — | ODF source: `.spectralFlux(analysis:)` or `.feature(_:)` | +| `minBPM` | `Double` | `60.0` | tempo search lower bound | +| `maxBPM` | `Double` | `200.0` | tempo search upper bound | +| `preferredBPM` | `Double` | `120.0` | preference-weight centre + pre-lock default | +| `windowSeconds` | `Double` | `6.0` | ODF history length | + +Convenience inits: `BeatTrack.Control(analysis: SpectralChain.Audio, …)`, +`BeatTrack.Control(feature: any ValidGeneratorInput, …)`, and +`BeatTrack.Control(spectral: SpectralBuffer, …)` (buffer-only, for tests / +advanced use — no analysis auto-pull). + +`minBPM` / `maxBPM` / `preferredBPM` / `windowSeconds` are read **once at +`init`** (they size the ring and the lag range — not RT-mutable). Audio-input +driven, Control-rate output only; no `Audio` variant exists. + +## Implementation layout + +- `Generators/Analysis/BeatTrackerCore.swift` — shared, non-`Generator` class + holding the ODF ring, decimation accumulator, autocorrelation/tempo state, + phase accumulator, and the 4-output computation. Fed one per-block ODF value + at a time; mutated in place (no allocation after `init`). +- `Generators/Analysis/BeatTrack.swift` — the `BeatTrack.Control` generator; a + private `Source` enum selects spectral-flux vs feature ODF per block. +- `Generators/Analysis/BeatTrackODF.swift` — the public `BeatTrackODF` source + selector (the implementation flag). +- `Generators/Analysis/BeatTrackHelpers.swift` — `blockMaxODF` + the flat-row + output fill. +- `Generators/Analysis/BeatTrackConstants.swift` — the named constants above. + +Each is a separate file (one public type per file). `BeatTrackerCore` is +`internal`. + +## Test plan (tests-first) + +Deterministic synthetic ODF feeds (no audio hardware): + +1. **Tempo lock** — feed a periodic impulse ODF at 120 BPM for several seconds; + assert row 3 converges to 120 ± 5 %. +2. **Different tempo** — repeat at 90 BPM; assert lock at 90 ± 5 % (guards + against a hard-coded period). +3. **Beat spacing** — count row-0 triggers over N seconds; assert ≈ + `N · BPM / 60` beats and mean inter-trigger interval ≈ the beat period. +4. **Subdivisions** — assert row 1 fires ~2× and row 2 ~4× as often as row 0. +5. **Silence safe** — zero ODF: no NaN/Inf in any row, tempo finite. +6. **DC ODF** — constant non-zero ODF: no spurious lock to a degenerate period. +7. **Multi-row shape** — `outputChannelCount == 4`; all four rows length + `count`. +8. **`BeatTrack` integration** — build a `SpectralChain` on a synthetic click + track (an `Impulse` at the beat rate) and assert the FFT-fed path locks tempo. + +--- + +# Loudness — Zwicker psychoacoustic loudness + +`Loudness.Control` estimates perceived **loudness in sones** from the magnitude +spectrum of a paired analyze-only `SpectralChain.Audio`. One sone is, by +definition, the loudness of a 1 kHz pure tone at 40 dB SPL; perceived loudness +roughly doubles per +10 dB (Stevens' power law). + +Three fidelity models are folded into the one generator behind a `LoudnessModel` +flag (mirroring the `Balance` `logDomain:` and `BeatTrack` `BeatTrackODF` folds). +The selector is an enum because the models carry different parameters: + +- **`.barkEstimate`** — cheapest. Power summed into ~24 Bark critical bands → a + Stevens power-law specific loudness per band → sum. No masking, no + equal-loudness contour. Rough but stable; no SC parity claim. +- **`.realtimeZwicker(smask:tmask:)`** — SC `Loudness` ergonomics. Bark-band + excitation, equal-loudness/threshold weighting, specific loudness + `N' = (E/E₀)^0.23`, an upper-slope **spectral mask** (`smask`, spreads + excitation toward higher bands) and a **temporal mask** (`tmask`, one-pole + decay on the running total). Clean-room real-time Zwicker. +- **`.iso532b(field:)`** — full **ISO 532 B / DIN 45631** stationary Zwicker + loudness. Third-octave band levels (28 bands, 25 Hz … 12.5 kHz) → core + loudness via the standard's RAP/DLL correction tables → critical-band level + excitation with the LTQ/A0/DDF/DCB tables → upper-slope spreading (USL) → + integrate the specific-loudness function. `field` selects free vs + diffuse field. Highest fidelity; heaviest. Clean-room from Zwicker's published + algorithm (Zwicker, Fastl & Dallmayr 1991; DIN 45631) — **not** a port of the + GPL SuperCollider `Loudness` source. + +> **Clean-room note.** SuperCollider's `Loudness` (Nick Collins) is GPL and uses +> baked Bark/equal-loudness tables. This is an independent implementation from +> the published Zwicker model and the ISO 532 B / DIN 45631 standard. Output is +> in sones; do not expect bit-exact parity with SC. + +## Output + +`Loudness.Control` is a single-row `ControlGenerator`: total instantaneous +loudness in **sones** (≥ 0), ramped across the block like other control features +(`fillRampedResult`). `floatValue` returns the latest value. + +## Calibration + +Loudness needs absolute level (dB SPL), but the FFT magnitudes are in arbitrary +digital units (the exact scale depends on window + FFT normalisation). A single +`calibrationDB` parameter bridges the two: it is the dB offset added to each +bin's power level so that digital level maps to assumed SPL. Per bin: + +``` +P_k = magnitude(k)² // power, arbitrary units +L_k = 10·log10(P_k + tiny) + calibrationDB // dB SPL +``` + +`calibrationDB` defaults to `loudnessDefaultCalibrationDB` (chosen so a +full-scale 1 kHz sine lands near the top of the musical range). It is read once +at init. The **relative** behaviour (doubling per +10 dB, monotonicity) is +calibration-independent; only the absolute sone value depends on it. Set it per +your monitoring chain if absolute SPL matters; the documented anchor (1 kHz @ +40 dB SPL = 1 sone) holds once `calibrationDB` is set so the test tone reads +40 dB SPL. + +## Algorithm + +### Shared front-end (all models) + +1. Per bin `k`: power `P_k = magnitude(k)²`, centre frequency + `f_k = k · sampleRate / fftSize`. +2. Accumulate bin power into the model's band set: + - `.barkEstimate` / `.realtimeZwicker` → ~24 **Bark** critical bands + (band edges from the standard Bark scale). + - `.iso532b` → 28 **third-octave** bands (25 Hz … 12.5 kHz). +3. Band power → band level `L_band = 10·log10(P_band + tiny) + calibrationDB`. + +The bin→band index map is precomputed at init from `fftSize` + `sampleRate` +(no per-block branching on frequency); band accumulation is a single pass over +bins. + +### `.barkEstimate` + +Per Bark band: specific loudness `N'_z = max(0, (I_z / I₀)^0.3)` where `I_z` is +band intensity and `I₀` the reference intensity (`loudnessReferenceIntensity`). +Total `N = Σ N'_z` scaled by `loudnessBarkSpecificScale`. Stevens' exponent +`0.3` gives the +10 dB → 2× behaviour. + +### `.realtimeZwicker(smask:tmask:)` + +Per Bark band: excitation `E_z` from band level minus the band threshold-in-quiet +(`loudnessBarkThreshold[z]`); specific loudness +`N'_z = loudnessZwickerConst · (E_z/E₀)^0.23 · ((1 - s + s·E_z/E_thr)^0.23 - 1)` +in the Zwicker simplified form. `smask ∈ [0,1]` mixes an upper-slope spread of +excitation into higher bands before the exponent (spectral masking). The summed +loudness is then temporally masked by a one-pole release controlled by `tmask` +(seconds-ish; larger = slower decay, more masking of transients). Defaults +`smask = 0.25`, `tmask = 1.0` (SC defaults). + +### `.iso532b(field:)` + +The stationary Zwicker procedure (DIN 45631): + +1. Third-octave band levels → **core loudness** per critical band using the + `loudnessISORAP` range thresholds and the `loudnessISODLL` 8×28 correction + matrix (level-dependent transmission), the three lowest bands combined per + the standard. +2. Critical-band excitation level with `loudnessISOLTQ` (threshold in quiet), + `loudnessISOA0` (transfer ear), `loudnessISODDF` (free→diffuse, applied when + `field == .diffuse`), `loudnessISODCB` (core-loudness correction). +3. Specific loudness per critical band; **upper-slope spreading** down the + critical-band-rate (Bark) scale using `loudnessISOUSL` (18×8 slope table), + `loudnessISORNS`, and `loudnessISOZUP`. +4. Integrate the specific-loudness function (trapezoidal, band by band) → total + loudness `N` (sones). + +`field: LoudnessField` is `.free` (default) or `.diffuse`. Tables are transcribed +from the published standard; validated against the 1 kHz @ 40 dB = 1 sone anchor. + +### Edge cases + +- **Silence / zero spectrum**: all band powers ≈ 0 → `N → 0` sones; no NaN/Inf + (the `+ tiny` floor guards `log10(0)`, and specific loudness clamps at 0). +- **Monotonic**: more input power ⇒ more sones (all models). +- State (the `.realtimeZwicker` temporal-mask one-pole) is denormal-flushed each + block. + +## Constants (named, no magic numbers) + +| Constant | Meaning | +|---|---| +| `loudnessDefaultCalibrationDB` | default dBFS→SPL offset | +| `loudnessReferenceIntensity` | `I₀`, reference intensity for specific loudness | +| `loudnessTinyPower` | `log10` divide-by-zero floor | +| `loudnessBarkBandCount` | 24 (Bark critical bands) | +| `loudnessBarkEdgesHz` | Bark band edge frequencies | +| `loudnessBarkThreshold` | per-Bark threshold in quiet | +| `loudnessStevensExponent` | `0.3` (barkEstimate power law) | +| `loudnessZwickerExponent` | `0.23` (realtime Zwicker) | +| `loudnessZwickerConst`, `loudnessBarkSpecificScale` | model output scalings | +| `loudnessISOThirdOctaveCount` | 28 | +| `loudnessISOCenterFreqsHz`, `loudnessISORAP`, `loudnessISODLL`, `loudnessISOLTQ`, `loudnessISOA0`, `loudnessISODDF`, `loudnessISODCB`, `loudnessISOZUP`, `loudnessISORNS`, `loudnessISOUSL` | ISO 532 B tables | + +## Usage + +```swift +let chain = SpectralChain.Audio(input: mix, fftSize: 2048, hopSize: 512, analyzeOnly: true) + +// Cheap real-time meter: +let n1 = Loudness.Control(model: .barkEstimate, analysis: chain, sampleRate: sr) +// SC-style: +let n2 = Loudness.Control(model: .realtimeZwicker(smask: 0.25, tmask: 1.0), analysis: chain, sampleRate: sr) +// Full standard: +let n3 = Loudness.Control(model: .iso532b(field: .free), analysis: chain, sampleRate: sr) +// n[*] output is loudness in sones (single row). +``` + +## Parameters — `Loudness.Control` + +The designated init takes `model: LoudnessModel`; convenience inits may default it. + +| Param | Type | Default | Meaning | +|---|---|---|---| +| `model` | `LoudnessModel` | `.realtimeZwicker(smask:0.25,tmask:1.0)` | fidelity model + its params | +| `analysis` | `SpectralChain.Audio` | — | analyze-only chain (read each block) | +| `sampleRate` | `Double` | — | for bin→Hz band mapping | +| `calibrationDB` | `Double` | `loudnessDefaultCalibrationDB` | dBFS→SPL offset | +| `mul` / `add` | `ValidGeneratorInput` | `1.0` / `0.0` | output scaling | + +`model` / `sampleRate` / `calibrationDB` are read once at init (they size the +band map and tables — not RT-mutable). Audio-input driven, Control-rate output; +no `Audio` variant. + +## Implementation layout + +- `Generators/Analysis/Loudness.swift` — `Loudness.Control`; a private model + switch selects the backend per block. +- `Generators/Analysis/LoudnessModel.swift` — public `LoudnessModel` enum + + `LoudnessField`. +- `Generators/Analysis/LoudnessBandCore.swift` — shared FFT→band-power binning + (Bark + third-octave maps) + the per-model specific-loudness backends. +- `Generators/Analysis/LoudnessConstants.swift` — named constants + the ISO 532 B + tables. + +## Test plan (tests-first) + +Synthetic spectra fed through a `SpectralChain` (or a directly populated +`SpectralBuffer`): + +1. **Silence → ~0 sones** for all three models; finite, no NaN/Inf. +2. **Monotonic with level** — louder sine ⇒ more sones (all models). +3. **+10 dB ≈ 2×** — a sine 10 dB louder ≈ doubles sones (Stevens range), + tolerance ~30 % (model-dependent). +4. **Calibration anchor** — a 1 kHz sine with `calibrationDB` set so it reads + 40 dB SPL → ≈ 1 sone (±~25 %), per model where defined (strongest for + `.iso532b` and `.realtimeZwicker`). +5. **Each model runs + finite** over many blocks; control-rate output shape + (single row, length `count`, ramped). +6. **`field` effect** — `.iso532b(.diffuse)` differs from `.free` for an HF tone. +7. **Enum-vs-convenience init equivalence** if convenience inits are added. diff --git a/docs/stdlib/generators.md b/docs/stdlib/generators.md index 7422d76..d729314 100644 --- a/docs/stdlib/generators.md +++ b/docs/stdlib/generators.md @@ -16,7 +16,7 @@ extension OscSin: GeneratorEnum { } ``` -All paired built-in generators (`OscSin`, `OscTable`, `Impulse`, `WhiteNoise`, `LFStepNoise`, `LFLineNoise`, `PinkNoise`, `BrownNoise`, `GrayNoise`, `ClipNoise`, `Dust`, `Dust2`, `Crackle`, `LFCurveNoise`, `UniformNoise`, `GaussNoise`, `LpRandNoise`, `HpRandNoise`, `MeanRandNoise`, `ExpRandNoise`, `ExponentialNoise`, `GammaNoise`, `LaplaceNoise`, `ALaplaceNoise`, `HcosNoise`, `LogisticNoise`, `PoissonNoise`, `ArcsinNoise`, `BetaRandNoise`, `CauchyNoise`, `EnvelopeGen`, `PlayBuffer`, `RecordBuffer`, `In`, `Out`, `SendTrigger`, `Demand`, `TimedDemand`) conform to `GeneratorEnum`. New paired generators must do the same — see `docs/protocols/writing-generators.md`. +All paired built-in generators (`OscSin`, `OscTable`, `Impulse`, `Phasor`, `WhiteNoise`, `LFStepNoise`, `LFLineNoise`, `PinkNoise`, `BrownNoise`, `GrayNoise`, `ClipNoise`, `Dust`, `Dust2`, `Crackle`, `LFCurveNoise`, `UniformNoise`, `GaussNoise`, `LpRandNoise`, `HpRandNoise`, `MeanRandNoise`, `ExpRandNoise`, `ExponentialNoise`, `GammaNoise`, `LaplaceNoise`, `ALaplaceNoise`, `HcosNoise`, `LogisticNoise`, `PoissonNoise`, `ArcsinNoise`, `BetaRandNoise`, `CauchyNoise`, `EnvelopeGen`, `PlayBuffer`, `RecordBuffer`, `In`, `Out`, `SendTrigger`, `Demand`, `TimedDemand`, `Trig`, `Trig1`, `TriggeredDelay`, `PulseCount`, `Stepper`, `Schmidt`, `Slew`, `ZeroCrossing`, `Slope`, `RunningMin`, `RunningMax`, `CrossFade`, `LinearCrossFade`, `Select`, `Waveshaper`, `CrossoverDistortion`, `Formlet`, `LFGauss`, `LorenzLinear`, `HenonStepped`, `QuadStepped`, `LinCongStepped`, `GbmanStepped`, `StandardStepped`, `FBSineStepped`, `LatoocarfianStepped`, `CuspStepped`) conform to `GeneratorEnum`. New paired generators must do the same — see `docs/protocols/writing-generators.md`. ## RT-allocation model (all generators) @@ -184,6 +184,21 @@ Impulse.Audio(freq: 1.0, initPhase: 0.5) // first fire at half-period offset - `initPhase` is a fraction [0, 1) — `0.0` fires at sample 0 of the first block. - State: `LyrebirdFloat` phase accumulator. +#### Phasor +Linear phase accumulator (ramp generator). Equivalent to SuperCollider `Phasor`. Accumulates `rate` units per sample within the half-open range `[start, end)`. On a ≤0 → >0 rising edge of `trig`, phase resets to `resetPos`. + +```swift +Phasor.Audio() // default: ramp 0..1 at 1/sample +Phasor.Audio(rate: 440.0 * 1024.0 / 44100.0, start: 0, end: 1024) // 1024-sample wavetable scan at 440 Hz +Phasor.Audio(trig: Impulse.Audio(freq: 2.0), rate: 0.01, resetPos: 0) // reset on trigger +Phasor.Control(rate: 0.001) // slow ramp at control rate +``` + +- `rate` is the **per-sample phase increment** (not Hz). For table scanning: `rate = freq * tableSize / sampleRate`. +- `start` / `end` define the half-open range `[start, end)`. Wrapping is via `truncatingRemainder` — safe for rates larger than the span. +- `trig` scans the full audio-rate trigger block per audio block in both `.Audio` and `.Control` variants. +- Standalone sync/ramp primitive; works at any rate in the signal graph. + --- ### Noise @@ -862,6 +877,36 @@ All `AudioGenerator` and `ControlGenerator` instances inherit a `[n]` subscript Out-of-range `n` returns silence. See `docs/stdlib/multichannel.md` for full examples. +### CrossFade.Audio / CrossFade.Control (SC `XFade2`) + +Equal-power crossfade between two inputs. Maps `pan ∈ [−1, 1]` to a quarter-sine/cosine +gain pair so that `gainA² + gainB² = 1` at every position. `mul` plays the role of SC's +`level` argument. Mono output (channel 0 of each input). Both `Audio` and `Control` variants. + +```swift +let xfade = CrossFade.Audio(inA: osc1, inB: osc2, pan: modLFO) +``` + +### LinearCrossFade.Audio / LinearCrossFade.Control (SC `LinXFade2`) + +Linear crossfade between two inputs. `gainA = (1 − pan) * 0.5`, `gainB = (1 + pan) * 0.5` +so `gainA + gainB = 1` everywhere. Useful when constant-amplitude sum is preferred over +constant power. `mul` plays the role of SC's `level` argument. Mono output. Both variants. + +```swift +let xfade = LinearCrossFade.Audio(inA: dry, inB: wet, pan: sendLevel) +``` + +### Select.Audio / Select.Control (SC `Select`) + +Index-selected N-input switch. Outputs the input at integer index `which` (truncated toward +zero, clamped to `[0, N−1]`). All inputs are pulled every block regardless of selection — +SC parity: non-selected sources advance their internal state. Both `Audio` and `Control` variants. + +```swift +let sel = Select.Audio(which: modLFO, inputs: [osc1, osc2, osc3]) +``` + --- ## LyrebirdMusicMath — Musical Conversion Utilities @@ -998,16 +1043,24 @@ let freqCR = LinExp.Control(env, inLo: 0.0, inHi: 1.0, outLo: 80.0, outHi: 8000 ## Dynamics -Five signal-processing generators for amplitude tracking, pitch detection, limiting, compression, and expansion. Full API reference: `docs/stdlib/dynamics.md`. +Seven signal-processing generators for amplitude tracking, pitch detection, limiting, normalizing, RMS matching, compression, and expansion. Full API reference: `docs/stdlib/dynamics.md`. | Generator | Variants | Description | |-----------|----------|-------------| | `AmplitudeFollower` | Audio + Control | Envelope follower; asymmetric attack/release one-pole smoother | | `FreqTracker` | Audio only | YIN-based pitch tracker; 2-channel out (Hz + confidence 0..1) | | `LookAheadLimiter` | Audio only | True look-ahead limiter; no overshoot; `lookAheadTime` latency | +| `Normalizer` | Audio only | Look-ahead peak normalizer; scales up AND down to `level`; `dur` latency | +| `Balance` | Audio only | RMS level matcher; scales `in` to track the running RMS of `test`; decoupled `hp`/`smooth`; optional `logDomain` glide | | `Compressor` | Audio + Control | Feed-forward compressor; threshold/ratio/attack/release/knee/makeup | | `Expander` | Audio + Control | Downward expander/gate; mirrors `Compressor` below threshold | +`Balance` (sc3-plugins `Balance`, JoshUGens) tracks the running mean-square of two signals via a one-pole lowpass on squared samples (pole `b1 = exp(-2π·hp/sr)` from the `hp` cutoff in Hz, snapshotted per block) and outputs `in · sqrt(ms_test / (ms_in + tiny))`. Because the gain is a ratio of two identically-normalised mean-squares, the normalisation cancels — only the `hp` window length matters (equivalent to SC's unnormalised running-sum form, but bounded + denormal-safe). Canonical use: bring a filtered signal back up to the level of the unfiltered source. Silent `in` stays silent; silent `test` drives `in` toward zero; `tiny` (1e-10) guards the divide. Takes `mul`/`add`. + +A single one-pole on `x²` ripples at twice the signal frequency, so a high `hp` lets that ripple modulate the gain (amplitude-modulation sidebands, worst on bass). `Balance` adds a second, **decoupled** one-pole on the gain via `smooth` (seconds): raise `hp` for fast level detection, then raise `smooth` to suppress the ripple independently. `smooth == 0` (default) bypasses the lag — bit-identical to the classic single-pole form. Set `logDomain: true` to smooth the gain in the **decibel (log) domain** instead: it smooths the level *difference in dB* (`log10(ms_test/ms_in)`) then exps back, so a `+6 dB` and a `−6 dB` correction glide with the same shape and time (symmetric, perceptually even — like an analogue auto-leveller), versus the default linear-gain lag which is faster on boosts than cuts. The log path costs one `log10` + one `exp` per sample and floors the power so silence stays finite. + +`Normalizer` (SC `Normalizer`) shares `LookAheadLimiter`'s ring-buffer + monotonic sliding-window-max deque, but its gain law is `level / windowPeak` applied unconditionally (vs the limiter's `maxAmp / windowPeak` only when over the ceiling), so quiet passages are scaled **up** and loud ones **down** to track `level`. Instant attack (no overshoot) + one-pole smoothed release (time constant `dur`); output delayed by `Int(dur·sampleRate)`. `sampleRate` is required at init. An exactly-silent window holds gain (no `level/0`); a near-silent non-zero window amplifies its noise floor toward `level` (intended normalizer behaviour). + All generators are single-channel in/out. Multi-channel use via MCE. `AmplitudeFollower`, `Compressor`, `Expander` conform to `GeneratorEnum`. --- @@ -1247,6 +1300,20 @@ LFTriangle.Audio(freq: 4.0, mul: 0.1) // gentle tremolo LFO LFDutyCycle.Audio(freq: 6.0, dutyCycle: 0.2) ``` +### LFGauss (SC `LFGauss`) +Gaussian bell-shaped oscillator. Over each `period` (seconds) the output traces a Gaussian bell — near `0` at the period boundaries, peaking at `1.0` at the period midpoint. `width` is the standard deviation as a fraction of the half-period (smaller → narrower spike). Output range `(0, 1]`. A smooth non-band-limited LFO and a ready-made grain-window shape. Paired `GeneratorEnum` (Audio + Control). `period` and `width` accept generator inputs; `phase` is an init-only `[0, 1)` offset (`0` starts at a trough, `0.5` at the peak). + +``` +x = 2·phase − 1 (phase advances 1 / (period · sr) per sample) +out = exp(−0.5 · (x / width)²) +``` + +```swift +LFGauss.Audio(period: 0.02, width: 0.15) // ~50 Hz bell-train LFO +LFGauss.Audio(period: 0.5, width: 0.1, phase: 0.0) // grain envelope, starts at trough +LFGauss.Control(period: 2.0, width: 0.25) // slow swell +``` + ### WavetableMorph Linear-interpolation wavetable scanner across an array of equal-length mono `LyrebirdBuffer` tables. `position` ∈ `[0, table_count − 1]` selects between adjacent tables; fractional positions blend. @@ -1266,6 +1333,78 @@ WavetableMorph.Audio( --- +## Chaotic / Strange-Attractor Oscillators + +`Generators/Chaotic/`. Oscillators that iterate a discrete chaotic map at a chosen `freq` (iterations/sec, **not** once per sample) and bridge successive iterations with `interpolation` (`.none` held/aliased, `.linear`, `.cubic`). Shared base `ChaoticBase` (analogous to `NoiseBase`) owns `freq`, `mulAdd`, the interpolation kernel, a 4-value history ring, and the sub-iteration phase accumulator; per-map `_Base` subclasses add the map variables + `iterate()`. `freq` and map parameters are read once per block (no per-sample audio-rate modulation). `Control` advances one audio block per call and ramps via `fillRampedResult`. `Crackle` (under Noise) is the only per-sample chaotic map and is unrelated to this family. + +### LorenzLinear (SC `LorenzL`) +Lorenz strange attractor by forward Euler (`x' = x + h·s·(y−x)`, etc.), output = `x`. Default `interpolation: .linear`. Output is the **raw** `x` coordinate (`|x|` ≲ 25 on the attractor) — scale with `mul`. The Euler step `h` defaults to `0.02`: SC's nominal `0.05` diverges under plain forward Euler (verified — blows up within ~25 steps), so keep `h` below ~0.03. + +```swift +LorenzLinear.Audio(freq: 22050.0, mul: 0.05) // classic attractor tone, scaled to ~[-1,1] +LorenzLinear.Control(freq: 200.0, mul: 0.05) // slow chaotic LFO +``` + +### HenonStepped (SC `HenonN`) +Hénon map `x[n+1] = 1 − a·x[n]² + b·x[n−1]`, output = `x`. Default `interpolation: .none` (held/stepped — the aliased SC `HenonN` character). Canonical `a = 1.4`, `b = 0.3` → bounded chaotic orbit in roughly `[-1.5, 1.5]`. + +```swift +HenonStepped.Audio(freq: 22050.0) // gritty stepped chaos +HenonStepped.Audio(freq: 8000.0, interpolation: .cubic) // smoothed +``` + +### QuadStepped (SC `QuadN`) +General quadratic map `x[n+1] = a·x[n]² + b·x[n] + c`, output `x`, default `.none`. Canonical `a = 1`, `b = −1`, `c = −0.75` → chaotic, bounded ~`[-1.25, 1.25]` (conjugate to the logistic map). + +```swift +QuadStepped.Audio(freq: 6000.0) +``` + +### LinCongStepped (SC `LinCongN`) +Linear-congruential map `x[n+1] = (a·x[n] + c) mod m`, output stays in `[0, m)`, default `.none`. Canonical `a = 1.1`, `c = 0.13`, `m = 1`. + +```swift +LinCongStepped.Audio(freq: 6000.0) // output in [0, 1) +LinCongStepped.Audio(freq: 6000.0, mul: 2.0, add: -1.0) // bipolarised to [-1, 1) +``` + +### GbmanStepped (SC `GbmanN`) +Gingerbreadman map `x[n+1] = 1 − y[n] + |x[n]|`, `y[n+1] = x[n]`; output `x`, default `.none`. No shape parameters — only initial conditions `xi`/`yi`. Bounded chaotic (`|x| ≲ 8`). + +```swift +GbmanStepped.Audio(freq: 6000.0, mul: 0.2) +``` + +### StandardStepped (SC `StandardN`) +Chirikov standard map (kicked rotor): `y' = (y + k·sin(x)) mod 2π`, `x' = (x + y') mod 2π`; output `x` ∈ `[0, 2π)`. Larger `k` → stronger chaos (default `1`). Scale with `mul: 1/π, add: -1` for `[-1, 1)`. + +```swift +StandardStepped.Audio(freq: 6000.0, k: 1.0) +``` + +### FBSineStepped (SC `FBSineN`) +Feedback sine map: `x' = sin(im·y + fb·x)`, `y' = (a·y + c) mod 2π`; output `x` ∈ `[-1, 1]`. Defaults `im=1`, `fb=0.1`, `a=1.1`, `c=0.5`. + +```swift +FBSineStepped.Audio(freq: 6000.0) +``` + +### LatoocarfianStepped (SC `LatoocarfianN`) +Pickover's Latoocarfian: `x' = sin(b·y) + c·sin(b·x)`, `y' = sin(a·x) + d·sin(a·y)`; output `x` ∈ ~`[-1.5, 1.5]`. Chaos generally needs `|a|, |b| ≤ 3` (defaults `a=1`, `b=3`, `c=d=0.5`). + +```swift +LatoocarfianStepped.Audio(freq: 6000.0) +``` + +### CuspStepped (SC `CuspN`) +Cusp map: `x' = a − b·√|x|`; output `x`. Canonical `a=1`, `b=1.9` → chaotic, bounded ~`[-0.9, 1.0]`. + +```swift +CuspStepped.Audio(freq: 6000.0) +``` + +--- + ## EnvelopePoll Read a fixed-shape `Envelope` at arbitrary times. Output is the envelope's level at `time` seconds. No internal phase or trigger — purely a value lookup. Useful for driving filter cutoff curves, panning trajectories, or pattern-driven scoring. @@ -1323,6 +1462,18 @@ Lag2UpDown.Control(input: $sig, lagUp: 0.01, lagDown: 0.3) // cascade asymmetri - `time`, `lagUp`, `lagDown` are 60 dB time constants in seconds. - All accept audio-rate inputs; coefficient recomputation per block. +### Slew +Linear slew-rate limiter. Equivalent to SuperCollider `Slew`. Moves the output toward `input` at a maximum rate of `up` units per second when rising and `dn` units per second when falling. On the first block the output is initialised directly to the first input value. + +```swift +Slew.Audio(input: controlSignal, up: 500.0, dn: 200.0) // asymmetric slopes +Slew.Control(input: $cv, up: 100.0, dn: 100.0) // smooth CV at control rate +``` + +- `up` / `dn` are slopes in **units per second** (not per sample). The per-sample step is `up / sampleRate` (audio) or `up / (sampleRate / blockSize)` (control). +- **Linear** rate-limiting — distinct from the **exponential** smoothing produced by the `Lag` family. Use `Lag` for an RC-filter curve; use `Slew` for a linear ramp at a controlled maximum slope. +- `Slew.Control` produces a flat output block (like `Lag.Control`); use `Slew.Audio` for smoothly interpolated output. + ### Decay / Decay2 / LeakDC - **`Decay`**: One-pole exponential decay tail on each non-zero input sample. `decayTime` is the 60 dB decay time in seconds. - **`Decay2`**: Differenced pair of Decays — produces a percussive attack-then-release envelope from an impulse train. @@ -1358,6 +1509,36 @@ ResonatorBank.Audio(input: excitation, buffer: buffer) - Buffer `channelCount` precondition: `resonatorBankChannelCount` (= 3). - Each row is a complex resonator; bank is summed to mono output. +### Klank.Audio (SC `Klank`) +Modulatable counterpart of `ResonatorBank` — parallel two-pole resonator bank with the three SC `Klank` block-rate modulation parameters. Spec buffer rows are `(freq, amp, decay)` (SC channel order). Audio-only. + +```swift +let spec = LyrebirdBuffer(count: 3, channelCount: klankSpecChannelCount) // freq, amp, decay +// fill rows with N resonator specs +Klank.Audio(input: excitation, buffer: spec, + freqscale: 1.0, freqoffset: 0.0, decayscale: 1.0) +``` + +- `freqscale` / `freqoffset` / `decayscale` are any `ValidGeneratorInput`, snapshotted once per audio block: `freq_eff = freq·freqscale + freqoffset`, `decay_eff = decay·decayscale`. +- Buffer `channelCount` precondition: `klankSpecChannelCount` (= 3); channel indices `klankFreqChannel` / `klankAmpChannel` / `klankDecayChannel`. +- Whole-table live swap via `setBuffer(_:engine:)` (RT-safe `RTBufferSlot`); new buffer must match the initial bank size. `freq_eff` floored at `0.1` Hz, `decay_eff` at `1e-6` s; `amp` unclamped. +- Same vDSP per-sample kernel as `ResonatorBank`; summed to mono. + +### Klang.Audio (SC `Klang`) +Additive sine-partial bank — the source counterpart of `Klank` (no input). Outputs the sum of N table-lookup sines. Spec buffer rows are `(freq, amp, phase)` (SC channel order). Audio-only. + +```swift +let spec = LyrebirdBuffer(count: 4, channelCount: klangSpecChannelCount) // freq, amp, phase +// fill rows with N partial specs +Klang.Audio(buffer: spec, freqscale: 1.0, freqoffset: 0.0, + interpolation: .linear) +``` + +- `freqscale` / `freqoffset` snapshotted once per block: `freq_eff = freq·freqscale + freqoffset`. +- `freq` / `amp` re-read from the table each block (live `setValue` + `setBuffer(_:engine:)` swap retune the bank). The `phase` channel seeds each partial's phase accumulator at `init` only — phases free-run thereafter, so table swaps never click. +- Buffer `channelCount` precondition: `klangSpecChannelCount` (= 3); channel indices `klangFreqChannel` / `klangAmpChannel` / `klangPhaseChannel`. +- `interpolation: TableInterpolation` (`.none` / `.linear` / `.cubic`) on the shared sine table; `amp` and `freq_eff` unclamped (negatives invert / reverse). + ### MuTronIII.Audio / .Control *See [MuTronIII](#mutroniii) under Filters above for full description.* @@ -1374,6 +1555,20 @@ RingingFilter(input: trig, freq: 440.0, bandwidth: 80.0) // tuned ringing - `Comb` / `Allpass` use a circular delay line allocated to `maxDelay × sampleRate`; `delay` and `decayTime` can be retuned per block. Feedback coefficient derives from the shared `combFeedbackCoeff(decayTime:delay:)` helper. - `Resonating` and `Ringing` are biquads tuned by `freq` + (`decayTime` | `bandwidth`). +### Formlet (SC `Formlet`) +FOF-like resonant filter parameterised by `attackTime` / `decayTime` rather than `freq` + `Q`. The impulse response is a sine at `freq` under a rise-then-fall (Decay2-style) envelope — the basis of formant / vowel synthesis. Defined as the difference of two `ResonatingFilter` (Ringz) outputs at the same `freq`: + +``` +Formlet(in, freq, attack, decay) == ResonatingFilter(in, freq, decay) − ResonatingFilter(in, freq, attack) +``` + +Paired `GeneratorEnum` (Audio + Control). Reuses `runTwoPoleResonatorScalarBlock` / `…InterpolatedBlock` and `resonatingCoeffs`. `freq`, `attackTime`, `decayTime` all accept generator inputs (block-boundary coefficient interpolation). + +```swift +Formlet.Audio(input: impulse, freq: 880.0, attackTime: 0.001, decayTime: 0.1) +Formlet.Control(input: trig, freq: 220.0, attackTime: 0.01, decayTime: 0.5) +``` + --- ## Triggers @@ -1414,6 +1609,74 @@ SendTrigger.Control(trig: Impulse.Control(freq: 4.0), id: 7, value: $cutoff) - `id` is `Int32`, init-only. - Events delivered via the engine's lock-free `TriggerListener` queue. +### Trig +SC `Trig`. On each ≤0 → >0 rising edge of `input`, captures the input value at that frame and outputs it for `dur` seconds, then returns to `0.0`. A new edge during the hold restarts the timer and re-captures the level. + +```swift +Trig.Audio(input: Impulse.Audio(freq: 4.0), dur: 0.1) +Trig.Control(input: envTrig, dur: 0.5) +``` + +- `dur`: hold duration in seconds (init-time scalar; converted to samples via engine sample rate; minimum 1 sample). +- The `input` signal is both the trigger source and the level captured on each rising edge. + +### Trig1 +SC `Trig1`. Identical to `Trig` but always outputs `1.0` (unity) regardless of the input level for `dur` seconds after each ≤0 → >0 rising edge. Useful for generating fixed-amplitude gate pulses. + +```swift +Trig1.Audio(input: Impulse.Audio(freq: 4.0), dur: 0.05) +Trig1.Control(input: envTrig, dur: 0.2) +``` + +- `dur`: hold duration in seconds (init-time scalar; minimum 1 sample). + +### TriggeredDelay +SC `TDelay`. Delays a trigger by `dur` seconds: on a ≤0 → >0 rising edge of `input`, starts a countdown. When the countdown elapses, emits a single-sample `1.0`. Additional edges arriving while the countdown is active are **ignored** (only the first edge per idle cycle is honoured). + +```swift +TriggeredDelay.Audio(input: Impulse.Audio(freq: 2.0), dur: 0.2) +TriggeredDelay.Control(input: clockTrig, dur: 0.1) +``` + +- `dur`: delay duration in seconds (init-time scalar; minimum 1 sample). + +### PulseCount +SC `PulseCount`. Running counter that increments by 1 on each ≤0 → >0 rising edge of `trig`. A rising edge of `reset` clears the counter to `0.0` before the `trig` increment at that sample. + +```swift +PulseCount.Audio(trig: Impulse.Audio(freq: 4.0)) +PulseCount.Control(trig: clock, reset: resetTrig) +``` + +- Counter is never clamped and grows without bound. + +### Stepper +SC `Stepper`. Wrapping integer step counter. On each rising edge of `trig`, advances by `step` within `[min, max]`, wrapping at the boundaries. `reset` returns the value to `resetval`. All range/step/reset parameters are init-time scalars. + +```swift +// 8-step sequencer index cycling 0..7 +Stepper.Audio(trig: Impulse.Audio(freq: 4.0), min: 0, max: 7, step: 1, resetval: 0) +Stepper.Control(trig: clock, reset: resetSig, min: 0, max: 15) +``` + +- `min`, `max`: range (inclusive). `max` must be ≥ `min`. Defaults: `0` / `7`. +- `step`: signed increment per edge. Defaults to `1`. Negative values step downward. +- `resetval`: value written on a reset edge; clamped to `[min, max]`. Defaults to `0`. + +### Schmidt +SC `Schmidt`. Schmitt trigger with hysteresis. Maintains binary `0.0` / `1.0` state with separate switch-on (`hi`) and switch-off (`lo`) thresholds. Prevents chatter near the threshold. + +- State `0.0` → `1.0`: when `input > hi`. +- State `1.0` → `0.0`: when `input < lo`. +- In the hysteresis band `[lo, hi]`: state unchanged. + +```swift +Schmidt.Audio(input: amp, lo: 0.1, hi: 0.3) +Schmidt.Control(input: $cv, lo: 0.2, hi: 0.8) +``` + +- `lo`, `hi`: any `ValidGeneratorInput` — scalar literals, `ParameterNode`, `@LiveParam`, or audio/control-rate generators. When using audio-rate generators for per-sample varying thresholds, ensure they conform to `Generator` (not `Closure`). + --- ## Random Generators @@ -2255,3 +2518,111 @@ let onset = OnsetDetector.Control(analysis: analysis, method: .spectralFlux, - `OnsetDetector` exposes `OnsetDetectionMethod` enum (`.spectralFlux`, `.complexDomain`, etc.); fires `1.0` for one block at each detected onset. --- + +## Time-Domain Analysis + +Four SuperCollider-parity time-domain analysis and measurement generators. Source files live in `Sources/Lyrebird/Generators/Analysis/`. + +| Generator | SC equivalent | Audio | Control | Description | +|-----------|--------------|-------|---------|-------------| +| `ZeroCrossing` | `ZeroCrossing` | yes | yes | Frequency estimate (Hz) from rising zero-crossing spacing. Output held between crossings; `0.0` until the first full period is measured. | +| `Slope` | `Slope` | yes | yes | Per-second rate of change: `(x[n] − x[n−1]) × sampleRate`. First sample/block outputs `0.0` (lazy init — no startup spike). | +| `RunningMin` | `RunningMin` | yes | yes | Running minimum since the last trigger reset. Lazy-initialised to the first input value. Rising `trig` edge resets to the current input. | +| `RunningMax` | `RunningMax` | yes | yes | Running maximum since the last trigger reset. Identical behaviour to `RunningMin` but tracking the maximum. | + +All four are paired generators conforming to `GeneratorEnum`. `Control` variants bypass the sub-block loop (scan the full audio-rate input block once per audio cycle and output a flat result). + +```swift +// Frequency estimation. +let zcFreq = ZeroCrossing.Audio(input: audioSignal) +let zcFreqCtl = ZeroCrossing.Control(input: audioSignal) // block-rate measurement + +// Rate-of-change differentiation. +let diff = Slope.Audio(input: envelope) // per-sample differentiation +let diffCtl = Slope.Control(input: $cv) // block-rate differentiation + +// Peak / trough tracking. +let peakTracker = RunningMax.Audio(input: signal) +let peakTrackerReset = RunningMax.Audio(input: signal, trig: resetClock) +let troughTracker = RunningMin.Control(input: $cv, trig: gate) +``` + +Parameters common to all four: +- `input`: signal to analyse (`any ValidGeneratorInput`) +- `mul`: output multiplier, default `1.0` +- `add`: output offset, default `0.0` +- `RunningMin` / `RunningMax` additionally accept `trig` (default `0.0`) + +--- + +## Waveshaping / Distortion + +Transfer-function and stochastic distortion generators. Source files live in +`Sources/Lyrebird/Generators/Waveshaping/`. + +| Generator | SC equivalent | Audio | Control | Description | +|-----------|--------------|-------|---------|-------------| +| `Waveshaper` | `Shaper` | yes | yes | Table-lookup transfer-function waveshaper. Input clamped to `[-1, 1]` before linear-interpolated table lookup. RT-safe live table swap via `setTable(_:engine:)`. | +| `CrossoverDistortion` | `CrossoverDistortion` | yes | yes | Dead-zone / crossover distortion. Signals in `[-amp, amp]` are silenced; signals outside that range are shifted toward zero. Optional C¹ smooth knee. | +| `Disintegrator` | `Disintegrator` | yes | — | Stochastic sample-dropping distortion. Each sample is independently disintegrated (replaced by `input × multiplier`) with probability `probability`. Audio-only. | + +`Waveshaper` and `CrossoverDistortion` conform to `GeneratorEnum`. `Disintegrator` is Audio-only and does not. + +### Waveshaper (SC `Shaper`) + +Transfer-function waveshaper using a `LyrebirdBuffer` as the transfer curve. + +```swift +let table = LyrebirdBuffer(count: 1024) +table.fill { i, n in + let x = Double(i) / Double(n - 1) * 2.0 - 1.0 + return tanh(x * 4.0) // soft saturation +} +let shaper = Waveshaper.Audio(table: table, input: signal) +let lfoShaper = Waveshaper.Control(table: table, input: lfoSignal) +``` + +- `table`: mono `LyrebirdBuffer` (at least 2 samples). The transfer curve is indexed by the clamped input `x ∈ [-1, 1]` via `pos = (x × 0.5 + 0.5) × (tableSize − 1)` with linear interpolation. +- `input`: signal to waveshape. Values outside `[-1, 1]` are clamped (saturating, not wrapping). +- `mul` / `add`: standard output multiplier and offset. +- `setTable(_:engine:)`: RT-safe live table swap. New table must be mono and same size as the initial table. + +### CrossoverDistortion (inspired by SC `CrossoverDistortion`) + +Crossover / dead-zone distortion with optional smooth knee. The implementation is a clean +owned formula — not claimed bit-exact with SuperCollider, but sharing the same conceptual model. + +```swift +// Hard-knee crossover: dead zone ±0.5, then linear continuation. +let dist = CrossoverDistortion.Audio(input: signal, amp: 0.5, smooth: 0.0) + +// Soft-knee: C¹ quadratic ease-in at the dead-zone boundary. +let softDist = CrossoverDistortion.Audio(input: signal, amp: 0.3, smooth: 0.5) +``` + +- `amp`: dead-zone half-width (≥ 0). Signals in `[−amp, amp]` are zeroed. **Not an output gain** — use `mul` for gain. SC also names this `amp`. +- `smooth`: knee smoothness `[0, 1]`. `0` = hard knee (instantaneous transition); `1` = full-width C¹ ease-in over the full dead-zone width. +- Transfer function: for `|x| > amp`, `over = |x| − amp`. Hard-knee: `out = sign(x) × over`. Soft-knee: `out = sign(x) × over² / (2 × kneeWidth)` within the knee, then linear continuation maintaining C¹ continuity. + +### Disintegrator (SC `Disintegrator`) + +Stochastic sample-dropping distortion. Audio-only — "block-rate disintegration" has no +meaningful physical interpretation; the random draw must happen per sample. + +```swift +// Drop ~50 % of samples to silence. +let dist = Disintegrator.Audio(input: signal, probability: 0.5, multiplier: 0.0) + +// Attenuate ~30 % of samples by half. +let grit = Disintegrator.Audio(input: signal, probability: 0.3, multiplier: 0.5) + +// Deterministic seed for tests. +let det = Disintegrator.Audio(input: signal, probability: 0.5, seed: 42) +``` + +- `probability`: `[0, 1]` chance per sample of disintegration. Clamped internally. +- `multiplier`: scale factor applied to disintegrated samples. `0.0` → silence; `1.0` → no change (same as `probability = 0`). +- `seed`: optional PRNG seed. `nil` = time-derived unique seed; explicit value = deterministic/reproducible output. +- `mul` / `add`: applied after disintegration to all samples (including undisintegrated ones). + +--- diff --git a/docs/stdlib/shoegaze.md b/docs/stdlib/shoegaze.md new file mode 100644 index 0000000..57c45c9 --- /dev/null +++ b/docs/stdlib/shoegaze.md @@ -0,0 +1,349 @@ +# ShoeGaze — Guitar Pedalboard Framework + +ShoeGaze is a nested SwiftPM sub-package (`ShoeGaze/`) that models a guitar-effect signal chain as a sequence of `Pedal` objects managed by a `PedalBoard`, all hosted by a `ShoeGaze` manager that owns the `SynthesisEngine`. + +--- + +## Core Concepts + +### `Pedal` + +A `Pedal` is a `SynthesizerBase` subclass that reads a mono signal from its input bus, runs it through a subclass-supplied `effect(_:)` stage, blends wet/dry with an equal-power crossfade (`mix`), applies a click-free `bypass` crossfade, scales by `level`, and writes to its output bus. Each pedal exposes its knobs as `@UIParam` properties and publishes a `knobs: [PedalKnob]` list so `PedalView` (from `LyrebirdShoeGazeUI`) renders a control per parameter. + +Eight built-in pedals (the signal chain is mono; stereo-native effects fold to mono internally): + +| Type | Effect | +|---|---| +| `OverdrivePedal` | Soft-clip saturation → RBJ low-pass tone. Knobs: `drive`, `tone` | +| `DelayPedal` | Feedback delay line. Knobs: `time`, `feedback` | +| `ReverbPedal` | Freeverb (stereo, summed to mono). Knobs: `roomSize`, `damping` | +| `ModulationPedal` | Chorus (stereo, summed to mono). Knobs: `rate`, `depth` | +| `FuzzPedal` | High-gain `tanh` saturation (drive → square-up) → RBJ low-pass tone. Knobs: `fuzz`, `tone` | +| `TremoloPedal` | Unipolar sine LFO amplitude modulation. Knobs: `rate`, `depth` | +| `PhaserPedal` | Cascaded all-pass stages swept by a sine LFO. Knobs: `rate`, `feedback` | +| `CompressorPedal` | Feed-forward dynamic range compressor. Knobs: `threshold`, `ratio` | + +Every pedal also inherits the common `mix`, `bypass`, and `level` controls from `Pedal`. + +Write a custom pedal by subclassing `Pedal`, overriding `effect(_:)` to return a mono processed signal, and overriding `effectKnobs` to publish its `@UIParam` knobs. The base class handles wet/dry mixing, bypass, and output gain. + +### `PedalBoard` + +A `PedalBoard` is an ordered collection of pedals. Pedals are appended in signal-flow order with `board.add(pedal)`. A board must be finalised with `shoeGaze.finalizeBoard(board)` before audio flows through it — finalisation wires the signal chain and adds all pedals to the engine. + +### `ShoeGaze` + +`ShoeGaze` owns the `SynthesisEngine` and manages one or more `PedalBoard` instances. The engine lifecycle is caller-owned: `ShoeGaze` itself has no `start()` / `stop()` methods. `ShoeGazeView` provides Start/Stop transport buttons that call `engine.start()` / `engine.stop()`, or the app can drive the engine directly. + +```swift +let shoeGaze = ShoeGaze(engine: engine) +let board = try shoeGaze.addBoard() +try board.add(OverdrivePedal()) +try board.add(DelayPedal()) +try shoeGaze.finalizeBoard(board) +``` + +### Input sources + +Every `PedalBoard` has an `InputSource` that determines what feeds the first pedal in the chain: + +| Source | Description | +|---|---| +| `.testLoop` (default) | Built-in synthesized test signal — no audio hardware input needed | +| `.liveInput(channel:)` | Routes a hardware input channel (zero-based; bus `numOutputChannels + channel`) from the microphone / audio interface | + +The source is set on the `ShoeGaze` manager at init; every board it creates uses it: + +```swift +let shoeGaze = ShoeGaze(engine: engine, inputSource: .liveInput(channel: 0)) +let board = try shoeGaze.addBoard() +``` + +`liveInput` requires `numInputChannels > 0` in the `SynthesisEngine` init and the appropriate OS permission (microphone entitlement on macOS, `NSMicrophoneUsageDescription` in Info.plist for iOS). + +### Recording + +`ShoeGaze` can record the raw **input** and the overall **output** to timestamped WAV +files (via core `DiskOut.Audio`): + +- `ShoeGaze.recordingFolder: URL?` — destination folder (set from the UI's folder picker). +- `ShoeGaze.startRecording() throws` — writes `output-.wav` (stereo hardware + output) and `input-<…>.wav` (the raw input: the hardware input channel for `.liveInput`, + or the first board's head bus for `.testLoop`). Throws `ShoeGazeError.recordingFolderNotSet` + if no folder is set; creates the folder if missing. +- `ShoeGaze.stopRecording()` — removes the taps and flushes/closes the files. +- `ShoeGaze.isRecording: Bool`. + +The record taps are inserted `.after(engine.mainGroup)` so they capture each block's fully +processed bus values. `ShoeGazeView` provides a **Choose Folder…** button and a **Record/Stop** +button (disabled until a folder is chosen). For the cleanest tail of the file, stop the engine +before `stopRecording()` (engine node removal is asynchronous, so the last block or two may be +dropped otherwise). + +### Board selection & crossfade + +By default every board's output sums to the hardware output. To make only one board +audible at a time — switching between them without clicks — use: + +- `ShoeGaze.selectBoard(_ board:, crossfadeSeconds:)` — solo `board`, crossfading the others out. +- `ShoeGaze.selectAllBoards(crossfadeSeconds:)` — restore the summed (all-audible) state. +- `ShoeGaze.activeBoardIndex: Int?` — the soloed board index, or `nil` when all are audible. + +Each board's output master carries a lagged board-select gain (separate from the master +volume knob); `crossfadeSeconds` sets the lag time, so a switch is a click-free crossfade +of that duration (`0` = instant). `ShoeGazeView` exposes an "Active" board picker plus a +crossfade-seconds field driving these calls. + +--- + +## Parallel routing (split / merge) + +Two routing primitives let a signal fan out to two parallel paths and recombine: + +- **`Splitter`** — one input bus → two branch buses, each gated by a click-free, lagged enable (`@UIParam branchAEnabled` / `branchBEnabled`). The `mode: SplitMode` convenience selects `.a` (branch A only), `.b` (branch B only), or `.both` (parallel). A/B switching is click-free. +- **`Merger`** — two branch buses → one output bus, each scaled by `@UIParam levelA` / `levelB`, summed. + +Both are `SynthesizerBase` routing nodes (not `Pedal`s — multi-bus, no wet/dry). They power two layers: + +### Intra-board: a parallel section inside one board + +`PedalBoard.split()` inserts a splitter at the current chain tail and returns a `ParallelSection` with two `BranchChain`s; populate each branch, then `PedalBoard.merge(_:)` sums them back into the chain. Series pedals before and after compose normally. + +```swift +let board = try shoeGaze.addBoard() +try board.add(OverdrivePedal()) // series pre +let section = try board.split() // → splitter +try section.branchA.add(DelayPedal()) // branch A +try section.branchB.add(FuzzPedal()) // branch B +try board.merge(section) // → merger +try board.add(ReverbPedal()) // series post +try shoeGaze.finalizeBoard(board) +section.splitter.mode = .both // run both branches +``` + +Branches use independent buses; the merge node is inserted after both branches so they evaluate first. Node-tree order: `pre → splitter → branch pedals → merger → post`. + +### Inter-board: an A/B chain router + +`ShoeGaze.makeChainRouter()` returns a `ChainRouter` that feeds one shared input through a splitter to **two whole boards** (`boardA` / `boardB`), then a merger + master to the hardware output. `router.mode` toggles which chain is audible (or both). + +```swift +let router = try shoeGaze.makeChainRouter() +try router.boardA.add(OverdrivePedal()) +try router.boardA.add(DelayPedal()) +try router.boardB.add(FuzzPedal()) +try router.boardB.add(ReverbPedal()) +try router.finalize() +router.mode = .a // chain A live; toggle to .b / .both +``` + +The router owns its source, splitter, merger, and master (it does not use the per-board source/master of `addBoard`/`finalizeBoard`). `ChainRouter.teardown()` removes all nodes before releasing buses; `ShoeGaze.teardown()` tears down routers too. + +--- + +## SwiftUI — `LyrebirdShoeGazeUI` + +`LyrebirdShoeGazeUI` provides ready-made SwiftUI views: + +| View | Description | +|---|---| +| `ShoeGazeView(shoeGaze:)` | Top-level view: transport controls + all boards | +| `PedalBoardView(board:)` | Horizontal scroll of `PedalView` tiles for one board | +| `PedalView(pedal:)` | Single pedal tile: bypass toggle + one knob per entry in `pedal.knobs` | +| `SplitterView(splitter:)` | 3-way A / B / Both mode selector + per-branch enable LEDs | +| `MergerView(merger:)` | Branch A / B level knobs | +| `ParallelSectionView(section:)` | Splitter + the two branch pedal rows for an intra-board section | +| `ChainRouterView(router:)` | Splitter + master knob, boards A/B, and the merger for an A/B chain router | +| `BoardEditorView(shoeGaze:boardIndex:versionStore:)` | Auto-laid-out board editor: wrap-to-fit pedal grid + save/load version toolbar | +| `FlowLayout` | A `Layout` that wraps subviews left-to-right to fit the available width (used by the editor) | + +`PedalView` renders the descriptors a pedal publishes via its `knobs: [PedalKnob]` list (effect knobs, then the common `mix` and `level`). A custom pedal gets knobs by overriding `effectKnobs` — no view code is required. + +--- + +## Board versions & auto-layout editor + +`BoardEditorView(shoeGaze:boardIndex:versionStore:)` visualizes one board: its pedals are arranged by `FlowLayout`, a SwiftUI `Layout` that flows pedals left-to-right and wraps to the next row to fit the window width (a real pedalboard look). A toolbar saves and recalls **versions** of the board. + +Backend: +- `PedalBoard.captureState() -> BoardState` snapshots a board (label + each pedal's type + knob/bypass values). +- `ShoeGaze.rebuildBoard(_:from:) throws -> PedalBoard` tears the board down and recreates it from a `BoardState` — recreating pedals via `PedalRegistry` and restoring knob values — **at the same index** in `boards` (unknown pedal types are skipped). Call with the engine stopped (same async-removal caveat as `teardown`). +- `BoardVersionStore` (`@Observable`) holds named `BoardVersion`s (`id`, `name`, `savedAt`, `state`) in memory and persists them as JSON: + - `capture(board, name:)` snapshots the current board. + - `writeAllToDisk(in:)` / `loadAllFromDisk(in:)` round-trip versions to a directory (`BoardVersionStore.defaultDirectory()` = `/LyrebirdShoeGaze/ShoeGazeVersions/`). + +```swift +let store = BoardVersionStore() +store.capture(board, name: "Crunch rhythm") // snapshot current knobs +try store.writeAllToDisk(in: BoardVersionStore.defaultDirectory()) +// later — recall, rebuilding the board from the saved version: +_ = try shoeGaze.rebuildBoard(board, from: store.versions[0].state) +``` + +In the UI, "Save Version" snapshots the live board, the Versions menu loads one (rebuilding in place), and Save/Load-to-disk persist the set. Because `ShoeGaze` and `BoardVersionStore` are `@Observable`, the editor re-renders automatically after a capture or rebuild. + +--- + +## Demo apps + +The package ships two in-repo demo apps in the workspace — a macOS app and an iOS app. +Both live under `ShoeGaze/Demo/` and share the same workspace: + +```sh +open ShoeGaze/ShoeGaze.xcworkspace +``` + +The workspace contains three entries: the `ShoeGaze` SwiftPM package (library targets), +`Demo/ShoeGazeDemo.xcodeproj` (macOS), and `Demo/ShoeGazeiOSDemo.xcodeproj` (iOS). Xcode +resolves the two local package references (`..` for `LyrebirdShoeGaze`/`LyrebirdShoeGazeUI`, +`../..` for `Lyrebird`/`LyrebirdUI`) automatically when you first open the workspace. + +### `ShoeGazeDemo` (macOS) + +Showcases every feature via a mode picker (Boards / Editor / Parallel / Router), an input +dropdown, transport, and the board selector + crossfade. Build & Run produces `ShoeGazeDemo.app` +with a full menu bar — **Quit ⌘Q**, **Audio ▸ Mute ⌘M** (checkmark while muted): + +```sh +open ShoeGaze/ShoeGaze.xcworkspace # select the "ShoeGazeDemo" scheme → Run +``` + +### `ShoeGazeiOSDemo` (iPhone + iPad) + +A minimal iOS app wrapping `ShoeGazeView` in a `NavigationStack` + `ScrollView` so the +pedalboard scrolls on compact screens. Shows a default board (Overdrive → Delay → Reverb → +Modulation) fed by the built-in `.testLoop` source — no microphone permission required. + +To run: + +1. Open `ShoeGaze/ShoeGaze.xcworkspace` in Xcode. +2. Select the **ShoeGazeiOSDemo** scheme. +3. Pick an iPhone or iPad simulator (or a physical device with a provisioning profile). +4. Click **Run**. + +The app uses `AVAudioSession` to read the hardware sample rate at launch, so pitch and timing +are accurate on all devices. To switch to live microphone input: set +`numInputChannels: 1` and `.playAndRecord` in `ShoeGazeiOSDemoAppModel.swift`, then pass +`.liveInput(channel: 0)` to the `ShoeGaze` init. + +Note: the CLI `lyrebird new --template shoegaze` / `--template shoegaze-ios` (below) is still +the way to scaffold your OWN app project. The demo apps are in-repo only. + +--- + +## `lyrebird new --template shoegaze` Workflow (macOS Xcode app) + +```sh +lyrebird new MyRig --template shoegaze \ + --lyrebird-path /path/to/LyrebirdII \ + --shoegaze-path /path/to/LyrebirdII/ShoeGaze +``` + +Generates a full `.xcodeproj` macOS application (macOS 15+): + +``` +MyRig/ +├── MyRig.xcodeproj/ +│ ├── project.pbxproj +│ └── xcshareddata/xcschemes/MyRig.xcscheme +├── MyRig.xcworkspace/ +│ └── contents.xcworkspacedata (references MyRig.xcodeproj) +└── MyRig/ + ├── Info.plist (NSMicrophoneUsageDescription pre-wired) + ├── MyRigApp.swift (@main SwiftUI App — ShoeGazeView root + Mute menu) + └── MyRigAppModel.swift (@Observable model — engine + ShoeGaze) +``` + +Open `MyRig.xcworkspace` in Xcode and run. The generated app: + +- Wires `CoreAudioDriver` at 48 000 Hz with 256 audio buses. +- Builds a default board (Overdrive → Delay → Reverb → Modulation) with the `.testLoop` input source. +- Exposes an **Audio ▸ Mute ⌘M** command (stops/starts the engine). +- Ships `NSMicrophoneUsageDescription` in `Info.plist` so switching to `.liveInput` doesn't require an extra plist edit. +- `ShoeGazeView` already provides Choose Folder / Record / Stop recording controls. + +Key differences between the macOS and iOS shoegaze templates: + +| | `shoegaze` (macOS Xcode) | `shoegaze-ios` (iOS Xcode) | +|---|---|---| +| Project type | `.xcodeproj` app bundle | `.xcodeproj` app bundle | +| Driver | `CoreAudioDriver` | `iOSAudioDriver` | +| Session | — | `AVAudioSession(.playback)` | +| Entry point | SwiftUI `@main App` | SwiftUI `@main App` | +| Window sizing | `.frame(minWidth:minHeight:)` | device-fill, no min size | +| Menu | Audio ▸ Mute ⌘M | — | + +### `--shoegaze-path` + +ShoeGaze is not yet published at a stable remote URL. Passing `--shoegaze-path ` wires it as an `XCLocalSwiftPackageReference` in the generated `.xcodeproj`. If you omit the flag, the pbxproj uses a placeholder URL (`https://github.com/realizedsound/LyrebirdShoeGaze`) — edit `project.pbxproj` or re-generate once ShoeGaze is published. + +The placeholder URL is stored in `ProjectScaffolder.shoegazePackageURL`. + +### Live audio input on macOS + +The generated template uses `.testLoop` and `numInputChannels: 0`. To switch to microphone or audio interface input: + +1. Change `numInputChannels: 0` to the desired channel count in `MyRigAppModel.swift`. +2. Change `ShoeGaze(engine: eng)` to `ShoeGaze(engine: eng, inputSource: .liveInput(channel: 0))`. +3. `NSMicrophoneUsageDescription` is already in `Info.plist` — update the string to describe your use case. +4. If running under App Sandbox, add `com.apple.security.device.audio-input` to the `.entitlements` file. The `shoegaze` template is unsandboxed by default (Hardened Runtime without sandbox), so no entitlement file is needed in the common development workflow. + +--- + +## `lyrebird new --template shoegaze-ios` Workflow (iOS) + +```sh +lyrebird new MyRig --template shoegaze-ios \ + --lyrebird-path /path/to/LyrebirdII \ + --shoegaze-path /path/to/LyrebirdII/ShoeGaze +``` + +Generates a full `.xcodeproj` iOS application (iPhone + iPad, iOS 18+): + +``` +MyRig/ +├── MyRig.xcodeproj/ +│ ├── project.pbxproj +│ └── xcshareddata/xcschemes/MyRig.xcscheme +├── MyRig.xcworkspace/ +│ └── contents.xcworkspacedata (references MyRig.xcodeproj) +└── MyRig/ + ├── Info.plist + ├── MyRigApp.swift (@main SwiftUI App — ShoeGazeView root) + └── MyRigAppModel.swift (@Observable model — engine + ShoeGaze) +``` + +Open `MyRig.xcworkspace` in Xcode, select an iPhone/iPad simulator or device, and run. The generated app: + +- Activates `AVAudioSession(.playback)` and queries the hardware sample rate at init so pitch and timing are accurate on all devices. +- Builds a default board (Overdrive → Delay → Reverb → Modulation) with the `.testLoop` input source. +- Wraps `ShoeGazeView` in a `NavigationStack` + `ScrollView` for compact-screen compatibility. + +Key differences from the macOS `shoegaze` template: + +| | `shoegaze` (macOS Xcode) | `shoegaze-ios` (iOS Xcode) | +|---|---|---| +| Project type | `.xcodeproj` app bundle | `.xcodeproj` app bundle | +| Driver | `CoreAudioDriver` | `iOSAudioDriver` | +| Session | — | `AVAudioSession(.playback)` | +| Entry point | SwiftUI `@main App` | SwiftUI `@main App` | +| Window sizing | `.frame(minWidth:minHeight:)` | device-fill, no min size | +| Menu | Audio ▸ Mute ⌘M | — | + +### Live audio input on iOS + +The generated template uses `.testLoop` and `numInputChannels: 0`. To switch to microphone input: + +1. Change `numInputChannels: 0` to `numInputChannels: 1` in `MyRigAppModel.swift`. +2. Change `.playback` to `.playAndRecord` (mode: `.default`, options: `[.defaultToSpeaker]`) in the `AVAudioSession` setup. +3. Add `NSMicrophoneUsageDescription` to `Info.plist` (required for App Store submission and the system permission prompt). +4. Change `ShoeGaze(engine: eng)` to `ShoeGaze(engine: eng, inputSource: .liveInput(channel: 0))`. + +--- + +## Extending the starter app + +- Add more pedals in `applicationDidFinishLaunching` with additional `board.add(...)` calls. +- Create a second board with `shoeGaze.addBoard()` — `ShoeGazeView` shows all boards. +- Write a custom pedal: subclass `Pedal`, override `effect(_:)` (return a mono signal) and `effectKnobs`. The base class handles wet/dry, bypass, and level; `PedalView` picks up the knobs automatically. +- Switch to live audio: construct `ShoeGaze(engine:, inputSource: .liveInput(channel: 0))` and set `numInputChannels` ≥ 1 in the engine init (plus the microphone entitlement / `NSMicrophoneUsageDescription`). diff --git a/docs/tooling/cli-guide.md b/docs/tooling/cli-guide.md index 977396f..7ac91b5 100644 --- a/docs/tooling/cli-guide.md +++ b/docs/tooling/cli-guide.md @@ -85,12 +85,16 @@ lyrebird new 1stPiece # error: not a valid Swift module name **Templates** — `--template `: - SPM-only (open `Package.swift` in Xcode): `basic` (default), `demo`, `ui-demo`, `nrt`, `score` -- Xcode-project (ships `.xcodeproj` + `.xcworkspace`): `macos-ui-xcode`, `ios-ui`, `auv3` +- Xcode-project (ships `.xcodeproj` + `.xcworkspace`, builds to `.app` or `.appex`): `shoegaze`, `shoegaze-ios`, `macos-ui-xcode`, `ios-ui`, `auv3` ```sh lyrebird new MyApp --template macos-ui-xcode # macOS .app lyrebird new MyApp --template ios-ui # iOS .app lyrebird new MyPlugin --template auv3 # AUv3 host + .appex +lyrebird new MyRig --template shoegaze \ + --shoegaze-path /path/to/ShoeGaze # macOS guitar pedalboard (.xcodeproj, .app) +lyrebird new MyRig --template shoegaze-ios \ + --shoegaze-path /path/to/ShoeGaze # iOS guitar pedalboard (.xcodeproj, .app) ``` **Local Lyrebird checkout** — `--lyrebird-path ` makes the generated project depend on a local Lyrebird checkout (via `.package(name: "Lyrebird", path: ...)` in `Package.swift`, `XCLocalSwiftPackageReference` in `.xcodeproj`). Use while the published repo URL isn't yet accessible: @@ -100,7 +104,15 @@ lyrebird new MyApp --template macos-ui-xcode \ --lyrebird-path /Users/me/Documents/LyrebirdII ``` -See `docs/tooling/project-system.md` for the layout each template emits. +**Local ShoeGaze checkout** — `--shoegaze-path ` (shoegaze / shoegaze-ios templates) wires the `LyrebirdShoeGaze` package as a local SPM dependency. Omitting this flag emits a placeholder remote URL in the generated project; edit it or re-run with `--shoegaze-path` once ShoeGaze is published. The placeholder URL is `ProjectScaffolder.shoegazePackageURL`. + +```sh +lyrebird new MyRig --template shoegaze-ios \ + --lyrebird-path /Users/me/Documents/LyrebirdII \ + --shoegaze-path /Users/me/Documents/LyrebirdII/ShoeGaze +``` + +See `docs/tooling/project-system.md` for the layout each template emits. See `docs/stdlib/shoegaze.md` for the ShoeGaze package concepts and workflow. If the directory already exists, the command fails cleanly and leaves the filesystem unchanged. diff --git a/docs/tooling/project-system.md b/docs/tooling/project-system.md index 6579120..3bc4e22 100644 --- a/docs/tooling/project-system.md +++ b/docs/tooling/project-system.md @@ -48,9 +48,11 @@ Xcode-project templates (ship a real `.xcodeproj` for deliverables SwiftPM can't | Template | Command | Description | |---|---|---| +| `shoegaze` | `lyrebird new MyRig --template shoegaze --shoegaze-path ` | macOS guitar-pedalboard `.app` (Xcode, SwiftUI `@main`). Generates a full `.xcodeproj` with a `ShoeGazeView` root view, an `@Observable` app model wiring `CoreAudioDriver` + `ShoeGaze`, and an **Audio ▸ Mute ⌘M** menu command. `NSMicrophoneUsageDescription` pre-wired for `.liveInput`. Default board: Overdrive→Delay→Reverb→Modulation fed by the built-in test loop. Requires `--shoegaze-path` until `LyrebirdShoeGaze` is published | | `macos-ui-xcode` | `lyrebird new MyApp --template macos-ui-xcode` | macOS `.app` (AppKit + SwiftUI), `@UIParam` synth, hardened runtime | | `ios-ui` | `lyrebird new MyApp --template ios-ui` | iOS `.app` (SwiftUI + `iOSAudioDriver`), `AVAudioSession` activation, iPhone + iPad device family | | `auv3` | `lyrebird new MyPlugin --template auv3` | AUv3 host `.app` + `aumu` `.appex` subclassing `LyrebirdAudioUnit`. Entitlements for both. Subtype + manufacturer pre-filled (manufacturer = `LYRB` placeholder — rewrite for distribution) | +| `shoegaze-ios` | `lyrebird new MyRig --template shoegaze-ios --shoegaze-path ` | iOS guitar-pedalboard `.app` (SwiftUI + `iOSAudioDriver`). Generates a full `.xcodeproj` with a `ShoeGazeView` root view and an `@Observable` app model wiring `AVAudioSession` + `ShoeGaze`. Default board: Overdrive→Delay→Reverb→Modulation fed by the built-in test loop. Adds `LyrebirdShoeGaze` + `LyrebirdShoeGazeUI` to the project's SPM deps. Requires `--shoegaze-path` until `LyrebirdShoeGaze` is published | Each Xcode-project template lays out: diff --git a/docs/tooling/xcode-templates.md b/docs/tooling/xcode-templates.md index 03b4440..9517d96 100644 --- a/docs/tooling/xcode-templates.md +++ b/docs/tooling/xcode-templates.md @@ -108,6 +108,17 @@ All six Tier 3 templates compile in projects depending on Lyrebird as a Swift Package and are reported as `OK (external)` by the validator. None require LyrebirdUI. +### Tier 4 — sample-project templates (ShoeGaze) + +| Template | Generates | Use when | +|---|---|---| +| **ShoeGaze Pedal** | `final class : Pedal` with an `@UIParam` knob, a stubbed `effect(_:)` returning the processed mono signal, and an `effectKnobs` override publishing its knobs | Adding a new guitar pedal to a project using the ShoeGaze sample package. The base `Pedal` handles wet/dry `mix`, click-free `bypass`, and `level`; `PedalView` renders the published knobs. | + +The ShoeGaze Pedal template requires the **LyrebirdShoeGaze** package (it imports +`LyrebirdShoeGaze` and `LyrebirdUI`), not just core Lyrebird. Use it inside a +project scaffolded with `lyrebird new --template shoegaze`, or any target that +depends on the ShoeGaze package. See [`../stdlib/shoegaze.md`](../stdlib/shoegaze.md). + Each template prompts for a name in Xcode's dialog. The name becomes both the file name and the top-level identifier inside the file.