SPB Git

Repository Public

Space.swift 14.0 KB 302 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX DJ9// File             : Packages/ORIXDJCore/Sources/ORIXDSP/Effects/Space.swift10// Description      : Space effects: Freeverb-style stereo reverb, clean11//                    beat-synchronised delay, tape-style echo.12// Module           : ORIXDSP13// Repository       : https://git.spboucher.ai/orix-dj14// Created          : 2026-11-2115// Last Modified    : 2026-11-2116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import Foundation9091// MARK: - Reverb9293/// Freeverb topology: per channel 8 parallel damped feedback combs followed by 4 series all-passes, right channel94/// detuned by a fixed spread. Feedback stays below 1 and the damping low-pass has unity DC gain, so it is stable for every setting.95public final class ReverbEffect: EffectUnit, @unchecked Sendable {96    private static let combTuning = [1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617] // samples at 44.1 kHz97    private static let allpassTuning = [556, 441, 341, 225]98    private static let stereoSpread = 2399    private static let lines = 24 // 0..<8 combs L, 8..<16 combs R, 16..<20 all-passes L, 20..<24 all-passes R100101    private let memory: UnsafeMutablePointer<Float>102    private let memoryCount: Int103    private let offset: UnsafeMutablePointer<Int>104    private let length: UnsafeMutablePointer<Int>105    private let position: UnsafeMutablePointer<Int>106    private let store: UnsafeMutablePointer<Float> // damping low-pass state of the 16 combs107    private let scratch: UnsafeMutablePointer<Float> // input, feedback ramp, damping ramp, sum L, sum R108    private let pre: DelayLine109    private var preTap: CrossfadeTap110    private var feedback: OnePoleSmoother111    private var damp: OnePoleSmoother112    private var width: OnePoleSmoother113    private var stale = false114115    public init(sampleRate: Double) {116        let n = Self.lines, scale = sampleRate / 44100117        offset = .allocate(capacity: n); length = .allocate(capacity: n); position = .allocate(capacity: n)118        var total = 0119        for k in 0 ..< n {120            let base = k < 16 ? Self.combTuning[k % 8] : Self.allpassTuning[(k - 16) % 4]121            let right = k < 16 ? k >= 8 : k >= 20122            let len = max(8, Int((Double(base + (right ? Self.stereoSpread : 0)) * scale).rounded()))123            offset[k] = total; length[k] = len; position[k] = 0; total += len124        }125        memoryCount = total126        memory = .allocate(capacity: total); memory.initialize(repeating: 0, count: total)127        store = .allocate(capacity: 16); store.initialize(repeating: 0, count: 16)128        scratch = .allocate(capacity: 5 * Self.maxBlock); scratch.initialize(repeating: 0, count: 5 * Self.maxBlock)129        pre = DelayLine(minimumSamples: Int(0.2 * sampleRate) + 8)130        let sr = Float(sampleRate)131        preTap = CrossfadeTap(delay: 0, fadeSamples: Int(0.03 * sampleRate))132        feedback = OnePoleSmoother(timeConstantMS: 30, sampleRate: sr)133        damp = OnePoleSmoother(timeConstantMS: 30, sampleRate: sr)134        width = OnePoleSmoother(timeConstantMS: 30, sampleRate: sr)135        super.init(kind: .reverb, sampleRate: sampleRate)136        for i in 0 ..< 4 { parameterChanged(i) }137        feedback.snap(feedback.target); damp.snap(damp.target); width.snap(width.target); preTap.snap(preDelaySamples)138    }139140    deinit { memory.deallocate(); offset.deallocate(); length.deallocate(); position.deallocate(); store.deallocate(); scratch.deallocate() }141142    private var preDelaySamples: Int { min(Int((values[2] * 0.001 * sampleRate).rounded()), pre.capacity - 8) }143144    public override func parameterChanged(_ index: Int) {145        switch index {146        case 0: feedback.target = 0.7 + 0.28 * values[0] // RT60 from about 0.6 s to about 11 s147        case 1: damp.target = 0.7 * values[1]148        case 3: width.target = values[3]149        default: break150        }151    }152153    public override func observeBypassed(_: UnsafeMutablePointer<Float>, _: UnsafeMutablePointer<Float>, _: Int) { stale = true }154155    public override func reset() {156        memory.update(repeating: 0, count: memoryCount); store.update(repeating: 0, count: 16); pre.reset()157        for k in 0 ..< Self.lines { position[k] = 0 }158    }159160    public override func processWet(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) {161        if stale { reset(); stale = false }162        let block = Self.maxBlock163        let inp = scratch, fbv = scratch + block, dv = scratch + 2 * block, accL = scratch + 3 * block, accR = scratch + 4 * block164        var tap = preTap, fb = feedback, dmp = damp165        tap.retarget(preDelaySamples)166        for i in 0 ..< n {167            pre.write(sane(l[i] + r[i]) * 0.015)168            inp[i] = tap.read(pre, offset: 1); tap.advance()169            fbv[i] = fb.next(); dv[i] = dmp.next(); accL[i] = 0; accR[i] = 0170        }171        preTap = tap; feedback = fb; damp = dmp172        for k in 0 ..< 16 { // combs: y = buffer; low-pass y into the store; buffer = input + store * feedback173            let b = memory + offset[k], len = length[k], acc = k < 8 ? accL : accR174            var j = position[k], s = store[k]175            for i in 0 ..< n {176                let y = b[j]177                s = flush(y + (s - y) * dv[i])178                b[j] = inp[i] + s * fbv[i]179                acc[i] += y180                j += 1; if j == len { j = 0 }181            }182            position[k] = j; store[k] = s183        }184        for k in 16 ..< 24 { // Schroeder all-pass diffusers, gain 0.5185            let b = memory + offset[k], len = length[k], acc = k < 20 ? accL : accR186            var j = position[k]187            for i in 0 ..< n {188                let y = b[j], x = acc[i]189                b[j] = flush(x + y * 0.5)190                acc[i] = y - x191                j += 1; if j == len { j = 0 }192            }193            position[k] = j194        }195        var w = width196        for i in 0 ..< n {197            let wv = w.next(), w1 = 1.5 * (1 + wv), w2 = 1.5 * (1 - wv), a = accL[i], b = accR[i]198            l[i] = a * w1 + b * w2; r[i] = b * w1 + a * w2199        }200        width = w201    }202}203204// MARK: - Delay205206/// Clean stereo delay. The wet signal is the repeats only; the delay length is an integer number of samples so repeats207/// are bit-exact copies scaled by the feedback. Length changes (parameter or tempo) crossfade between two taps.208public final class DelayEffect: EffectUnit, @unchecked Sendable {209    private let lineL: DelayLine, lineR: DelayLine210    private let maxDelay: Int211    private var tap: CrossfadeTap212    private var feedback: OnePoleSmoother213    private var pingPong: OnePoleSmoother214    private var stale = false215216    public init(sampleRate: Double) {217        maxDelay = Int(4 * sampleRate)218        lineL = DelayLine(minimumSamples: maxDelay + 8); lineR = DelayLine(minimumSamples: maxDelay + 8)219        tap = CrossfadeTap(delay: 1, fadeSamples: Int(0.03 * sampleRate))220        feedback = OnePoleSmoother(timeConstantMS: 20, sampleRate: Float(sampleRate))221        pingPong = OnePoleSmoother(timeConstantMS: 20, sampleRate: Float(sampleRate))222        super.init(kind: .delay, sampleRate: sampleRate)223        tap.snap(delaySamples); feedback.snap(values[1]); pingPong.snap(values[2] >= 0.5 ? 1 : 0)224    }225226    private var delaySamples: Int { min(max(Int((seconds(forBeats: values[0]) * sampleRate).rounded()), 1), maxDelay) }227228    public override func parameterChanged(_ index: Int) {229        if index == 1 { feedback.target = values[1] } else if index == 2 { pingPong.target = values[2] >= 0.5 ? 1 : 0 }230    }231232    public override func observeBypassed(_: UnsafeMutablePointer<Float>, _: UnsafeMutablePointer<Float>, _: Int) { stale = true }233    public override func reset() { lineL.reset(); lineR.reset() }234235    public override func processWet(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) {236        if stale { reset(); stale = false }237        var t = tap, fb = feedback, pp = pingPong238        t.retarget(delaySamples)239        for i in 0 ..< n {240            let xl = sane(l[i]), xr = sane(r[i])241            let dl = t.read(lineL), dr = t.read(lineR)242            t.advance()243            let f = fb.next(), p = pp.next()244            // Ping-pong (p = 1): the mono input enters the left line only and each line feeds the other one.245            let inL = xl + ((xl + xr) * 0.5 - xl) * p, inR = xr * (1 - p)246            lineL.write(flush(inL + f * (dl + (dr - dl) * p)))247            lineR.write(flush(inR + f * (dr + (dl - dr) * p)))248            l[i] = dl; r[i] = dr249        }250        tap = t; feedback = fb; pingPong = pp251    }252}253254// MARK: - Echo255256/// Tape-style echo: every pass through the loop goes through a one-pole low-pass and a gentle saturator, so repeats get darker and rounder.257public final class EchoEffect: EffectUnit, @unchecked Sendable {258    private let lineL: DelayLine, lineR: DelayLine259    private let maxDelay: Int260    private var tap: CrossfadeTap261    private var feedback: OnePoleSmoother262    private var tone: OnePoleSmoother // one-pole coefficient263    private var lpL: Float = 0, lpR: Float = 0264    private var stale = false265266    public init(sampleRate: Double) {267        maxDelay = Int(4 * sampleRate)268        lineL = DelayLine(minimumSamples: maxDelay + 8); lineR = DelayLine(minimumSamples: maxDelay + 8)269        tap = CrossfadeTap(delay: 1, fadeSamples: Int(0.03 * sampleRate))270        feedback = OnePoleSmoother(timeConstantMS: 20, sampleRate: Float(sampleRate))271        tone = OnePoleSmoother(timeConstantMS: 20, sampleRate: Float(sampleRate))272        super.init(kind: .echo, sampleRate: sampleRate)273        parameterChanged(2)274        tap.snap(delaySamples); feedback.snap(values[1]); tone.snap(tone.target)275    }276277    private var delaySamples: Int { min(max(Int((seconds(forBeats: values[0]) * sampleRate).rounded()), 1), maxDelay) }278279    public override func parameterChanged(_ index: Int) {280        if index == 1 { feedback.target = values[1] } else if index == 2 { tone.target = 1 - expf(-2 * .pi * min(values[2], 0.45 * sampleRate) / sampleRate) }281    }282283    public override func observeBypassed(_: UnsafeMutablePointer<Float>, _: UnsafeMutablePointer<Float>, _: Int) { stale = true }284    public override func reset() { lineL.reset(); lineR.reset(); lpL = 0; lpR = 0 }285286    public override func processWet(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) {287        if stale { reset(); stale = false }288        var t = tap, fb = feedback, tn = tone, sl = lpL, sr = lpR289        t.retarget(delaySamples)290        for i in 0 ..< n {291            let a = tn.next(), f = fb.next()292            sl += a * (t.read(lineL) - sl); sr += a * (t.read(lineR) - sr)293            t.advance()294            // 2 * softClip(x / 2) is transparent at normal levels and bounds the loop at ±2.295            lineL.write(flush(sane(l[i]) + f * 2 * softClip(sl * 0.5)))296            lineR.write(flush(sane(r[i]) + f * 2 * softClip(sr * 0.5)))297            l[i] = sl; r[i] = sr298        }299        tap = t; feedback = fb; tone = tn; lpL = flush(sl); lpR = flush(sr)300    }301}302
Files main
Menu

Theme