Compare commits
3 Commits
09fa4e8d4b
...
ed3283f645
| Author | SHA1 | Date | |
|---|---|---|---|
| ed3283f645 | |||
| 8983e8829e | |||
| e697789bd7 |
@@ -163,7 +163,7 @@
|
||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 12;
|
||||
CURRENT_PROJECT_VERSION = 14;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
@@ -175,7 +175,7 @@
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MARKETING_VERSION = 2.1.4;
|
||||
MARKETING_VERSION = 2.1.6;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
@@ -193,7 +193,7 @@
|
||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 12;
|
||||
CURRENT_PROJECT_VERSION = 14;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = ShoeGazeBuilder/Info.plist;
|
||||
@@ -204,7 +204,7 @@
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MARKETING_VERSION = 2.1.4;
|
||||
MARKETING_VERSION = 2.1.6;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"originHash" : "2a63dcbef74c280c7062a8342821f694fd71a59d391c302b86b3b86b00481260",
|
||||
"originHash" : "9365abc9e3bf41483a03dca1c6be0421a5ca41bff1a9db33c8ddc62b2de04ef1",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
@@ -15,8 +15,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||
"state" : {
|
||||
"revision" : "63d6e0746fdedce626c9eff832e799bad949708e",
|
||||
"version" : "1.2.4"
|
||||
"revision" : "d6875da2cb6628c4274454dd55a632dd76212759",
|
||||
"version" : "1.6.4"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ let package = Package(
|
||||
.library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.6.3"),
|
||||
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.6.4"),
|
||||
],
|
||||
targets: [
|
||||
// The core target depends on LyrebirdUI as well as the synthesis core:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"originHash" : "4c33c107b780400f6ccd69fd1203a485fca3ff6a90f93c3aad40bd403ef33702",
|
||||
"originHash" : "6963980dd14bc118dfae577e57517f2776cb0d010d7b4ae798bdb57e4f0d2cb7",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
@@ -15,8 +15,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||
"state" : {
|
||||
"revision" : "5e6534a615af6c075fc539e909cef3a63b038ced",
|
||||
"version" : "1.6.3"
|
||||
"revision" : "d6875da2cb6628c4274454dd55a632dd76212759",
|
||||
"version" : "1.6.4"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
// OversampledRingModulator.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import Darwin
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load. Returned when an upstream
|
||||
/// input yields no channel for a `_computeSamples` call, so the RT path never allocates.
|
||||
private let oversampledRingModZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// Ring modulator (`input × sine carrier`) evaluated at 2× or 4× the engine sample rate.
|
||||
///
|
||||
/// A ring modulator's product produces sum-and-difference sidebands at `f_in ± f_carrier`. The
|
||||
/// sum sideband can land above the engine Nyquist and fold back as an inharmonic alias —
|
||||
/// worst with a high carrier and bright input. Evaluating the multiply at an oversampled rate
|
||||
/// (the input upsampled through a halfband FIR, the carrier generated directly at the
|
||||
/// oversampled rate) pushes the sum term below the upsampled Nyquist, then the matching
|
||||
/// downsampler filters it out before returning to the engine rate.
|
||||
///
|
||||
/// Output is mono (channel 0 of the input is used).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to modulate.
|
||||
/// - freq: Carrier frequency in Hz. Read once per block. Defaults to `220.0`.
|
||||
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`.
|
||||
public final class OversampledRingModulator: GeneratorBase, AudioGenerator {
|
||||
|
||||
/// Resolved input signal (classified once at `init`, never on the RT thread).
|
||||
private let inputSource: any ValidGeneratorInput
|
||||
|
||||
/// Resolved carrier-frequency control. Read once per block.
|
||||
private let freqInput: any ValidGeneratorInput
|
||||
|
||||
/// Oversampling factor — `2` or `4`, fixed at init.
|
||||
private let oversampleFactor: Int
|
||||
|
||||
/// Carrier phase in radians, advanced at the oversampled rate and wrapped to `[0, 2π)`.
|
||||
private var phase: Double = 0.0
|
||||
|
||||
/// 2× halfband oversampling state (used when `oversampleFactor == 2`).
|
||||
private var upsampler2x: HalfbandUpsampler2x
|
||||
private var downsampler2x: HalfbandDownsampler2x
|
||||
|
||||
/// 4× halfband oversampling state (used when `oversampleFactor == 4`).
|
||||
private var upsampler4x: HalfbandUpsampler4x
|
||||
private var downsampler4x: HalfbandDownsampler4x
|
||||
|
||||
private let twoPi: Double = 2.0 * Double.pi
|
||||
|
||||
/// Creates an oversampled ring modulator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to modulate.
|
||||
/// - freq: Carrier frequency in Hz. Read once per block. Defaults to `220.0`.
|
||||
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`.
|
||||
public init(
|
||||
_ input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput = 220.0,
|
||||
oversample: Int = 2
|
||||
) {
|
||||
precondition(
|
||||
oversample == 2 || oversample == 4,
|
||||
"OversampledRingModulator: oversample must be 2 or 4"
|
||||
)
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
|
||||
inputSource = resolvedInput
|
||||
freqInput = resolvedFreq
|
||||
oversampleFactor = oversample
|
||||
upsampler2x = HalfbandUpsampler2x()
|
||||
downsampler2x = HalfbandDownsampler2x()
|
||||
upsampler4x = HalfbandUpsampler4x()
|
||||
downsampler4x = HalfbandDownsampler4x()
|
||||
super.init()
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let input: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first
|
||||
?? oversampledRingModZeroBlock
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
// A degenerate sample rate would make phaseInc NaN/Inf and latch NaN into the
|
||||
// persisted phase; zero-fill and bail, matching MoogLadder's guard.
|
||||
guard sr >= 1.0 else {
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<count { dstP[i] = 0 }
|
||||
}
|
||||
return _result
|
||||
}
|
||||
let freq: Double = freqInput.floatValue(graph: graph)
|
||||
let inCount: Int = input.count
|
||||
let useFourX: Bool = oversampleFactor == 4
|
||||
// Phase increment per oversampled sample.
|
||||
let factor: Double = useFourX ? 4.0 : 2.0
|
||||
let phaseInc: Double = twoPi * freq / (sr * factor)
|
||||
|
||||
var localPhase: Double = phase
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
if useFourX {
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? input[i] : 0
|
||||
let (a, b, c, d) = upsampler4x.process(x)
|
||||
let ya: Double = a * sin(localPhase); localPhase += phaseInc
|
||||
let yb: Double = b * sin(localPhase); localPhase += phaseInc
|
||||
let yc: Double = c * sin(localPhase); localPhase += phaseInc
|
||||
let yd: Double = d * sin(localPhase); localPhase += phaseInc
|
||||
// Wrap both directions — a negative carrier frequency drives phaseInc
|
||||
// negative, so an upward-only wrap would let the phase grow unbounded.
|
||||
if localPhase >= twoPi || localPhase < 0 {
|
||||
localPhase = localPhase.truncatingRemainder(dividingBy: twoPi)
|
||||
if localPhase < 0 { localPhase += twoPi }
|
||||
}
|
||||
dstP[i] = downsampler4x.process(ya, yb, yc, yd)
|
||||
}
|
||||
} else {
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? input[i] : 0
|
||||
let (a, b) = upsampler2x.process(x)
|
||||
let ya: Double = a * sin(localPhase); localPhase += phaseInc
|
||||
let yb: Double = b * sin(localPhase); localPhase += phaseInc
|
||||
// Wrap both directions (see 4× branch).
|
||||
if localPhase >= twoPi || localPhase < 0 {
|
||||
localPhase = localPhase.truncatingRemainder(dividingBy: twoPi)
|
||||
if localPhase < 0 { localPhase += twoPi }
|
||||
}
|
||||
dstP[i] = downsampler2x.process(ya, yb)
|
||||
}
|
||||
}
|
||||
}
|
||||
phase = localPhase
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// OversampledSaturator.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load. Returned when an upstream
|
||||
/// input yields no channel for a `_computeSamples` call, so the RT path never allocates.
|
||||
private let oversampledSaturatorZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// A waveshaping saturator that evaluates its nonlinearity at 2× or 4× the engine sample
|
||||
/// rate to keep the harmonics it generates from folding back into the audible band as
|
||||
/// aliasing.
|
||||
///
|
||||
/// A hard or steep nonlinearity (`tanh` driven hard, a hard clipper) produces harmonics well
|
||||
/// above the engine Nyquist. Evaluated at the base rate those harmonics alias — an
|
||||
/// inharmonic, buzzy "crackle" that gets worse the louder and brighter the input and the
|
||||
/// harder the drive. This generator upsamples the input, applies the ``SaturationCurve``
|
||||
/// per oversampled sample, then downsamples with the matching halfband FIR, so the aliased
|
||||
/// content is filtered out before returning to the engine rate.
|
||||
///
|
||||
/// Linear stages (DC-block high-pass, tone low-pass, output trim) do **not** alias and should
|
||||
/// stay as ordinary graph nodes around this one — only the nonlinearity needs oversampling.
|
||||
///
|
||||
/// Output is mono (channel 0 of the input is used).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to saturate.
|
||||
/// - drive: Drive amount fed to the curve. Clamped to a small positive floor. Defaults to `1.0`.
|
||||
/// - curve: The ``SaturationCurve`` to apply per oversampled sample.
|
||||
/// - oversample: Oversampling factor — `2` or `4`. Use `4` for hard-clipping curves whose
|
||||
/// harmonics extend furthest; `2` is enough for `tanh`-family soft saturation. Defaults to `2`.
|
||||
public final class OversampledSaturator: GeneratorBase, AudioGenerator {
|
||||
|
||||
/// Resolved input signal (classified once at `init`, never on the RT thread).
|
||||
private let inputSource: any ValidGeneratorInput
|
||||
|
||||
/// Resolved drive control. Read once per block.
|
||||
private let driveInput: any ValidGeneratorInput
|
||||
|
||||
/// The waveshaping curve applied per oversampled sample.
|
||||
private let curve: SaturationCurve
|
||||
|
||||
/// Oversampling factor — `2` or `4`, fixed at init.
|
||||
private let oversampleFactor: Int
|
||||
|
||||
/// Lower bound on drive so `softClipNormalized`'s `tanh(drive)` denominator is never zero.
|
||||
private let minDrive: Double = 1.0e-4
|
||||
|
||||
/// 2× halfband oversampling state (used when `oversampleFactor == 2`).
|
||||
private var upsampler2x: HalfbandUpsampler2x
|
||||
private var downsampler2x: HalfbandDownsampler2x
|
||||
|
||||
/// 4× halfband oversampling state (used when `oversampleFactor == 4`).
|
||||
private var upsampler4x: HalfbandUpsampler4x
|
||||
private var downsampler4x: HalfbandDownsampler4x
|
||||
|
||||
/// Creates an oversampled saturator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to saturate.
|
||||
/// - drive: Drive amount fed to the curve. Clamped to a small positive floor. Defaults to `1.0`.
|
||||
/// - curve: The ``SaturationCurve`` to apply per oversampled sample.
|
||||
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`.
|
||||
public init(
|
||||
_ input: any ValidGeneratorInput,
|
||||
drive: any ValidGeneratorInput = 1.0,
|
||||
curve: SaturationCurve,
|
||||
oversample: Int = 2
|
||||
) {
|
||||
precondition(
|
||||
oversample == 2 || oversample == 4,
|
||||
"OversampledSaturator: oversample must be 2 or 4"
|
||||
)
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedDrive: any ValidGeneratorInput = drive._resolvedInput()
|
||||
inputSource = resolvedInput
|
||||
driveInput = resolvedDrive
|
||||
self.curve = curve
|
||||
oversampleFactor = oversample
|
||||
upsampler2x = HalfbandUpsampler2x()
|
||||
downsampler2x = HalfbandDownsampler2x()
|
||||
upsampler4x = HalfbandUpsampler4x()
|
||||
downsampler4x = HalfbandDownsampler4x()
|
||||
super.init()
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let input: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first
|
||||
?? oversampledSaturatorZeroBlock
|
||||
let driveRaw: Double = driveInput.floatValue(graph: graph)
|
||||
let drive: Double = Swift.max(minDrive, driveRaw)
|
||||
let inCount: Int = input.count
|
||||
let useFourX: Bool = oversampleFactor == 4
|
||||
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
if useFourX {
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? input[i] : 0
|
||||
let (a, b, c, d) = upsampler4x.process(x)
|
||||
dstP[i] = downsampler4x.process(
|
||||
curve.apply(a, drive: drive),
|
||||
curve.apply(b, drive: drive),
|
||||
curve.apply(c, drive: drive),
|
||||
curve.apply(d, drive: drive)
|
||||
)
|
||||
}
|
||||
} else {
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? input[i] : 0
|
||||
let (a, b) = upsampler2x.process(x)
|
||||
dstP[i] = downsampler2x.process(
|
||||
curve.apply(a, drive: drive),
|
||||
curve.apply(b, drive: drive)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// SaturationCurve.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
|
||||
/// The waveshaping curve applied per (oversampled) sample by ``OversampledSaturator``.
|
||||
///
|
||||
/// Each case reproduces the nonlinearity a specific drive pedal used to build inline from
|
||||
/// stock generators, so moving that pedal onto the oversampled path is voicing-preserving:
|
||||
///
|
||||
/// - `tanhPreGain` — `tanh(drive · x)`. Symmetric soft saturation with the drive applied
|
||||
/// *before* the `tanh` (the fuzz voicing: hard pre-gain squares the wave off).
|
||||
/// - `softClipNormalized` — `tanh(drive · x) / tanh(drive)`. The same curve normalised so a
|
||||
/// unity-drive signal passes near-linearly (the overdrive voicing).
|
||||
/// - `tanhPostGainHardClip(low:high:)` — `clip(tanh(x) · drive, low, high)`. A gentle `tanh`
|
||||
/// stage, post-gained by drive into a hard clipper (the distortion voicing). The hard clip
|
||||
/// is the dominant harmonic source and the reason this curve wants the highest oversampling
|
||||
/// factor.
|
||||
public enum SaturationCurve: Sendable {
|
||||
case tanhPreGain
|
||||
case softClipNormalized
|
||||
case tanhPostGainHardClip(low: Double, high: Double)
|
||||
|
||||
/// Applies the curve to a single sample.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x: Input sample (already at the oversampled rate).
|
||||
/// - drive: Drive amount. The caller clamps this to a small positive floor so
|
||||
/// `softClipNormalized`'s `tanh(drive)` denominator is never zero.
|
||||
/// - Returns: The shaped sample.
|
||||
@inline(__always)
|
||||
func apply(_ x: Double, drive: Double) -> Double {
|
||||
switch self {
|
||||
case .tanhPreGain:
|
||||
return tanh(drive * x)
|
||||
case .softClipNormalized:
|
||||
return tanh(drive * x) / tanh(drive)
|
||||
case .tanhPostGainHardClip(let low, let high):
|
||||
let shaped: Double = tanh(x) * drive
|
||||
return Swift.min(high, Swift.max(low, shaped))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,12 @@ import LyrebirdUI
|
||||
/// compressed. Range `[-40, 0]` dB. Defaults to `-12.0`.
|
||||
/// - ratio: Compression ratio `≥ 1.0`. `1.0` = bypass, `4.0` = 4:1 compression.
|
||||
/// Range `[1, 20]`. Defaults to `4.0`.
|
||||
///
|
||||
/// A feed-forward compressor can overshoot on fast transients (its attack is non-zero),
|
||||
/// so a hot input plus makeup gain can push peaks past full scale and clip the output.
|
||||
/// The **Safety** switch inserts a brick-wall `LookAheadLimiter` after the compressor to
|
||||
/// catch those peaks; it is off by default (leave adding a limiter to the user) and adds
|
||||
/// a short look-ahead output delay when engaged.
|
||||
public final class CompressorPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
@@ -50,6 +56,10 @@ public final class CompressorPedal: Pedal {
|
||||
/// Compression ratio. Range [1, 20].
|
||||
@UIParam public var ratio: Double = 4.0
|
||||
|
||||
/// Safety limiter engage state. `0` = off (compressor may overshoot), `1` = on
|
||||
/// (brick-wall look-ahead limiter catches transient peaks).
|
||||
@UIParam public var safetyLimiter: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — fully wet; the compressor is inserted in-line.
|
||||
@@ -71,6 +81,20 @@ public final class CompressorPedal: Pedal {
|
||||
/// Makeup gain in dB applied after compression to restore perceived loudness.
|
||||
private let makeupGainDB: Double = 4.0
|
||||
|
||||
/// Safety-limiter peak ceiling (linear amplitude), just below full scale.
|
||||
private let safetyCeiling: Double = 0.98
|
||||
|
||||
/// Safety-limiter look-ahead / output delay in seconds. Short enough to catch
|
||||
/// transients without smearing attack; only in circuit when Safety is engaged.
|
||||
private let safetyLookAheadTime: Double = 0.005
|
||||
|
||||
/// Safety-limiter gain-release time in seconds.
|
||||
private let safetyReleaseTime: Double = 0.05
|
||||
|
||||
/// Safety switch position values.
|
||||
private let safetyOffValue: Double = 0.0
|
||||
private let safetyOnValue: Double = 1.0
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Input-gain knob range in dB.
|
||||
@@ -90,6 +114,19 @@ public final class CompressorPedal: Pedal {
|
||||
]
|
||||
}
|
||||
|
||||
public override var effectSwitches: [PedalSwitch] {
|
||||
[
|
||||
PedalSwitch(
|
||||
label: "Safety",
|
||||
node: $safetyLimiter,
|
||||
options: [
|
||||
PedalSwitch.Option(title: "Off", value: safetyOffValue),
|
||||
PedalSwitch.Option(title: "On", value: safetyOnValue),
|
||||
]
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a compressor pedal.
|
||||
@@ -121,7 +158,7 @@ public final class CompressorPedal: Pedal {
|
||||
// Convert the input-gain dB to a linear multiplier (10^(dB/20)) and apply before compression.
|
||||
let inputGainLinear: Exp.Audio = Exp.Audio($inputGain * dbToLinExpScale)
|
||||
let boosted: any ValidGeneratorInput = dry * inputGainLinear
|
||||
return Compressor.Audio(
|
||||
let compressed: Compressor.Audio = Compressor.Audio(
|
||||
in: boosted,
|
||||
threshold: $threshold,
|
||||
ratio: $ratio,
|
||||
@@ -130,5 +167,18 @@ public final class CompressorPedal: Pedal {
|
||||
kneeWidth: kneeWidth,
|
||||
makeupGain: makeupGainDB
|
||||
)
|
||||
// Brick-wall safety limiter after the compressor. Both branches are always built;
|
||||
// `Select` picks per the Safety switch (0 = compressor only, 1 = limited).
|
||||
let limited: LookAheadLimiter = LookAheadLimiter(
|
||||
in: compressed,
|
||||
maxAmplitude: safetyCeiling,
|
||||
lookAheadTime: safetyLookAheadTime,
|
||||
releaseTime: safetyReleaseTime,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
return Select.Audio(
|
||||
which: $safetyLimiter,
|
||||
inputs: [compressed, limited]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,9 +9,10 @@ import LyrebirdUI
|
||||
|
||||
/// Mid-gain distortion — more saturated than `OverdrivePedal`, more controlled than `FuzzPedal`.
|
||||
///
|
||||
/// A DC-blocking high-pass feeds a `tanh` soft-clipper driven hard by the `Drive` knob; a
|
||||
/// post-clip low-pass `Tone` control tames the harmonics, and a final hard clip guarantees the
|
||||
/// output stays bounded.
|
||||
/// A DC-blocking high-pass feeds a `tanh` stage that is post-gained by the `Drive` knob into a
|
||||
/// hard clipper — both evaluated at 4× oversampling so the clipper's harmonics don't alias. A
|
||||
/// post-clip low-pass `Tone` control tames the harmonics, and a final hard clip re-bounds the
|
||||
/// output (the tone low-pass can ring slightly past the ceiling on transients).
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `drive`: Pre-clip gain into the `tanh` stage. Range `[1, 50]`.
|
||||
@@ -87,12 +88,24 @@ public final class DistortionPedal: Pedal {
|
||||
freq: dcBlockFreq,
|
||||
q: filterQ
|
||||
)
|
||||
let driven: Tanh.Audio = Tanh.Audio(dcBlocked, mul: $drive)
|
||||
// tanh soft stage → post-gain by drive → hard clip, all evaluated at 4× so the hard
|
||||
// clipper's harmonics settle above the upsampled Nyquist instead of aliasing back.
|
||||
// The tone low-pass now follows the clip (standard clip→tone order), which also
|
||||
// filters any residual high-band content the downsampler leaves.
|
||||
let clipped: OversampledSaturator = OversampledSaturator(
|
||||
dcBlocked,
|
||||
drive: $drive,
|
||||
curve: .tanhPostGainHardClip(low: clipLow, high: clipHigh),
|
||||
oversample: 4
|
||||
)
|
||||
let toned: RBJLowPass.Audio = RBJLowPass.Audio(
|
||||
input: driven,
|
||||
input: clipped,
|
||||
freq: $tone,
|
||||
q: filterQ
|
||||
)
|
||||
// Final hard clip re-establishes the strict output bound: the tone low-pass is linear
|
||||
// and band-limited, so it can overshoot the ceiling slightly on transients, but
|
||||
// clipping its (already band-limited) output adds negligible new aliasing.
|
||||
return Clip.Audio(toned, lo: clipLow, hi: clipHigh)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,11 +105,17 @@ public final class FuzzPedal: Pedal {
|
||||
/// - Returns: Fuzzed and tone-shaped mono output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
// Pre-gain the signal hard, then saturate. `tanh` squares the waveform off as the
|
||||
// drive rises while keeping the level bounded — the hallmark of a fuzz.
|
||||
let driven: any ValidGeneratorInput = dry * $fuzz
|
||||
let saturated: Tanh.Audio = Tanh.Audio(driven, mul: outputTrim)
|
||||
// drive rises while keeping the level bounded — the hallmark of a fuzz. Evaluated at
|
||||
// 2× so the high harmonics the hard pre-gain generates don't fold back as aliasing.
|
||||
let saturated: OversampledSaturator = OversampledSaturator(
|
||||
dry,
|
||||
drive: $fuzz,
|
||||
curve: .tanhPreGain,
|
||||
oversample: 2
|
||||
)
|
||||
let trimmed: any ValidGeneratorInput = saturated * outputTrim
|
||||
return RBJLowPass.Audio(
|
||||
input: saturated,
|
||||
input: trimmed,
|
||||
freq: $tone,
|
||||
q: toneQ
|
||||
)
|
||||
|
||||
@@ -29,6 +29,9 @@ import LyrebirdUI
|
||||
/// drive harder into the limiter. Range `[1, 12]`. Defaults to `1.0`.
|
||||
/// - ceiling: Output peak ceiling as a linear amplitude in `[0, 1]`. The limited output
|
||||
/// never exceeds this absolute value. Range `[0.1, 1.0]`. Defaults to `0.95`.
|
||||
/// - release: Gain-release time in seconds. Too short a release modulates the gain
|
||||
/// within a waveform cycle and distorts low notes; longer is cleaner but lets the
|
||||
/// level swell back more slowly. Range `[0.01, 0.5]`. Defaults to `0.05`.
|
||||
public final class LimiterPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
@@ -44,6 +47,9 @@ public final class LimiterPedal: Pedal {
|
||||
/// Output peak ceiling (linear amplitude). Range [0.1, 1.0].
|
||||
@UIParam public var ceiling: Double = 0.95
|
||||
|
||||
/// Gain-release time in seconds. Range [0.01, 0.5].
|
||||
@UIParam public var release: Double = 0.05
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — fully wet; the limiter sits in-line.
|
||||
@@ -61,10 +67,14 @@ public final class LimiterPedal: Pedal {
|
||||
/// Ceiling knob range (linear output peak).
|
||||
private let ceilingRange: ClosedRange<Double> = 0.1 ... 1.0
|
||||
|
||||
/// Release knob range in seconds.
|
||||
private let releaseRange: ClosedRange<Double> = 0.01 ... 0.5
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Boost", node: $boost, range: boostRange),
|
||||
PedalKnob(label: "Ceiling", node: $ceiling, range: ceilingRange),
|
||||
PedalKnob(label: "Release", node: $release, range: releaseRange),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -101,6 +111,7 @@ public final class LimiterPedal: Pedal {
|
||||
in: boosted,
|
||||
maxAmplitude: $ceiling,
|
||||
lookAheadTime: lookAheadTime,
|
||||
releaseTime: $release,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import LyrebirdUI
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry → SoftClip(drive:) → RBJLowPass(freq: tone, q: 0.707) → mono out
|
||||
/// dry → OversampledSaturator(curve: .softClipNormalized, drive:) → RBJLowPass(freq: tone, q: 0.707) → mono out
|
||||
/// ```
|
||||
///
|
||||
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
|
||||
@@ -83,7 +83,14 @@ public final class OverdrivePedal: Pedal {
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Saturated and tone-shaped mono output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let saturated: SoftClip.Audio = SoftClip.Audio(dry, drive: $drive)
|
||||
// Same normalised soft-clip curve as before (`tanh(drive·x) / tanh(drive)`), but
|
||||
// evaluated at 2× so high-drive harmonics don't alias.
|
||||
let saturated: OversampledSaturator = OversampledSaturator(
|
||||
dry,
|
||||
drive: $drive,
|
||||
curve: .softClipNormalized,
|
||||
oversample: 2
|
||||
)
|
||||
return RBJLowPass.Audio(
|
||||
input: saturated,
|
||||
freq: $tone,
|
||||
|
||||
@@ -15,7 +15,7 @@ import LyrebirdUI
|
||||
///
|
||||
/// Signal path (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry × OscSin(frequency) → wet
|
||||
/// dry → OversampledRingModulator(freq: frequency, oversample: 2) → wet
|
||||
/// ```
|
||||
///
|
||||
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
|
||||
@@ -78,7 +78,8 @@ public final class RingModulatorPedal: Pedal {
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: The ring-modulated wet signal.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let carrier: OscSin.Audio = OscSin.Audio(freq: $frequency)
|
||||
return dry * carrier
|
||||
// Oversampled multiply: the sum sideband (f_in + f_carrier) can exceed Nyquist and
|
||||
// fold back as an inharmonic alias, so do the product at 2× and filter on the way down.
|
||||
return OversampledRingModulator(dry, freq: $frequency, oversample: 2)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,12 @@ import LyrebirdUI
|
||||
/// - sustain: Amount of sustain/compression. `0` = gentle, `10` = maximum squash and hold.
|
||||
/// Range `[0, 10]`. Defaults to `5.0`.
|
||||
/// - tone: Output low-pass cutoff in Hz. Range `[800, 8000]`. Defaults to `6000.0`.
|
||||
///
|
||||
/// At high sustain the compressor applies a low threshold, a high ratio, and up to +18 dB of
|
||||
/// makeup — a feed-forward compressor's non-zero attack lets transients overshoot before the
|
||||
/// gain clamps, so a hot pick can push the output past full scale and clip. The **Safety**
|
||||
/// switch inserts a brick-wall `LookAheadLimiter` after the compressor to catch those peaks;
|
||||
/// it is off by default and adds a short look-ahead output delay when engaged.
|
||||
public final class SustainerPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
@@ -39,6 +45,10 @@ public final class SustainerPedal: Pedal {
|
||||
/// Output low-pass cutoff in Hz. Range [800, 8000].
|
||||
@UIParam public var tone: Double = 6000.0
|
||||
|
||||
/// Safety limiter engage state. `0` = off (compressor may overshoot), `1` = on
|
||||
/// (brick-wall look-ahead limiter catches transient peaks).
|
||||
@UIParam public var safetyLimiter: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private static let defaultMix: Double = 1.0
|
||||
@@ -69,6 +79,19 @@ public final class SustainerPedal: Pedal {
|
||||
private let makeupAtMin: Double = 0.0
|
||||
private let makeupAtMax: Double = 18.0
|
||||
|
||||
/// Safety-limiter peak ceiling (linear amplitude), just below full scale.
|
||||
private let safetyCeiling: Double = 0.98
|
||||
|
||||
/// Safety-limiter look-ahead / output delay in seconds. Only in circuit when Safety is on.
|
||||
private let safetyLookAheadTime: Double = 0.005
|
||||
|
||||
/// Safety-limiter gain-release time in seconds.
|
||||
private let safetyReleaseTime: Double = 0.05
|
||||
|
||||
/// Safety switch position values.
|
||||
private let safetyOffValue: Double = 0.0
|
||||
private let safetyOnValue: Double = 1.0
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
private let sustainRange: ClosedRange<Double> = 0.0 ... 10.0
|
||||
@@ -81,6 +104,19 @@ public final class SustainerPedal: Pedal {
|
||||
]
|
||||
}
|
||||
|
||||
public override var effectSwitches: [PedalSwitch] {
|
||||
[
|
||||
PedalSwitch(
|
||||
label: "Safety",
|
||||
node: $safetyLimiter,
|
||||
options: [
|
||||
PedalSwitch.Option(title: "Off", value: safetyOffValue),
|
||||
PedalSwitch.Option(title: "On", value: safetyOnValue),
|
||||
]
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a sustainer pedal.
|
||||
@@ -124,8 +160,22 @@ public final class SustainerPedal: Pedal {
|
||||
kneeWidth: kneeWidth,
|
||||
makeupGain: makeup
|
||||
)
|
||||
// Optional brick-wall safety limiter. Both branches are always built; `Select` picks
|
||||
// per the Safety switch (0 = compressor only, 1 = limited). Engaging it adds the
|
||||
// limiter's short look-ahead delay.
|
||||
let limited: LookAheadLimiter = LookAheadLimiter(
|
||||
in: compressed,
|
||||
maxAmplitude: safetyCeiling,
|
||||
lookAheadTime: safetyLookAheadTime,
|
||||
releaseTime: safetyReleaseTime,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
let guarded: Select.Audio = Select.Audio(
|
||||
which: $safetyLimiter,
|
||||
inputs: [compressed, limited]
|
||||
)
|
||||
return RBJLowPass.Audio(
|
||||
input: compressed,
|
||||
input: guarded,
|
||||
freq: $tone,
|
||||
q: toneQ
|
||||
)
|
||||
|
||||
@@ -105,6 +105,82 @@ struct CompressorPedalTests {
|
||||
#expect(labels == ["Input", "Threshold", "Ratio"])
|
||||
}
|
||||
|
||||
@Test func exposesSafetySwitch() throws {
|
||||
let pedal: CompressorPedal = CompressorPedal()
|
||||
let switchLabels: [String] = pedal.effectSwitches.map { $0.label }
|
||||
#expect(switchLabels == ["Safety"])
|
||||
let optionTitles: [String] = pedal.effectSwitches.first?.options.map { $0.title } ?? []
|
||||
#expect(optionTitles == ["Off", "On"])
|
||||
}
|
||||
|
||||
@Test func safetyLimiterCapsPeaks() throws {
|
||||
// Drive the compressor hard (hot input + makeup gain) so its non-zero attack lets
|
||||
// transients overshoot. With the safety limiter engaged the output peak must stay
|
||||
// near full scale; the two switch states must also produce different output.
|
||||
let renderDuration: Double = 0.1
|
||||
let sampleRate: Double = 44100.0
|
||||
|
||||
func render(safety: Double) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||
let pedal: CompressorPedal = CompressorPedal(
|
||||
inputBus: srcBus.index,
|
||||
outputBus: dstBus.index
|
||||
)
|
||||
pedal.sampleRate = sampleRate
|
||||
pedal.inputGain = 24.0
|
||||
pedal.threshold = -30.0
|
||||
pedal.ratio = 8.0
|
||||
pedal.safetyLimiter = safety
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url, sampleRate: sampleRate)
|
||||
}
|
||||
|
||||
let off: [Float] = try render(safety: 0.0)
|
||||
let on: [Float] = try render(safety: 1.0)
|
||||
|
||||
#expect(hasNonSilentOutput(off), "safety-off render was silent")
|
||||
#expect(hasNonSilentOutput(on), "safety-on render was silent")
|
||||
|
||||
// Skip the safety limiter's look-ahead fill window before measuring the peak.
|
||||
let lookAheadFillSamples: Int = 2048
|
||||
guard on.count > lookAheadFillSamples else { return }
|
||||
let onWindow: ArraySlice<Float> = on[lookAheadFillSamples...]
|
||||
let onPeak: Float = onWindow.reduce(0) { Swift.max($0, abs($1)) }
|
||||
|
||||
// Safety ceiling is just under full scale; downstream master only attenuates.
|
||||
let ceilingTolerance: Float = 0.05
|
||||
#expect(onPeak <= 1.0 + ceilingTolerance, "safety limiter failed to cap peak: \(onPeak)")
|
||||
|
||||
// The two switch positions must differ.
|
||||
let skip: Int = lookAheadFillSamples
|
||||
let window: Int = 2048
|
||||
guard off.count >= skip + window, on.count >= skip + window else { return }
|
||||
let offWindow: [Float] = Array(off[skip..<(skip + window)])
|
||||
let onWindow2: [Float] = Array(on[skip..<(skip + window)])
|
||||
let ssd: Double = zip(offWindow, onWindow2).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
#expect(ssd > 0, "safety switch had no effect on output")
|
||||
}
|
||||
|
||||
@Test func inputGainChangesOutput() throws {
|
||||
// The pre-compression input gain stage must alter the output: boosting the input
|
||||
// drives more of the signal past the threshold, changing the compressed result.
|
||||
|
||||
@@ -84,6 +84,16 @@ struct DistortionPedalTests {
|
||||
#expect(labels == ["Drive", "Tone"])
|
||||
}
|
||||
|
||||
@Test func outputStaysBoundedAtHighDrive() throws {
|
||||
// The final hard clip (after the tone low-pass) must re-establish the ±1 output bound
|
||||
// even at extreme drive, despite the oversampled clip sitting before the low-pass.
|
||||
let samples: [Float] = try render { pedal in pedal.drive = 50.0; pedal.tone = 6000.0 }
|
||||
let skip: Int = 2048
|
||||
guard samples.count > skip else { return }
|
||||
let peak: Float = samples[skip...].reduce(0) { Swift.max($0, abs($1)) }
|
||||
#expect(peak <= 1.05, "distortion output exceeded the clip ceiling: peak=\(peak)")
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Distortion")
|
||||
#expect(pedal is DistortionPedal)
|
||||
|
||||
@@ -18,6 +18,7 @@ struct LimiterPedalTests {
|
||||
private func render(
|
||||
boost: Double,
|
||||
ceiling: Double,
|
||||
release: Double = 0.05,
|
||||
sampleRate: Double = 44100.0
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.1
|
||||
@@ -43,6 +44,7 @@ struct LimiterPedalTests {
|
||||
pedal.sampleRate = sampleRate
|
||||
pedal.boost = boost
|
||||
pedal.ceiling = ceiling
|
||||
pedal.release = release
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
@@ -78,4 +80,32 @@ struct LimiterPedalTests {
|
||||
let tolerance: Float = 0.05
|
||||
#expect(peak <= Float(ceiling) + tolerance, "Limiter overshot ceiling: peak=\(peak)")
|
||||
}
|
||||
|
||||
@Test func exposesBoostCeilingReleaseKnobs() throws {
|
||||
let pedal: LimiterPedal = LimiterPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Boost", "Ceiling", "Release"])
|
||||
}
|
||||
|
||||
@Test func releaseChangesOutput() throws {
|
||||
// Same drive and ceiling, different release times: the gain recovers between peaks
|
||||
// at different rates, so the limited output differs. Ceiling still holds for both.
|
||||
let ceiling: Double = 0.4
|
||||
let fast: [Float] = try render(boost: 12.0, ceiling: ceiling, release: 0.01)
|
||||
let slow: [Float] = try render(boost: 12.0, ceiling: ceiling, release: 0.5)
|
||||
|
||||
#expect(hasNonSilentOutput(fast), "fast-release render was silent")
|
||||
#expect(hasNonSilentOutput(slow), "slow-release render was silent")
|
||||
|
||||
let skip: Int = 2048
|
||||
let window: Int = 2048
|
||||
guard fast.count >= skip + window, slow.count >= skip + window else { return }
|
||||
let fastWindow: [Float] = Array(fast[skip..<(skip + window)])
|
||||
let slowWindow: [Float] = Array(slow[skip..<(skip + window)])
|
||||
let ssd: Double = zip(fastWindow, slowWindow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
#expect(ssd > 0, "release time had no effect on limiter output")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
// OversampledRingModulatorTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("OversampledRingModulator")
|
||||
struct OversampledRingModulatorTests {
|
||||
|
||||
private let sampleRate: Double = 44100.0
|
||||
|
||||
/// Minimal synth: a sine through an `OversampledRingModulator`, written to a mono bus.
|
||||
private final class RingSynth: SynthesizerBase {
|
||||
private let inFreq: Double
|
||||
private let carrierFreq: Double
|
||||
private let factor: Int
|
||||
private let outBus: Int
|
||||
|
||||
init(inFreq: Double, carrierFreq: Double, factor: Int, outBus: Int) {
|
||||
self.inFreq = inFreq
|
||||
self.carrierFreq = carrierFreq
|
||||
self.factor = factor
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: inFreq)
|
||||
output(bus: outBus, source: OversampledRingModulator(
|
||||
osc, freq: carrierFreq, oversample: factor))
|
||||
}
|
||||
}
|
||||
|
||||
private func render(inFreq: Double, carrierFreq: Double, factor: Int) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.15, numAudioBuses: 64)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
let synth: RingSynth = RingSynth(
|
||||
inFreq: inFreq, carrierFreq: carrierFreq, factor: factor, outBus: dstBus.index)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(synth)
|
||||
try engine.add(master, position: NodePosition.after(synth))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url, sampleRate: sampleRate)
|
||||
}
|
||||
|
||||
private func leftChannel(_ samples: [Float], skip: Int) -> [Double] {
|
||||
var out: [Double] = []
|
||||
var i: Int = skip * 2
|
||||
while i < samples.count {
|
||||
out.append(Double(samples[i]))
|
||||
i += 2
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private func goertzelMagnitude(_ x: [Double], cyclesPerSample: Double) -> Double {
|
||||
let omega: Double = 2.0 * Double.pi * cyclesPerSample
|
||||
let cosine: Double = cos(omega)
|
||||
let sine: Double = sin(omega)
|
||||
let coeff: Double = 2.0 * cosine
|
||||
var s1: Double = 0.0
|
||||
var s2: Double = 0.0
|
||||
for v: Double in x {
|
||||
let s0: Double = v + coeff * s1 - s2
|
||||
s2 = s1
|
||||
s1 = s0
|
||||
}
|
||||
let real: Double = s1 - s2 * cosine
|
||||
let imag: Double = s2 * sine
|
||||
return (real * real + imag * imag).squareRoot()
|
||||
}
|
||||
|
||||
private func naiveRingMod(inFreq: Double, carrierFreq: Double, count: Int) -> [Double] {
|
||||
let inCps: Double = inFreq / sampleRate
|
||||
let cCps: Double = carrierFreq / sampleRate
|
||||
var out: [Double] = []
|
||||
out.reserveCapacity(count)
|
||||
for n: Int in 0..<count {
|
||||
let x: Double = sin(2.0 * Double.pi * inCps * Double(n))
|
||||
let c: Double = sin(2.0 * Double.pi * cCps * Double(n))
|
||||
out.append(x * c)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@Test func reducesSumSidebandAliasVersusNaive() throws {
|
||||
// in = 0.20·Fs, carrier = 0.35·Fs. Difference sideband = 0.15·Fs (legit, below Nyquist);
|
||||
// sum sideband = 0.55·Fs, which folds to a 0.45·Fs alias at the base rate. Measure the
|
||||
// alias relative to the legit difference sideband (self-normalising).
|
||||
let inHz: Double = 0.20 * sampleRate
|
||||
let carrierHz: Double = 0.35 * sampleRate
|
||||
let diffBin: Double = 0.15 // |0.35 − 0.20|
|
||||
let aliasBin: Double = 0.45 // |1 − 0.55|
|
||||
|
||||
let os: [Float] = try render(inFreq: inHz, carrierFreq: carrierHz, factor: 2)
|
||||
let osLeft: [Double] = leftChannel(os, skip: 2048)
|
||||
#expect(osLeft.count > 2048)
|
||||
|
||||
let osDiff: Double = goertzelMagnitude(osLeft, cyclesPerSample: diffBin)
|
||||
let osAlias: Double = goertzelMagnitude(osLeft, cyclesPerSample: aliasBin)
|
||||
let osRatio: Double = osAlias / osDiff
|
||||
|
||||
let naive: [Double] = naiveRingMod(inFreq: inHz, carrierFreq: carrierHz, count: osLeft.count)
|
||||
let nDiff: Double = goertzelMagnitude(naive, cyclesPerSample: diffBin)
|
||||
let nAlias: Double = goertzelMagnitude(naive, cyclesPerSample: aliasBin)
|
||||
let naiveRatio: Double = nAlias / nDiff
|
||||
|
||||
#expect(naiveRatio > 0.05, "baseline did not alias as expected (ratio=\(naiveRatio))")
|
||||
#expect(
|
||||
osRatio < naiveRatio * 0.5,
|
||||
"oversampling did not reduce ring-mod aliasing: os=\(osRatio) naive=\(naiveRatio)"
|
||||
)
|
||||
}
|
||||
|
||||
@Test func producesNonSilentOutput() throws {
|
||||
let os: [Float] = try render(inFreq: 440.0, carrierFreq: 220.0, factor: 2)
|
||||
#expect(hasNonSilentOutput(os), "ring modulator produced silence")
|
||||
}
|
||||
|
||||
@Test func negativeCarrierStaysFiniteAndBounded() throws {
|
||||
// A negative carrier frequency drives the phase increment negative; the phase must wrap
|
||||
// both directions rather than growing unbounded and pushing sin() out of accurate range.
|
||||
let os: [Float] = try render(inFreq: 440.0, carrierFreq: -220.0, factor: 2)
|
||||
let left: [Double] = leftChannel(os, skip: 1024)
|
||||
#expect(!left.isEmpty)
|
||||
#expect(left.allSatisfy { $0.isFinite }, "negative carrier produced non-finite output")
|
||||
let peak: Double = left.map { abs($0) }.max() ?? 0
|
||||
#expect(peak <= 1.2, "negative carrier output was not bounded: peak=\(peak)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// OversampledSaturatorTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("OversampledSaturator")
|
||||
struct OversampledSaturatorTests {
|
||||
|
||||
private let sampleRate: Double = 44100.0
|
||||
|
||||
/// Minimal synth: a sine through an `OversampledSaturator`, written to a mono bus.
|
||||
private final class SaturatorSynth: SynthesizerBase {
|
||||
private let freq: Double
|
||||
private let drive: Double
|
||||
private let curve: SaturationCurve
|
||||
private let factor: Int
|
||||
private let outBus: Int
|
||||
|
||||
init(freq: Double, drive: Double, curve: SaturationCurve, factor: Int, outBus: Int) {
|
||||
self.freq = freq
|
||||
self.drive = drive
|
||||
self.curve = curve
|
||||
self.factor = factor
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
output(bus: outBus, source: OversampledSaturator(
|
||||
osc, drive: drive, curve: curve, oversample: factor))
|
||||
}
|
||||
}
|
||||
|
||||
private func render(
|
||||
freq: Double,
|
||||
drive: Double,
|
||||
curve: SaturationCurve,
|
||||
factor: Int
|
||||
) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.15, numAudioBuses: 64)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
let synth: SaturatorSynth = SaturatorSynth(
|
||||
freq: freq, drive: drive, curve: curve, factor: factor, outBus: dstBus.index)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(synth)
|
||||
try engine.add(master, position: NodePosition.after(synth))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url, sampleRate: sampleRate)
|
||||
}
|
||||
|
||||
/// Left channel (interleaved stereo), warm-up frames skipped.
|
||||
private func leftChannel(_ samples: [Float], skip: Int) -> [Double] {
|
||||
var out: [Double] = []
|
||||
var i: Int = skip * 2
|
||||
while i < samples.count {
|
||||
out.append(Double(samples[i]))
|
||||
i += 2
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Goertzel magnitude at normalised frequency `cyclesPerSample`.
|
||||
private func goertzelMagnitude(_ x: [Double], cyclesPerSample: Double) -> Double {
|
||||
let omega: Double = 2.0 * Double.pi * cyclesPerSample
|
||||
let cosine: Double = cos(omega)
|
||||
let sine: Double = sin(omega)
|
||||
let coeff: Double = 2.0 * cosine
|
||||
var s1: Double = 0.0
|
||||
var s2: Double = 0.0
|
||||
for v: Double in x {
|
||||
let s0: Double = v + coeff * s1 - s2
|
||||
s2 = s1
|
||||
s1 = s0
|
||||
}
|
||||
let real: Double = s1 - s2 * cosine
|
||||
let imag: Double = s2 * sine
|
||||
return (real * real + imag * imag).squareRoot()
|
||||
}
|
||||
|
||||
/// A naive base-rate hard clipper on the same sine — the alias-generating baseline the
|
||||
/// oversampled path is meant to beat.
|
||||
private func naiveHardClip(
|
||||
freq: Double,
|
||||
drive: Double,
|
||||
low: Double,
|
||||
high: Double,
|
||||
count: Int
|
||||
) -> [Double] {
|
||||
let cyclesPerSample: Double = freq / sampleRate
|
||||
var out: [Double] = []
|
||||
out.reserveCapacity(count)
|
||||
for n: Int in 0..<count {
|
||||
let x: Double = sin(2.0 * Double.pi * cyclesPerSample * Double(n))
|
||||
let shaped: Double = tanh(x) * drive
|
||||
out.append(Swift.min(high, Swift.max(low, shaped)))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@Test func reducesAliasingVersusNaiveHardClip() throws {
|
||||
// 13230 Hz = 0.3·Fs. A symmetric clipper's dominant 3rd harmonic lands at 0.9·Fs,
|
||||
// which folds to a 0.1·Fs (4410 Hz) alias at the base rate. Measure the alias energy
|
||||
// RELATIVE to the fundamental (self-normalising, so downstream routing gain cancels).
|
||||
let fundamentalHz: Double = 0.3 * sampleRate
|
||||
let aliasHz: Double = 0.1 * sampleRate // |3·0.3 − 1|·Fs
|
||||
let drive: Double = 5.0
|
||||
let low: Double = -1.0
|
||||
let high: Double = 1.0
|
||||
|
||||
let os: [Float] = try render(
|
||||
freq: fundamentalHz, drive: drive,
|
||||
curve: .tanhPostGainHardClip(low: low, high: high), factor: 4)
|
||||
let osLeft: [Double] = leftChannel(os, skip: 2048)
|
||||
#expect(osLeft.count > 2048)
|
||||
|
||||
let fundamentalBin: Double = fundamentalHz / sampleRate
|
||||
let aliasBin: Double = aliasHz / sampleRate
|
||||
|
||||
let osFund: Double = goertzelMagnitude(osLeft, cyclesPerSample: fundamentalBin)
|
||||
let osAlias: Double = goertzelMagnitude(osLeft, cyclesPerSample: aliasBin)
|
||||
let osRatio: Double = osAlias / osFund
|
||||
|
||||
let naive: [Double] = naiveHardClip(
|
||||
freq: fundamentalHz, drive: drive, low: low, high: high, count: osLeft.count)
|
||||
let nFund: Double = goertzelMagnitude(naive, cyclesPerSample: fundamentalBin)
|
||||
let nAlias: Double = goertzelMagnitude(naive, cyclesPerSample: aliasBin)
|
||||
let naiveRatio: Double = nAlias / nFund
|
||||
|
||||
// The naive clipper must actually alias (sanity), and oversampling must cut the
|
||||
// alias-to-fundamental ratio by at least half. In practice the 4× halfband path
|
||||
// attenuates it far more; 0.5 is a conservative, non-flaky bound.
|
||||
#expect(naiveRatio > 0.05, "baseline did not alias as expected (ratio=\(naiveRatio))")
|
||||
#expect(
|
||||
osRatio < naiveRatio * 0.5,
|
||||
"oversampling did not reduce aliasing: os=\(osRatio) naive=\(naiveRatio)"
|
||||
)
|
||||
}
|
||||
|
||||
@Test func hardClipCurveRespectsBounds() throws {
|
||||
// With a hard-clip curve the output must stay within [low, high] (plus a small margin
|
||||
// for halfband ripple / routing) regardless of how hard it is driven.
|
||||
let low: Double = -0.5
|
||||
let high: Double = 0.5
|
||||
let samples: [Float] = try render(
|
||||
freq: 2000.0, drive: 10.0,
|
||||
curve: .tanhPostGainHardClip(low: low, high: high), factor: 4)
|
||||
let left: [Double] = leftChannel(samples, skip: 2048)
|
||||
#expect(!left.isEmpty)
|
||||
let peak: Double = left.map { abs($0) }.max() ?? 0
|
||||
let margin: Double = 0.1
|
||||
#expect(peak <= high + margin, "hard-clip curve exceeded its ceiling: peak=\(peak)")
|
||||
}
|
||||
|
||||
@Test func softCurvesStayBounded() throws {
|
||||
// tanh-family curves saturate toward ±1; output must stay bounded well under runaway.
|
||||
let samples: [Float] = try render(
|
||||
freq: 2000.0, drive: 30.0, curve: .tanhPreGain, factor: 2)
|
||||
let left: [Double] = leftChannel(samples, skip: 2048)
|
||||
#expect(!left.isEmpty)
|
||||
let peak: Double = left.map { abs($0) }.max() ?? 0
|
||||
#expect(peak <= 1.2, "tanh saturator output was not bounded near ±1: peak=\(peak)")
|
||||
}
|
||||
}
|
||||
@@ -61,4 +61,35 @@ struct SustainerPedalTests {
|
||||
}
|
||||
#expect(ssd > 0, "sustain knob had no effect on output")
|
||||
}
|
||||
|
||||
@Test func exposesSafetySwitch() throws {
|
||||
let pedal: SustainerPedal = SustainerPedal()
|
||||
#expect(pedal.effectSwitches.map { $0.label } == ["Safety"])
|
||||
#expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Off", "On"])
|
||||
}
|
||||
|
||||
@Test func safetyLimiterCapsPeaks() throws {
|
||||
// Max sustain drives a low threshold, high ratio, and +18 dB makeup — the compressor's
|
||||
// non-zero attack lets transients overshoot. With Safety on, the output peak must stay
|
||||
// near full scale, and the two switch states must differ.
|
||||
let off: [Float] = try render {
|
||||
$0.sampleRate = 44100.0; $0.sustain = 10.0; $0.safetyLimiter = 0.0
|
||||
}
|
||||
let on: [Float] = try render {
|
||||
$0.sampleRate = 44100.0; $0.sustain = 10.0; $0.safetyLimiter = 1.0
|
||||
}
|
||||
#expect(hasNonSilentOutput(off) && hasNonSilentOutput(on))
|
||||
|
||||
let fill: Int = 2048
|
||||
guard on.count > fill else { return }
|
||||
let onPeak: Float = on[fill...].reduce(0) { Swift.max($0, abs($1)) }
|
||||
#expect(onPeak <= 1.05, "safety limiter failed to cap peak: \(onPeak)")
|
||||
|
||||
let window: Int = 2048
|
||||
guard off.count >= fill + window, on.count >= fill + window else { return }
|
||||
let ssd: Double = zip(off[fill..<(fill + window)], on[fill..<(fill + window)]).reduce(0.0) { acc, pair in
|
||||
let d: Double = Double(pair.0 - pair.1); return acc + d * d
|
||||
}
|
||||
#expect(ssd > 0, "safety switch had no effect on output")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user