Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXDSP/Primitives.swift3// Description: Real-time safe DSP building blocks: gain maths, biquad filters, smoothers, delay lines, lock-free SPSC queue.4// Everything here is allocation-free after init and safe to call from the audio render thread.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Synchronization1011// MARK: - Gain maths1213/// Decibel floor used across ORIX DJ: at or below this value a gain is treated as silence.14public let silenceFloorDB: Float = -601516@inline(__always) public func dbToLinear(_ db: Float) -> Float {17 db <= silenceFloorDB ? 0 : powf(10, db / 20)18}1920@inline(__always) public func linearToDB(_ linear: Float) -> Float {21 linear <= 0.001 ? silenceFloorDB : max(silenceFloorDB, 20 * log10f(linear))22}2324@inline(__always) public func clampf(_ x: Float, _ lo: Float, _ hi: Float) -> Float { min(max(x, lo), hi) }2526// MARK: - Biquad2728/// Biquad coefficients (RBJ Audio EQ Cookbook), normalised so a0 == 1.29public struct BiquadCoefficients: Sendable, Equatable {30 public var b0: Float = 1, b1: Float = 0, b2: Float = 0, a1: Float = 0, a2: Float = 03132 public init() {}3334 public static let identity = BiquadCoefficients()3536 private static func make(_ b0: Float, _ b1: Float, _ b2: Float, _ a0: Float, _ a1: Float, _ a2: Float) -> BiquadCoefficients {37 var c = BiquadCoefficients()38 let inv = 1 / a039 c.b0 = b0 * inv; c.b1 = b1 * inv; c.b2 = b2 * inv; c.a1 = a1 * inv; c.a2 = a2 * inv40 return c41 }4243 @inline(__always) private static func omega(_ f: Float, _ sr: Float) -> (cos: Float, sin: Float) {44 let w = 2 * Float.pi * clampf(f, 10, sr * 0.49) / sr45 return (cosf(w), sinf(w))46 }4748 public static func lowpass(frequency f: Float, q: Float, sampleRate sr: Float) -> BiquadCoefficients {49 let (cw, sw) = omega(f, sr); let alpha = sw / (2 * max(q, 0.05))50 return make((1 - cw) / 2, 1 - cw, (1 - cw) / 2, 1 + alpha, -2 * cw, 1 - alpha)51 }5253 public static func highpass(frequency f: Float, q: Float, sampleRate sr: Float) -> BiquadCoefficients {54 let (cw, sw) = omega(f, sr); let alpha = sw / (2 * max(q, 0.05))55 return make((1 + cw) / 2, -(1 + cw), (1 + cw) / 2, 1 + alpha, -2 * cw, 1 - alpha)56 }5758 /// Constant 0 dB peak gain band-pass.59 public static func bandpass(frequency f: Float, q: Float, sampleRate sr: Float) -> BiquadCoefficients {60 let (cw, sw) = omega(f, sr); let alpha = sw / (2 * max(q, 0.05))61 return make(alpha, 0, -alpha, 1 + alpha, -2 * cw, 1 - alpha)62 }6364 public static func peaking(frequency f: Float, q: Float, gainDB: Float, sampleRate sr: Float) -> BiquadCoefficients {65 let a = powf(10, gainDB / 40); let (cw, sw) = omega(f, sr); let alpha = sw / (2 * max(q, 0.05))66 return make(1 + alpha * a, -2 * cw, 1 - alpha * a, 1 + alpha / a, -2 * cw, 1 - alpha / a)67 }6869 public static func lowShelf(frequency f: Float, gainDB: Float, slope: Float = 1, sampleRate sr: Float) -> BiquadCoefficients {70 let a = powf(10, gainDB / 40); let (cw, sw) = omega(f, sr)71 let alpha = sw / 2 * sqrtf(max(0, (a + 1 / a) * (1 / slope - 1) + 2)); let k = 2 * sqrtf(a) * alpha72 return make(a * ((a + 1) - (a - 1) * cw + k), 2 * a * ((a - 1) - (a + 1) * cw), a * ((a + 1) - (a - 1) * cw - k),73 (a + 1) + (a - 1) * cw + k, -2 * ((a - 1) + (a + 1) * cw), (a + 1) + (a - 1) * cw - k)74 }7576 public static func highShelf(frequency f: Float, gainDB: Float, slope: Float = 1, sampleRate sr: Float) -> BiquadCoefficients {77 let a = powf(10, gainDB / 40); let (cw, sw) = omega(f, sr)78 let alpha = sw / 2 * sqrtf(max(0, (a + 1 / a) * (1 / slope - 1) + 2)); let k = 2 * sqrtf(a) * alpha79 return make(a * ((a + 1) + (a - 1) * cw + k), -2 * a * ((a - 1) + (a + 1) * cw), a * ((a + 1) + (a - 1) * cw - k),80 (a + 1) - (a - 1) * cw + k, 2 * ((a - 1) - (a + 1) * cw), (a + 1) - (a - 1) * cw - k)81 }8283 public static func allpass(frequency f: Float, q: Float, sampleRate sr: Float) -> BiquadCoefficients {84 let (cw, sw) = omega(f, sr); let alpha = sw / (2 * max(q, 0.05))85 return make(1 - alpha, -2 * cw, 1 + alpha, 1 + alpha, -2 * cw, 1 - alpha)86 }8788 /// Magnitude response (linear) at `frequency`, used by tests and by the EQ curve display.89 public func magnitude(at frequency: Float, sampleRate: Float) -> Float {90 let w = 2 * Float.pi * frequency / sampleRate91 let c1 = cosf(w), s1 = sinf(w), c2 = cosf(2 * w), s2 = sinf(2 * w)92 let nr = b0 + b1 * c1 + b2 * c2, ni = -(b1 * s1 + b2 * s2)93 let dr = 1 + a1 * c1 + a2 * c2, di = -(a1 * s1 + a2 * s2)94 return sqrtf((nr * nr + ni * ni) / max(dr * dr + di * di, 1e-30))95 }96}9798/// Stereo biquad, transposed direct form II. Value type; state lives inline (no allocation).99public struct StereoBiquad: Sendable {100 public var c = BiquadCoefficients()101 private var l1: Float = 0, l2: Float = 0, r1: Float = 0, r2: Float = 0102103 public init() {}104105 public mutating func reset() { l1 = 0; l2 = 0; r1 = 0; r2 = 0 }106107 @inline(__always) public mutating func processLeft(_ x: Float) -> Float {108 let y = c.b0 * x + l1109 l1 = c.b1 * x - c.a1 * y + l2110 l2 = c.b2 * x - c.a2 * y111 return y112 }113114 @inline(__always) public mutating func processRight(_ x: Float) -> Float {115 let y = c.b0 * x + r1116 r1 = c.b1 * x - c.a1 * y + r2117 r2 = c.b2 * x - c.a2 * y118 return y119 }120121 public mutating func process(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) {122 for i in 0 ..< n { l[i] = processLeft(l[i]); r[i] = processRight(r[i]) }123 // Denormal protection: flush tiny state to zero.124 if abs(l1) < 1e-20 { l1 = 0 }; if abs(l2) < 1e-20 { l2 = 0 }125 if abs(r1) < 1e-20 { r1 = 0 }; if abs(r2) < 1e-20 { r2 = 0 }126 }127}128129// MARK: - Smoothing130131/// One-pole exponential smoother for control values.132public struct OnePoleSmoother: Sendable {133 public var value: Float134 public var target: Float135 private var coeff: Float136137 public init(value: Float = 0, timeConstantMS: Float = 10, sampleRate: Float = 48000) {138 self.value = value; target = value139 coeff = expf(-1 / max(1, timeConstantMS * 0.001 * sampleRate))140 }141142 public mutating func setTime(ms: Float, sampleRate: Float) { coeff = expf(-1 / max(1, ms * 0.001 * sampleRate)) }143 public mutating func snap(_ v: Float) { value = v; target = v }144 @inline(__always) public mutating func next() -> Float { value = target + (value - target) * coeff; return value }145 /// Advances `n` samples at once and returns the value at the end of the block.146 @inline(__always) public mutating func advance(_ n: Int) -> Float {147 value = target + (value - target) * powf(coeff, Float(n)); return value148 }149 public var isSettled: Bool { abs(value - target) < 1e-5 }150}151152/// Linear ramp towards a target over a fixed number of samples (sample-accurate automation ramps).153public struct LinearRamp: Sendable {154 public private(set) var value: Float155 public private(set) var target: Float156 private var step: Float = 0157 private var remaining: Int = 0158159 public init(_ value: Float = 0) { self.value = value; target = value }160161 public mutating func snap(_ v: Float) { value = v; target = v; remaining = 0; step = 0 }162163 public mutating func set(_ newTarget: Float, overSamples n: Int) {164 target = newTarget165 if n <= 0 { value = newTarget; remaining = 0; step = 0 } else { remaining = n; step = (newTarget - value) / Float(n) }166 }167168 @inline(__always) public mutating func next() -> Float {169 if remaining > 0 { value += step; remaining -= 1; if remaining == 0 { value = target } }170 return value171 }172173 @inline(__always) public mutating func advance(_ n: Int) -> Float {174 if remaining > 0 { let k = min(n, remaining); value += step * Float(k); remaining -= k; if remaining == 0 { value = target } }175 return value176 }177178 public var isRamping: Bool { remaining > 0 }179}180181// MARK: - Delay line182183/// Fixed-capacity mono delay line with fractional (linear-interpolated) reads. Owns its memory; create off the audio thread.184public final class DelayLine: @unchecked Sendable {185 public let capacity: Int186 private let mask: Int187 private let buffer: UnsafeMutablePointer<Float>188 private var writeIndex = 0189190 /// `minimumSamples` is rounded up to a power of two.191 public init(minimumSamples: Int) {192 var cap = 16193 while cap < minimumSamples + 4 { cap <<= 1 }194 capacity = cap; mask = cap - 1195 buffer = .allocate(capacity: cap); buffer.initialize(repeating: 0, count: cap)196 }197198 deinit { buffer.deallocate() }199200 public func reset() { buffer.update(repeating: 0, count: capacity); writeIndex = 0 }201202 @inline(__always) public func write(_ x: Float) {203 buffer[writeIndex] = x; writeIndex = (writeIndex + 1) & mask204 }205206 /// Reads the sample written `delay` samples ago (delay >= 1 reads strictly past samples when called before `write`).207 @inline(__always) public func read(delaySamples delay: Float) -> Float {208 let d = min(max(delay, 0), Float(capacity - 3))209 let pos = Float(writeIndex) - d210 let fl = floorf(pos); let frac = pos - fl211 let i0 = (Int(fl) + capacity * 2) & mask212 let i1 = (i0 + 1) & mask213 return buffer[i0] + (buffer[i1] - buffer[i0]) * frac214 }215216 @inline(__always) public func read(delayInt delay: Int) -> Float {217 buffer[(writeIndex - min(max(delay, 0), capacity - 1) + capacity) & mask]218 }219}220221// MARK: - Lock-free single-producer single-consumer queue222223/// Bounded wait-free SPSC ring. One thread pushes, one thread pops. Used for control events to and from the render thread.224public final class SPSCQueue<Element: BitwiseCopyable>: @unchecked Sendable {225 private let storage: UnsafeMutablePointer<Element>226 private let mask: Int227 private let head = Atomic<Int>(0) // next slot to pop (consumer-owned)228 private let tail = Atomic<Int>(0) // next slot to push (producer-owned)229230 public let capacity: Int231232 public init(minimumCapacity: Int) {233 var cap = 2234 while cap < minimumCapacity + 1 { cap <<= 1 }235 capacity = cap - 1; mask = cap - 1236 storage = .allocate(capacity: cap)237 }238239 deinit { storage.deallocate() }240241 /// Returns false when the queue is full (the event is dropped by the caller, never blocks).242 @discardableResult @inline(__always) public func push(_ element: Element) -> Bool {243 let t = tail.load(ordering: .relaxed)244 let next = (t + 1) & mask245 if next == head.load(ordering: .acquiring) { return false }246 storage[t] = element247 tail.store(next, ordering: .releasing)248 return true249 }250251 @inline(__always) public func pop() -> Element? {252 let h = head.load(ordering: .relaxed)253 if h == tail.load(ordering: .acquiring) { return nil }254 let e = storage[h]255 head.store((h + 1) & mask, ordering: .releasing)256 return e257 }258259 public var count: Int { (tail.load(ordering: .relaxed) - head.load(ordering: .relaxed)) & mask }260}261262// MARK: - Deterministic noise263264/// Tiny xorshift generator: deterministic, allocation-free, good enough for dither and noise sweeps.265public struct NoiseGenerator: Sendable {266 private var state: UInt32267 public init(seed: UInt32 = 0x9E37_79B9) { state = seed == 0 ? 1 : seed }268 /// White noise in -1...1.269 @inline(__always) public mutating func next() -> Float {270 state ^= state << 13; state ^= state >> 17; state ^= state << 5271 return Float(Int32(bitPattern: state)) * (1.0 / 2_147_483_648.0)272 }273}274