SPB Git

Repository Public

Rhythm.swift 11.6 KB 257 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/Rhythm.swift10// Description      : Beat-locked effects: tremolo, auto-pan, beat gate, beat11//                    repeat. LFO phase = fract(beatPosition / rate).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// The three LFO units recompute their phase from the transport at every block start and advance it per sample with the92// tempo, so they can never drift off the grid. A 1 ms smoother on the resulting gain absorbs phase jumps (seek, rate change).9394// MARK: - Tremolo9596/// Gain = 1 - depth * (1 - m), m = raised cosine peaking on the grid; `shape` sharpens the cosine into a square.97public final class TremoloEffect: EffectUnit, @unchecked Sendable {98    private var depth: OnePoleSmoother99    private var gain: OnePoleSmoother100101    public init(sampleRate: Double) {102        depth = OnePoleSmoother(timeConstantMS: 15, sampleRate: Float(sampleRate))103        gain = OnePoleSmoother(value: 1, timeConstantMS: 1, sampleRate: Float(sampleRate))104        super.init(kind: .tremolo, sampleRate: sampleRate)105        depth.snap(values[1])106    }107108    public override func parameterChanged(_ index: Int) { if index == 1 { depth.target = values[1] } }109110    public override func processWet(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) {111        var ph = beatPhase(beatPosition, values[0])112        let inc = beatPhaseIncrement(bpm: bpm, rate: values[0], sampleRate: sampleRate)113        let sharp = 1 / (1 - 0.98 * values[2]) // 1 (sine) ... 50 (square with short ramps)114        var dp = depth, g = gain115        for i in 0 ..< n {116            let m = 0.5 + 0.5 * clampf(cosf(2 * .pi * Float(ph)) * sharp, -1, 1)117            g.target = 1 - dp.next() * (1 - m)118            let v = g.next()119            l[i] *= v; r[i] *= v120            ph += inc; if ph >= 1 { ph -= 1 }121        }122        depth = dp; gain = g123    }124}125126// MARK: - Auto-pan127128/// Balance law without boost: the channel the signal moves away from is attenuated, the other one stays at unity.129public final class AutopanEffect: EffectUnit, @unchecked Sendable {130    private var depth: OnePoleSmoother131    private var pan: OnePoleSmoother // -1 left ... +1 right132133    public init(sampleRate: Double) {134        depth = OnePoleSmoother(timeConstantMS: 15, sampleRate: Float(sampleRate))135        pan = OnePoleSmoother(value: 0, timeConstantMS: 1, sampleRate: Float(sampleRate))136        super.init(kind: .autopan, sampleRate: sampleRate)137        depth.snap(values[1])138    }139140    public override func parameterChanged(_ index: Int) { if index == 1 { depth.target = values[1] } }141142    public override func processWet(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) {143        var ph = beatPhase(beatPosition, values[0])144        let inc = beatPhaseIncrement(bpm: bpm, rate: values[0], sampleRate: sampleRate)145        var dp = depth, pn = pan146        for i in 0 ..< n {147            pn.target = dp.next() * sinf(2 * .pi * Float(ph))148            let p = pn.next()149            l[i] *= min(1, 1 - p); r[i] *= min(1, 1 + p)150            ph += inc; if ph >= 1 { ph -= 1 }151        }152        depth = dp; pan = pn153    }154}155156// MARK: - Beat gate157158/// Open for the first `duty` fraction of every cycle, attenuated by `depth` for the rest; edges are 1 ms ramps.159public final class GateEffect: EffectUnit, @unchecked Sendable {160    private var gain: OnePoleSmoother161162    public init(sampleRate: Double) {163        gain = OnePoleSmoother(value: 1, timeConstantMS: 1, sampleRate: Float(sampleRate))164        super.init(kind: .gate, sampleRate: sampleRate)165    }166167    public override func processWet(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) {168        var ph = beatPhase(beatPosition, values[0])169        let inc = beatPhaseIncrement(bpm: bpm, rate: values[0], sampleRate: sampleRate)170        let duty = Double(values[1]), closed = 1 - values[2]171        var g = gain172        for i in 0 ..< n {173            g.target = ph < duty ? 1 : closed174            let v = g.next()175            l[i] *= v; r[i] *= v176            ph += inc; if ph >= 1 { ph -= 1 }177        }178        gain = g179    }180}181182// MARK: - Beat repeat183184/// Keeps recording the input in a ring (also while bypassed). On enable, the most recent `length` beats plus a short185/// pre-roll are copied into a loop buffer and played in a loop. The last samples of every pass crossfade into the186/// pre-roll, which runs seamlessly into the slice start, so the seam does not click and the output is exactly periodic.187/// A new length (parameter or tempo) is applied at the next loop start and can only shorten the frozen slice.188public final class BeatRepeatEffect: EffectUnit, @unchecked Sendable {189    private let ringL: UnsafeMutablePointer<Float>, ringR: UnsafeMutablePointer<Float>190    private let loopL: UnsafeMutablePointer<Float>, loopR: UnsafeMutablePointer<Float>191    private let ringCapacity: Int, ringMask: Int, maxLength: Int, maxFade: Int192    private var writeIndex = 0193    private var captured = 0 // frozen slice length (0 = nothing frozen)194    private var preRoll = 0 // frames stored before the slice start195    private var loopLength = 0, fade = 0, position = 0196197    public init(sampleRate: Double) {198        maxLength = Int(4 * sampleRate); maxFade = Int(0.005 * sampleRate)199        var cap = 1024200        while cap < maxLength + maxFade + 8 { cap <<= 1 }201        ringCapacity = cap; ringMask = cap - 1202        ringL = .allocate(capacity: cap); ringR = .allocate(capacity: cap)203        ringL.initialize(repeating: 0, count: cap); ringR.initialize(repeating: 0, count: cap)204        let loopCount = maxLength + maxFade205        loopL = .allocate(capacity: loopCount); loopR = .allocate(capacity: loopCount)206        loopL.initialize(repeating: 0, count: loopCount); loopR.initialize(repeating: 0, count: loopCount)207        super.init(kind: .beatrepeat, sampleRate: sampleRate)208    }209210    deinit { ringL.deallocate(); ringR.deallocate(); loopL.deallocate(); loopR.deallocate() }211212    private var targetLength: Int { min(max(Int((seconds(forBeats: values[0]) * sampleRate).rounded()), 16), maxLength) }213214    @inline(__always) private func capture(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) {215        var w = writeIndex216        for i in 0 ..< n { ringL[w] = sane(l[i]); ringR[w] = sane(r[i]); w = (w + 1) & ringMask }217        writeIndex = w218    }219220    public override func observeBypassed(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) { capture(l, r, n) }221222    public override func willEnable() {223        let length = targetLength, pre = min(maxFade, length / 4), total = length + pre224        let start = (writeIndex - total) & ringMask, first = min(total, ringCapacity - start)225        loopL.update(from: ringL + start, count: first); loopR.update(from: ringR + start, count: first)226        if total > first {227            (loopL + first).update(from: ringL, count: total - first); (loopR + first).update(from: ringR, count: total - first)228        }229        captured = length; preRoll = pre; loopLength = length; fade = pre; position = 0230    }231232    public override func reset() {233        ringL.update(repeating: 0, count: ringCapacity); ringR.update(repeating: 0, count: ringCapacity)234        loopL.update(repeating: 0, count: maxLength + maxFade); loopR.update(repeating: 0, count: maxLength + maxFade)235        position = 0236    }237238    public override func processWet(_ l: UnsafeMutablePointer<Float>, _ r: UnsafeMutablePointer<Float>, _ n: Int) {239        capture(l, r, n) // the live input keeps feeding the ring so a later freeze is always current240        guard captured > 0 else { return }241        let wanted = min(targetLength, captured), sl = loopL + preRoll, sr = loopR + preRoll242        var pos = position, len = loopLength, fd = fade243        for i in 0 ..< n {244            var a = sl[pos], b = sr[pos]245            let fadeStart = len - fd246            if pos >= fadeStart { // blend towards the pre-roll, which continues into sample 0 of the slice247                let t = Float(pos - fadeStart + 1) / Float(fd + 1)248                a += (sl[pos - len] - a) * t; b += (sr[pos - len] - b) * t249            }250            l[i] = a; r[i] = b251            pos += 1252            if pos >= len { pos = 0; len = wanted; fd = min(preRoll, len / 4) }253        }254        position = pos; loopLength = len; fade = fd255    }256}257
Files main
Menu

Theme