SPB Git

Repository Public

EffectUnit.swift 5.0 KB 119 lines swift

1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXDSP/EffectUnit.swift3// Description: Base class of every real-time effect: parameter storage, click-free enable/bypass, wet/dry mixing.4//              Subclasses only implement `processWet`. Instances are created off the audio thread and then owned by it.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910/// A stereo in-place effect.11///12/// Threading contract: `init`/`deinit` happen off the audio thread. After the unit is handed to the render thread,13/// `setParameter`, `setMix`, `setEnabled`, `setTransport`, `render` and `reset` are called from that thread only.14/// None of them may allocate, lock, or call into Objective-C.15open class EffectUnit: @unchecked Sendable {16    /// Largest block `render` is ever called with.17    public static let maxBlock = 40961819    public let descriptor: EffectDescriptor20    public let sampleRate: Float2122    /// Current parameter values, indexed like `descriptor.params`.23    public let values: UnsafeMutablePointer<Float>24    public private(set) var enabled = false25    public private(set) var mix: Float26    /// Transport tempo and beat position, refreshed before each block.27    public private(set) var bpm: Float = 12028    public private(set) var beatPosition: Double = 02930    private var wetGain: Float = 031    private let dryL: UnsafeMutablePointer<Float>32    private let dryR: UnsafeMutablePointer<Float>33    private let rampPerSample: Float3435    public init(kind: EffectKind, sampleRate: Double) {36        descriptor = EffectCatalog.descriptor(kind)37        self.sampleRate = Float(sampleRate)38        values = .allocate(capacity: max(1, descriptor.params.count))39        for (i, p) in descriptor.params.enumerated() { values[i] = p.defaultValue }40        mix = descriptor.defaultMix41        dryL = .allocate(capacity: Self.maxBlock); dryR = .allocate(capacity: Self.maxBlock)42        dryL.initialize(repeating: 0, count: Self.maxBlock); dryR.initialize(repeating: 0, count: Self.maxBlock)43        rampPerSample = 1 / Float(0.012 * sampleRate) // 12 ms enable / mix fade44    }4546    deinit { values.deallocate(); dryL.deallocate(); dryR.deallocate() }4748    public var kind: EffectKind { descriptor.kind }4950    // MARK: Control (render thread)5152    public final func setParameter(_ index: Int, _ value: Float) {53        guard index >= 0, index < descriptor.params.count, value.isFinite else { return }54        let p = descriptor.params[index]55        values[index] = clampf(value, p.min, p.max)56        parameterChanged(index)57    }5859    public final func setMix(_ value: Float) { if value.isFinite { mix = clampf(value, 0, 1) } }6061    public final func setEnabled(_ on: Bool) {62        if on, !enabled { willEnable() }63        enabled = on64    }6566    public final func setTransport(bpm: Double, beatPosition: Double) {67        if bpm.isFinite, bpm > 20, bpm < 400 { self.bpm = Float(bpm) }68        self.beatPosition = beatPosition69    }7071    /// Seconds for a length expressed in beats at the current transport tempo.72    @inline(__always) public final func seconds(forBeats beats: Float) -> Float { beats * 60 / bpm }7374    /// True while the unit still produces audible output (enabled, or fading out).75    public final var isActive: Bool { enabled || wetGain > 0 }7677    // MARK: Processing (render thread)7879    /// Processes `frameCount` frames in place. `frameCount` must be <= `maxBlock`.80    public final func render(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ frameCount: Int) {81        let n = min(frameCount, Self.maxBlock)82        let target: Float = enabled ? mix : 083        if target == 0, wetGain == 0 {84            observeBypassed(l, r, n)85            return86        }87        dryL.update(from: l, count: n); dryR.update(from: r, count: n)88        processWet(l, r, n)89        var g = wetGain90        for i in 0 ..< n {91            if g < target { g = min(target, g + rampPerSample) } else if g > target { g = max(target, g - rampPerSample) }92            l[i] = dryL[i] + (l[i] - dryL[i]) * g93            r[i] = dryR[i] + (r[i] - dryR[i]) * g94        }95        wetGain = g96        if !enabled, g == 0 { didFadeOut() }97    }9899    // MARK: Subclass hooks100101    /// Replace the buffers with the fully wet signal. Must be allocation-free.102    open func processWet(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) {}103104    /// Called when a parameter value changed; recompute coefficients here.105    open func parameterChanged(_ index: Int) {}106107    /// Called with the untouched signal while the unit is fully bypassed (for units that keep capturing audio, e.g. beat repeat).108    open func observeBypassed(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) {}109110    /// Called on the transition from disabled to enabled.111    open func willEnable() {}112113    /// Called once the fade-out after disabling completed; clear tails here if they should not reappear.114    open func didFadeOut() {}115116    /// Clears all internal state (delay lines, filter memories).117    open func reset() {}118}119
Files main
Menu

Theme