Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXDSP/Effects/Dynamics.swift3// Description: Dynamics effects: feed-forward stereo-linked compressor and look-ahead peak limiter.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89// MARK: - Compressor1011/// Peak detector (instant attack, 10 ms decay) -> static curve in dB with a 6 dB soft knee -> attack/release smoothing12/// of the gain reduction in dB -> make-up. Both channels share one gain.13public final class CompressorEffect: EffectUnit, @unchecked Sendable {14 private var envelope: Float = 015 private var reduction: Float = 0 // dB, <= 016 private var attack: Float = 0, release: Float = 017 private let envelopeDecay: Float18 private var makeup: OnePoleSmoother // dB1920 public init(sampleRate: Double) {21 envelopeDecay = expf(-1 / Float(0.010 * sampleRate))22 makeup = OnePoleSmoother(timeConstantMS: 20, sampleRate: Float(sampleRate))23 super.init(kind: .compressor, sampleRate: sampleRate)24 for i in 0 ..< 5 { parameterChanged(i) }25 makeup.snap(values[4])26 }2728 public override func parameterChanged(_ index: Int) {29 switch index {30 case 2: attack = expf(-1 / max(1, values[2] * 0.001 * sampleRate))31 case 3: release = expf(-1 / max(1, values[3] * 0.001 * sampleRate))32 case 4: makeup.target = values[4]33 default: break // threshold and ratio are read per block; the gain smoothing below de-zippers them34 }35 }3637 public override func reset() { envelope = 0; reduction = 0 }3839 public override func processWet(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) {40 let threshold = values[0], slope = 1 / max(values[1], 1) - 1, att = attack, rel = release41 var env = envelope, gr = reduction, mk = makeup42 for i in 0 ..< n {43 let xl = sane(l[i]), xr = sane(r[i])44 env = max(max(abs(xl), abs(xr)), env * envelopeDecay)45 let over = 20 * log10f(max(env, 1e-6)) - threshold46 var target: Float = 047 if over >= 3 { target = slope * over } else if over > -3 { let t = over + 3; target = slope * t * t / 12 }48 gr = target + (gr - target) * (target < gr ? att : rel)49 let g = expf((gr + mk.next()) * 0.115129255) // 10^(dB / 20)50 l[i] = xl * g; r[i] = xr * g51 }52 envelope = flush(env); reduction = abs(gr) < 1e-9 ? 0 : gr; makeup = mk53 }54}5556// MARK: - Limiter5758/// Look-ahead brick-wall limiter, latency = 5 ms (not compensated: it is meant to be used fully wet).59/// required[n] = min(1, ceiling / peak[n]); m = sliding minimum of `required` over the look-ahead window (monotonic60/// deque, O(1) amortised); e = m with exponential release (never above m); gain = moving average of e over the same61/// window. Every term of that average is <= the gain required by the sample leaving the delay line, so the output62/// cannot exceed the ceiling; the average turns each gain drop into a 5 ms linear ramp instead of a click.63public final class LimiterEffect: EffectUnit, @unchecked Sendable {64 private let lineL: DelayLine, lineR: DelayLine65 private let window: Int // look-ahead + 166 private let dequeValue: UnsafeMutablePointer<Float>, dequeIndex: UnsafeMutablePointer<Int>67 private let dequeMask: Int68 private let average: UnsafeMutablePointer<Float>69 private var head = 0, tail = 0, index = 0, averagePosition = 070 private var sum: Double71 private var held: Float = 172 private var ceiling: Float = 1, release: Float = 073 /// Smallest gain applied during the last block (1 = no reduction). Read by the master meter.74 public private(set) var lastMinimumGain: Float = 17576 public init(sampleRate: Double) {77 let lookahead = max(1, Int(0.005 * sampleRate))78 window = lookahead + 179 lineL = DelayLine(minimumSamples: window + 4); lineR = DelayLine(minimumSamples: window + 4)80 var cap = 1681 while cap < window + 2 { cap <<= 1 }82 dequeMask = cap - 183 dequeValue = .allocate(capacity: cap); dequeIndex = .allocate(capacity: cap)84 dequeValue.initialize(repeating: 1, count: cap); dequeIndex.initialize(repeating: 0, count: cap)85 average = .allocate(capacity: window); average.initialize(repeating: 1, count: window)86 sum = Double(window)87 super.init(kind: .limiter, sampleRate: sampleRate)88 parameterChanged(0); parameterChanged(1)89 }9091 deinit { dequeValue.deallocate(); dequeIndex.deallocate(); average.deallocate() }9293 public override func parameterChanged(_ index: Int) {94 if index == 0 { ceiling = powf(10, values[0] / 20) } else { release = expf(-1 / max(1, values[1] * 0.001 * sampleRate)) }95 }9697 /// The detector and the delay keep running while bypassed (without touching the audio), so the unit is already98 /// tracking the programme when it fades in: no stale look-ahead buffer, no unprotected first 5 ms.99 public override func observeBypassed(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) { run(l, r, n, write: false) }100101 public override func reset() {102 lineL.reset(); lineR.reset()103 average.update(repeating: 1, count: window); sum = Double(window)104 head = 0; tail = 0; index = 0; averagePosition = 0; held = 1105 }106107 public override func processWet(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) { run(l, r, n, write: true) }108109 @inline(__always) private func run(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int, write: Bool) {110 let c = ceiling, rel = release, lookahead = window - 1, mask = dequeMask, invWindow = 1 / Double(window)111 var h = head, t = tail, idx = index, ap = averagePosition, s = sum, e = held112 var minimum: Float = 1113 for i in 0 ..< n {114 let xl = sane(l[i]), xr = sane(r[i])115 let peak = max(abs(xl), abs(xr)), required: Float = peak > c ? c / peak : 1116 // Sliding minimum: drop every queued value that the new one dominates, then expire the front.117 while t != h, dequeValue[(t - 1) & mask] >= required { t -= 1 }118 dequeValue[t & mask] = required; dequeIndex[t & mask] = idx; t += 1119 if dequeIndex[h & mask] <= idx - window { h += 1 }120 let m = dequeValue[h & mask]121 e = m < e ? m : m + (e - m) * rel122 s += Double(e) - Double(average[ap]); average[ap] = e123 ap += 1; if ap == window { ap = 0 }124 let dl = lineL.read(delayInt: lookahead), dr = lineR.read(delayInt: lookahead)125 lineL.write(xl); lineR.write(xr)126 let g = Float(s * invWindow)127 if g < minimum { minimum = g }128 if write {129 l[i] = clampf(dl * g, -c, c); r[i] = clampf(dr * g, -c, c) // safety net against rounding only130 }131 idx += 1132 }133 head = h; tail = t; index = idx; averagePosition = ap; sum = s; held = e134 lastMinimumGain = minimum135 }136}137