Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXDSP/Effects/EffectSupport.swift3// Description: Shared real-time helpers of the effect units: input sanitising, soft clip, beat phase, click-free delay taps, smoothed state-variable filter.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89/// Maps NaN to 0 and clamps to ±32 (about +30 dBFS) so a bad input sample can never poison recursive state.10@inline(__always) func sane(_ x: Float) -> Float {11 if x >= -32, x <= 32 { return x } // NaN fails both comparisons12 return x > 32 ? 32 : (x < -32 ? -32 : 0)13}1415/// Flushes values that are about to become denormal.16@inline(__always) func flush(_ x: Float) -> Float { abs(x) < 1e-15 ? 0 : x }1718/// Padé approximation of tanh, exactly ±1 beyond |x| >= 3. Used inside feedback loops to bound resonances.19@inline(__always) func softClip(_ x: Float) -> Float {20 if x >= 3 { return 1 }21 if x <= -3 { return -1 }22 let x2 = x * x23 return x * (27 + x2) / (27 + 9 * x2)24}2526/// Phase (0..<1) of a cycle lasting `rate` beats at beat position `beat`.27@inline(__always) func beatPhase(_ beat: Double, _ rate: Float) -> Double {28 guard beat.isFinite, rate > 0 else { return 0 }29 let p = beat / Double(rate)30 return p - p.rounded(.down)31}3233/// Phase increment per sample of a cycle lasting `rate` beats.34@inline(__always) func beatPhaseIncrement(bpm: Float, rate: Float, sampleRate: Float) -> Double {35 Double(bpm) / (60 * Double(sampleRate) * Double(max(rate, 1e-4)))36}3738/// Integer delay tap whose changes are rendered as a short crossfade between the old and the new read position39/// (no pitch glide, no click). A new target is taken only once the running crossfade finished.40struct CrossfadeTap: Sendable {41 private(set) var current: Int42 private(set) var next: Int43 /// Crossfade progress, 0 while idle.44 private(set) var x: Float = 045 private let step: Float4647 init(delay: Int, fadeSamples: Int) { current = delay; next = delay; step = 1 / Float(max(1, fadeSamples)) }4849 mutating func snap(_ delay: Int) { current = delay; next = delay; x = 0 }50 @inline(__always) mutating func retarget(_ delay: Int) { if x == 0, delay != current { next = delay; x = step } }5152 /// Reads the tap. `offset` is added to the delay (1 when the line was written before reading).53 @inline(__always) func read(_ line: DelayLine, offset: Int = 0) -> Float {54 let a = line.read(delayInt: current + offset)55 return x > 0 ? a + (line.read(delayInt: next + offset) - a) * x : a56 }5758 @inline(__always) mutating func advance() {59 if x > 0 { x += step; if x >= 1 { current = next; x = 0 } }60 }61}6263/// Stereo state-variable filter (trapezoidal / TPT form) whose cutoff (log domain) and Q are smoothed. Its response is64/// the same bilinear 12 dB/octave response as the RBJ biquad, but its state stays well behaved while the coefficients65/// move, so fast sweeps do not thump. Targets are evaluated every 32 samples and interpolated per sample in between.66struct SmoothedSVF: Sendable {67 enum Mode: Sendable { case lowpass, highpass, bandpass }68 static let chunk = 326970 private let mode: Mode71 private let sampleRate: Float72 private var logF: OnePoleSmoother73 private var q: OnePoleSmoother74 private var dirty = true75 private var moving = false76 private var g: Float = 0, k: Float = 1, gTarget: Float = 0, kTarget: Float = 1, gStep: Float = 0, kStep: Float = 077 private var a1: Float = 0, a2: Float = 0, a3: Float = 078 private var l1: Float = 0, l2: Float = 0, r1: Float = 0, r2: Float = 07980 init(mode: Mode, frequency: Float, q: Float, sampleRate: Float) {81 self.mode = mode; self.sampleRate = sampleRate82 logF = OnePoleSmoother(value: logf(frequency), timeConstantMS: 15, sampleRate: sampleRate)83 self.q = OnePoleSmoother(value: q, timeConstantMS: 15, sampleRate: sampleRate)84 snap()85 }8687 mutating func set(frequency: Float, q newQ: Float) { logF.target = logf(max(frequency, 1)); q.target = max(newQ, 0.05); dirty = true }88 mutating func reset() { l1 = 0; l2 = 0; r1 = 0; r2 = 0 }8990 mutating func snap() {91 logF.snap(logF.target); q.snap(q.target)92 targets(); g = gTarget; k = kTarget; gStep = 0; kStep = 0; moving = false; dirty = false93 coefficients()94 }9596 @inline(__always) private mutating func targets() {97 gTarget = tanf(.pi * clampf(expf(logF.value), 10, 0.49 * sampleRate) / sampleRate); kTarget = 1 / q.value98 }99100 @inline(__always) private mutating func coefficients() { a1 = 1 / (1 + g * (g + k)); a2 = g * a1; a3 = g * a2 }101102 /// Call before every run of at most `chunk` ticks: advances the smoothers and sets up the per-sample interpolation.103 @inline(__always) mutating func prepare(_ n: Int) {104 if moving { g = gTarget; k = kTarget; coefficients() } // land exactly on the previous target105 guard dirty else { moving = false; return }106 if logF.isSettled, q.isSettled { logF.snap(logF.target); q.snap(q.target); dirty = false } else { _ = logF.advance(n); _ = q.advance(n) }107 targets()108 gStep = (gTarget - g) / Float(n); kStep = (kTarget - k) / Float(n); moving = true109 }110111 @inline(__always) mutating func tick(_ xl: Float, _ xr: Float) -> (Float, Float) {112 if moving { g += gStep; k += kStep; coefficients() }113 let l3 = xl - l2, lv1 = a1 * l1 + a2 * l3, lv2 = l2 + a2 * l1 + a3 * l3114 l1 = 2 * lv1 - l1; l2 = 2 * lv2 - l2115 let r3 = xr - r2, rv1 = a1 * r1 + a2 * r3, rv2 = r2 + a2 * r1 + a3 * r3116 r1 = 2 * rv1 - r1; r2 = 2 * rv2 - r2117 switch mode {118 case .lowpass: return (lv2, rv2)119 case .highpass: return (xl - k * lv1 - lv2, xr - k * rv1 - rv2)120 case .bandpass: return (k * lv1, k * rv1) // unity gain at the centre121 }122 }123124 mutating func flushState() { l1 = flush(l1); l2 = flush(l2); r1 = flush(r1); r2 = flush(r2) }125126 mutating func process(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) {127 var i = 0128 while i < n {129 let c = min(Self.chunk, n - i)130 prepare(c)131 for j in i ..< i + c { (l[j], r[j]) = tick(sane(l[j]), sane(r[j])) }132 i += c133 }134 flushState()135 }136}137