Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXDJEngine/RenderCore.swift3// Description: The render-thread mixer: four deck voices, channel strips (trim, EQ, filters, effects rack, fader, cue),4// crossfader, master rack, limiter, meters, cue bus, recording tap. Driven only by timestamped control5// events from a bounded lock-free queue; never allocates, locks or blocks while rendering.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Accelerate10import Foundation11import ORIXDSP12import Synchronization1314public let deckCount = 415public let rackSlotCount = 816/// Rack index of the master bus in control events.17let masterRack: Int16 = -11819enum EventKind: UInt16 {20 case deckSetTrack, deckPlay, deckPause, deckSeek, deckRate, deckKeylock, deckPitch, deckReverse, deckLoop, deckLoopOff, deckBrake21 case param, clock22 case fxSet, fxSwap, fxEnable, fxMix, fxParam23 case record, panic24}2526/// Continuous and switch parameters of the mixer. Deck-scoped ones use the event's `deck` field.27enum MixParam: Int32 {28 case gain, volume, eqLow, eqMid, eqHigh, eqLowMid, filterKnob, highpass, lowpass, resonance, cue, assign29 case crossfader, crossfaderCurve, masterVolume, limiter, cueMix, cueVolume, eqBands, splitCue30}3132struct ControlEvent: BitwiseCopyable {33 /// Engine sample time at which the event applies; 0 means as soon as possible.34 var time: Int64 = 035 var kind: UInt1636 var deck: Int16 = 037 var index: Int32 = 038 var a: Double = 039 var b: Double = 040 var pointer: UnsafeMutableRawPointer?41 /// True for automation events whose timing accuracy is measured.42 var tracked = false4344 init(_ kind: EventKind, deck: Int = 0, index: Int32 = 0, a: Double = 0, b: Double = 0, pointer: UnsafeMutableRawPointer? = nil, time: Int64 = 0, tracked: Bool = false) {45 self.kind = kind.rawValue; self.deck = Int16(deck); self.index = index; self.a = a; self.b = b; self.pointer = pointer; self.time = time; self.tracked = tracked46 }47}4849enum NoticeKind: UInt16 { case trackEnded, brakeFinished, releaseTrack, releaseEffect }5051struct RenderNotice: BitwiseCopyable {52 var kind: UInt1653 var deck: Int1654 var pointer: UnsafeMutableRawPointer?55}5657/// Per-deck state published by the render thread.58public struct DeckRenderState: BitwiseCopyable, Sendable {59 public init() {}60 public var position = 0.061 public var rate = 1.062 public var playing = false63 public var loaded = false64 public var loopActive = false65 public var loopStart = 0.066 public var loopEnd = 0.067 /// Post-fader peak (linear), decaying.68 public var peak: Float = 069 public var rms: Float = 070}7172/// Engine-wide state published by the render thread.73public struct EngineRenderState: BitwiseCopyable, Sendable {74 public init() {}75 public var sampleTime: Int64 = 076 public var hostTime: UInt64 = 077 public var masterPeakL: Float = 078 public var masterPeakR: Float = 079 public var masterRMS: Float = 080 public var cuePeak: Float = 081 /// Gain reduction applied by the master limiter, in dB (0 or negative).82 public var limiterReductionDB: Float = 083 /// Render blocks in which the master output exceeded full scale.84 public var clippedBlocks: UInt32 = 085 public var renderCalls: UInt64 = 086 public var lastRenderNanos: UInt64 = 087 public var maxRenderNanos: UInt64 = 088 public var totalRenderNanos: UInt64 = 089 /// Render calls that took longer than the buffer they produced.90 public var overloads: UInt32 = 091 public var eventsApplied: UInt64 = 092 public var trackedEvents: UInt64 = 093 /// Tracked events applied after their target sample.94 public var lateEvents: UInt64 = 095 public var maxLateSamples: Int64 = 096 public var totalLateSamples: Int64 = 097 public var recordedFrames: Int64 = 098 public var recordOverruns: UInt32 = 099 public var recording = false100}101102/// Single-writer, multi-reader snapshot cell (sequence lock). Readers never block the writer.103final class SnapshotCell<T: BitwiseCopyable>: @unchecked Sendable {104 private let sequence = Atomic<UInt64>(0)105 private let storage: UnsafeMutablePointer<T>106 private let count: Int107108 init(count: Int, initial: T) { self.count = count; storage = .allocate(capacity: count); storage.initialize(repeating: initial, count: count) }109 deinit { storage.deallocate() }110111 @inline(__always) func write(_ body: (UnsafeMutablePointer<T>) -> Void) {112 sequence.add(1, ordering: .acquiringAndReleasing)113 body(storage)114 sequence.add(1, ordering: .acquiringAndReleasing)115 }116117 func read() -> [T] {118 var out = [T](); out.reserveCapacity(count)119 while true {120 let s = sequence.load(ordering: .acquiring)121 if s & 1 == 1 { continue }122 out.removeAll(keepingCapacity: true)123 for i in 0 ..< count { out.append(storage[i]) }124 if sequence.load(ordering: .acquiring) == s { return out }125 }126 }127}128129/// Lock-free stereo ring from the render thread to the recorder thread.130final class AudioRing: @unchecked Sendable {131 let capacity: Int132 private let mask: Int133 private let left: UnsafeMutablePointer<Float>134 private let right: UnsafeMutablePointer<Float>135 private let writeIndex = Atomic<Int>(0)136 private let readIndex = Atomic<Int>(0)137138 init(capacityFrames: Int) {139 var c = 1024140 while c < capacityFrames { c <<= 1 }141 capacity = c; mask = c - 1142 left = .allocate(capacity: c); right = .allocate(capacity: c)143 left.initialize(repeating: 0, count: c); right.initialize(repeating: 0, count: c)144 }145146 deinit { left.deallocate(); right.deallocate() }147148 var available: Int { writeIndex.load(ordering: .acquiring) - readIndex.load(ordering: .acquiring) }149150 /// Render thread. Returns false (and writes nothing) when the reader fell too far behind.151 func write(_ l: UnsafePointer<Float>, _ r: UnsafePointer<Float>, _ n: Int) -> Bool {152 let w = writeIndex.load(ordering: .relaxed)153 if capacity - (w - readIndex.load(ordering: .acquiring)) < n { return false }154 let start = w & mask155 let first = min(n, capacity - start)156 (left + start).update(from: l, count: first); (right + start).update(from: r, count: first)157 if first < n { left.update(from: l + first, count: n - first); right.update(from: r + first, count: n - first) }158 writeIndex.store(w + n, ordering: .releasing)159 return true160 }161162 /// Recorder thread. Copies up to `maxFrames` interleaved frames into `out`.163 func read(into out: UnsafeMutablePointer<Float>, maxFrames: Int) -> Int {164 let r = readIndex.load(ordering: .relaxed)165 let n = min(maxFrames, writeIndex.load(ordering: .acquiring) - r)166 for i in 0 ..< n { let k = (r + i) & mask; out[2 * i] = left[k]; out[2 * i + 1] = right[k] }167 readIndex.store(r + n, ordering: .releasing)168 return n169 }170171 func reset() { readIndex.store(writeIndex.load(ordering: .acquiring), ordering: .releasing) }172}173174private struct ChannelStrip {175 var gain = LinearRamp(1)176 var volume = LinearRamp(1)177 var eqLow = LinearRamp(0), eqMid = LinearRamp(0), eqHigh = LinearRamp(0), eqLowMid = LinearRamp(0)178 var filterKnob = LinearRamp(0), highpass = LinearRamp(20), lowpass = LinearRamp(20000), resonance = LinearRamp(0.9)179 var low = StereoBiquad(), lowMid = StereoBiquad(), mid = StereoBiquad(), high = StereoBiquad()180 var hp = StereoBiquad(), lp = StereoBiquad()181 var hpActive = false, lpActive = false, eqActive = false182 var dirty = true183 var cue = false184 /// 0 = A side, 1 = B side, 2 = through (not affected by the crossfader).185 var assign = 2186 var peak: Float = 0187 var rms: Float = 0188}189190/// The complete audio graph. One instance per engine; `render` is called by the audio device or by offline tests.191public final class RenderCore: @unchecked Sendable {192 public let sampleRate: Double193 static let maxFrames = 4096194 private static let chunk = 64195196 let events = SPSCQueue<ControlEvent>(minimumCapacity: 4096)197 let notices = SPSCQueue<RenderNotice>(minimumCapacity: 1024)198 let deckStates = SnapshotCell<DeckRenderState>(count: deckCount, initial: DeckRenderState())199 let engineState = SnapshotCell<EngineRenderState>(count: 1, initial: EngineRenderState())200 let recordRing: AudioRing201202 // Output routing (set while stopped or through atomics; read by the render thread).203 let masterLeft = Atomic<Int>(0)204 let masterRight = Atomic<Int>(1)205 let cueLeft = Atomic<Int>(-1)206 let cueRight = Atomic<Int>(-1)207208 private var voices: [DeckVoice]209 private let strips: UnsafeMutablePointer<ChannelStrip>210 private let racks: UnsafeMutablePointer<Unmanaged<EffectUnit>?>211 private let limiter: LimiterEffect212 private var pending: UnsafeMutablePointer<ControlEvent>213 private var pendingCount = 0214 private static let pendingCapacity = 512215216 private var crossfader = LinearRamp(0.5)217 private var crossfaderCurve = 0218 private var masterVolume = LinearRamp(1)219 private var cueMix = LinearRamp(0)220 private var cueVolume = LinearRamp(1)221 private var limiterOn = true222 private var fourBand = false223 private var splitCue = false224 private var recording = false225226 private var sampleTime: Int64 = 0227 private var clockBPM = 120.0228 private var clockBeat = 0.0229 private var clockSample: Int64 = 0230 private var state = EngineRenderState()231232 private let deckL: UnsafeMutablePointer<Float>233 private let deckR: UnsafeMutablePointer<Float>234 private let mixL: UnsafeMutablePointer<Float>235 private let mixR: UnsafeMutablePointer<Float>236 private let cueL: UnsafeMutablePointer<Float>237 private let cueR: UnsafeMutablePointer<Float>238 private let peakFall: Float239240 public init(sampleRate: Double) {241 self.sampleRate = sampleRate242 voices = (0 ..< deckCount).map { _ in DeckVoice(engineRate: sampleRate) }243 strips = .allocate(capacity: deckCount); strips.initialize(repeating: ChannelStrip(), count: deckCount)244 racks = .allocate(capacity: (deckCount + 1) * rackSlotCount); racks.initialize(repeating: nil, count: (deckCount + 1) * rackSlotCount)245 limiter = LimiterEffect(sampleRate: sampleRate)246 limiter.setEnabled(true); limiter.setMix(1)247 // Run the enable fade now, on silence, so the ceiling holds from the very first block.248 let primeL = UnsafeMutablePointer<Float>.allocate(capacity: 2048), primeR = UnsafeMutablePointer<Float>.allocate(capacity: 2048)249 primeL.initialize(repeating: 0, count: 2048); primeR.initialize(repeating: 0, count: 2048)250 for _ in 0 ..< 4 { limiter.render(primeL, primeR, 2048) }251 primeL.deallocate(); primeR.deallocate()252 pending = .allocate(capacity: Self.pendingCapacity)253 recordRing = AudioRing(capacityFrames: Int(sampleRate * 8))254 func buffer() -> UnsafeMutablePointer<Float> { let p = UnsafeMutablePointer<Float>.allocate(capacity: Self.maxFrames); p.initialize(repeating: 0, count: Self.maxFrames); return p }255 deckL = buffer(); deckR = buffer(); mixL = buffer(); mixR = buffer(); cueL = buffer(); cueR = buffer()256 // Meters fall 24 dB per second.257 peakFall = powf(10, -24.0 / 20.0 * Float(Self.chunk) / Float(sampleRate))258 strips[0].assign = 0; strips[1].assign = 1; strips[2].assign = 0; strips[3].assign = 1259 }260261 deinit {262 // Tracks and effect units are kept alive by the control plane (DJEngine.retained), not by this object.263 strips.deallocate(); racks.deallocate(); pending.deallocate()264 deckL.deallocate(); deckR.deallocate(); mixL.deallocate(); mixR.deallocate(); cueL.deallocate(); cueR.deallocate()265 }266267 @inline(__always) private func rackSlot(_ rack: Int16, _ slot: Int) -> Int { (rack < 0 ? deckCount : Int(rack)) * rackSlotCount + slot }268269 // MARK: Events270271 private func rampSamples(_ seconds: Double) -> Int { max(Int(0.004 * sampleRate), Int(seconds * sampleRate)) }272273 private func apply(_ e: ControlEvent) {274 state.eventsApplied += 1275 if e.tracked {276 state.trackedEvents += 1277 let late = e.time > 0 ? sampleTime - e.time : 0278 if late > 0 { state.lateEvents += 1; state.totalLateSamples += late; state.maxLateSamples = max(state.maxLateSamples, late) }279 }280 guard let kind = EventKind(rawValue: e.kind) else { return }281 let d = Int(e.deck)282 switch kind {283 case .deckSetTrack:284 guard d >= 0, d < deckCount else { return }285 let ref = e.pointer.map { Unmanaged<TrackBuffer>.fromOpaque($0) }286 if let old = voices[d].setTrack(ref) { notices.push(RenderNotice(kind: NoticeKind.releaseTrack.rawValue, deck: e.deck, pointer: old.toOpaque())) }287 case .deckPlay: if d >= 0, d < deckCount { voices[d].play() }288 case .deckPause: if d >= 0, d < deckCount { voices[d].pause() }289 case .deckSeek: if d >= 0, d < deckCount { voices[d].seek(e.a) }290 case .deckRate: if d >= 0, d < deckCount, e.a.isFinite { voices[d].targetRate = min(4, max(0.05, e.a)) }291 case .deckKeylock: if d >= 0, d < deckCount { voices[d].keylock = e.a >= 0.5 }292 case .deckPitch: if d >= 0, d < deckCount, e.a.isFinite { voices[d].pitchRatio = min(4, max(0.25, e.a)) }293 case .deckReverse: if d >= 0, d < deckCount { voices[d].reverse = e.a >= 0.5 }294 case .deckLoop: if d >= 0, d < deckCount { voices[d].setLoop(start: e.a, end: e.b) }295 case .deckLoopOff: if d >= 0, d < deckCount { voices[d].clearLoop() }296 case .deckBrake: if d >= 0, d < deckCount { voices[d].brake(seconds: e.a) }297 case .clock:298 if e.a.isFinite, e.a > 20, e.a < 400 { clockBPM = e.a }299 clockBeat = e.b; clockSample = e.time > 0 ? e.time : sampleTime300 case .param: applyParam(e)301 case .fxSet:302 let slot = Int(e.index)303 guard slot >= 0, slot < rackSlotCount, e.deck >= -1, d < deckCount else { return }304 let i = rackSlot(e.deck, slot)305 if let old = racks[i] { notices.push(RenderNotice(kind: NoticeKind.releaseEffect.rawValue, deck: e.deck, pointer: old.toOpaque())) }306 racks[i] = e.pointer.map { Unmanaged<EffectUnit>.fromOpaque($0) }307 case .fxSwap:308 let a = Int(e.index & 0xFF), b = Int(e.index >> 8)309 guard a >= 0, a < rackSlotCount, b >= 0, b < rackSlotCount, e.deck >= -1, d < deckCount else { return }310 let ia = rackSlot(e.deck, a), ib = rackSlot(e.deck, b)311 let t = racks[ia]; racks[ia] = racks[ib]; racks[ib] = t312 case .fxEnable, .fxMix, .fxParam:313 let slot = Int(e.index & 0xFF)314 guard slot >= 0, slot < rackSlotCount, e.deck >= -1, d < deckCount, let unit = racks[rackSlot(e.deck, slot)] else { return }315 unit._withUnsafeGuaranteedRef { u in316 switch kind {317 case .fxEnable: u.setEnabled(e.a >= 0.5)318 case .fxMix: u.setMix(Float(e.a))319 default: u.setParameter(Int(e.index >> 8), Float(e.a))320 }321 }322 case .record:323 recording = e.a >= 0.5324 if recording { state.recordedFrames = 0; state.recordOverruns = 0 }325 case .panic:326 // Emergency: bypass every effect at once.327 for i in 0 ..< (deckCount + 1) * rackSlotCount { racks[i]?._withUnsafeGuaranteedRef { $0.setEnabled(false) } }328 }329 }330331 private func applyParam(_ e: ControlEvent) {332 guard let p = MixParam(rawValue: e.index), e.a.isFinite else { return }333 let n = rampSamples(e.b)334 let v = Float(e.a)335 let d = Int(e.deck)336 switch p {337 case .crossfader: crossfader.set(clampf(v, 0, 1), overSamples: n)338 case .crossfaderCurve: crossfaderCurve = Int(e.a)339 case .masterVolume: masterVolume.set(dbToLinear(v), overSamples: n)340 case .limiter: limiterOn = e.a >= 0.5341 case .cueMix: cueMix.set(clampf(v, 0, 1), overSamples: n)342 case .cueVolume: cueVolume.set(dbToLinear(v), overSamples: n)343 case .eqBands: fourBand = e.a >= 3.5; for i in 0 ..< deckCount { strips[i].dirty = true }344 case .splitCue: splitCue = e.a >= 0.5345 default:346 guard d >= 0, d < deckCount else { return }347 switch p {348 case .gain: strips[d].gain.set(dbToLinear(v), overSamples: n)349 case .volume: strips[d].volume.set(dbToLinear(v), overSamples: n)350 case .eqLow: strips[d].eqLow.set(v, overSamples: n)351 case .eqMid: strips[d].eqMid.set(v, overSamples: n)352 case .eqHigh: strips[d].eqHigh.set(v, overSamples: n)353 case .eqLowMid: strips[d].eqLowMid.set(v, overSamples: n)354 case .filterKnob: strips[d].filterKnob.set(clampf(v, -1, 1), overSamples: n)355 case .highpass: strips[d].highpass.set(clampf(v, 20, 20000), overSamples: n)356 case .lowpass: strips[d].lowpass.set(clampf(v, 20, 20000), overSamples: n)357 case .resonance: strips[d].resonance.set(clampf(v, 0.5, 10), overSamples: n)358 case .cue: strips[d].cue = e.a >= 0.5359 case .assign: strips[d].assign = min(2, max(0, Int(e.a)))360 default: break361 }362 strips[d].dirty = true363 }364 }365366 /// Moves newly queued events into the time-ordered pending list.367 private func intake() {368 while pendingCount < Self.pendingCapacity, let e = events.pop() {369 if e.time <= sampleTime { apply(e); continue }370 var i = pendingCount371 while i > 0, pending[i - 1].time > e.time { pending[i] = pending[i - 1]; i -= 1 }372 pending[i] = e; pendingCount += 1373 }374 }375376 private func applyDue() {377 var k = 0378 while k < pendingCount, pending[k].time <= sampleTime { apply(pending[k]); k += 1 }379 if k > 0 {380 for i in k ..< pendingCount { pending[i - k] = pending[i] }381 pendingCount -= k382 }383 }384385 // MARK: Render386387 /// Kill threshold: at the bottom of its range an EQ band removes the band entirely.388 @inline(__always) private func eqGain(_ db: Float) -> Float { db <= -25.9 ? -80 : db }389390 private func updateFilters(_ s: inout ChannelStrip, _ n: Int) {391 let low = s.eqLow.advance(n), mid = s.eqMid.advance(n), high = s.eqHigh.advance(n), lowMid = s.eqLowMid.advance(n)392 let knob = s.filterKnob.advance(n), hpExplicit = s.highpass.advance(n), lpExplicit = s.lowpass.advance(n), q = s.resonance.advance(n)393 let ramping = s.eqLow.isRamping || s.eqMid.isRamping || s.eqHigh.isRamping || s.eqLowMid.isRamping || s.filterKnob.isRamping || s.highpass.isRamping || s.lowpass.isRamping || s.resonance.isRamping394 guard s.dirty || ramping else { return }395 s.dirty = ramping396 let sr = Float(sampleRate)397 if fourBand {398 s.low.c = .lowShelf(frequency: 100, gainDB: eqGain(low), sampleRate: sr)399 s.lowMid.c = .peaking(frequency: 400, q: 0.9, gainDB: eqGain(lowMid) < -40 ? -40 : lowMid, sampleRate: sr)400 s.mid.c = .peaking(frequency: 2000, q: 0.9, gainDB: eqGain(mid) < -40 ? -40 : mid, sampleRate: sr)401 s.high.c = .highShelf(frequency: 8000, gainDB: eqGain(high), sampleRate: sr)402 s.eqActive = low != 0 || lowMid != 0 || mid != 0 || high != 0403 } else {404 s.low.c = .lowShelf(frequency: 200, gainDB: eqGain(low), sampleRate: sr)405 s.mid.c = .peaking(frequency: 1000, q: 0.7, gainDB: eqGain(mid) < -40 ? -40 : mid, sampleRate: sr)406 s.high.c = .highShelf(frequency: 3000, gainDB: eqGain(high), sampleRate: sr)407 s.eqActive = low != 0 || mid != 0 || high != 0408 }409 // Bipolar knob: right half sweeps a high-pass up, left half sweeps a low-pass down.410 var hpFreq = hpExplicit, lpFreq = lpExplicit411 if knob > 0.02 { hpFreq = max(hpFreq, 20 * powf(500, knob)) } else if knob < -0.02 { lpFreq = min(lpFreq, 20000 * powf(1.0 / 200, -knob)) }412 let hpOn = hpFreq > 20.5, lpOn = lpFreq < 19900413 if hpOn { s.hp.c = .highpass(frequency: hpFreq, q: q, sampleRate: sr) } else if s.hpActive { s.hp.reset() }414 if lpOn { s.lp.c = .lowpass(frequency: lpFreq, q: q, sampleRate: sr) } else if s.lpActive { s.lp.reset() }415 s.hpActive = hpOn; s.lpActive = lpOn416 }417418 @inline(__always) private func crossfaderGains(_ x: Float) -> (a: Float, b: Float) {419 switch crossfaderCurve {420 case 1: return (min(1, 2 * (1 - x)), min(1, 2 * x)) // linear: both sides full in the centre421 case 2: return (x < 0.95 ? 1 : (1 - x) / 0.05, x > 0.05 ? 1 : x / 0.05) // cut: full until the last 5 %422 default: return (cosf(x * .pi / 2), sinf(x * .pi / 2)) // smooth: constant power423 }424 }425426 private func renderChunk(_ offset: Int, _ n: Int) {427 let mL = mixL + offset, mR = mixR + offset, cL = cueL + offset, cR = cueR + offset428 vDSP_vclr(mL, 1, vDSP_Length(n)); vDSP_vclr(mR, 1, vDSP_Length(n))429 vDSP_vclr(cL, 1, vDSP_Length(n)); vDSP_vclr(cR, 1, vDSP_Length(n))430 let beat = clockBeat + Double(sampleTime - clockSample) * clockBPM / 60 / sampleRate431 let x0 = crossfader.value432 let x1 = crossfader.advance(n)433 let g0 = crossfaderGains(x0), g1 = crossfaderGains(x1)434435 for d in 0 ..< deckCount {436 let voice = voices[d]437 let rackBase = d * rackSlotCount438 var rackActive = false439 for sIdx in 0 ..< rackSlotCount { if let u = racks[rackBase + sIdx], u._withUnsafeGuaranteedRef({ $0.isActive }) { rackActive = true; break } }440 if !voice.playing, !rackActive, strips[d].peak < 1e-5 {441 // Idle channel: keep the ramps moving so they are settled when it starts.442 voice.render(deckL, deckR, n)443 var s = strips[d]444 _ = s.gain.advance(n); _ = s.volume.advance(n); updateFilters(&s, n); s.peak = 0; s.rms = 0445 strips[d] = s446 for sIdx in 0 ..< rackSlotCount { racks[rackBase + sIdx]?._withUnsafeGuaranteedRef { $0.setTransport(bpm: clockBPM, beatPosition: beat); $0.render(deckL, deckR, n) } }447 continue448 }449 voice.render(deckL, deckR, n)450 var s = strips[d]451 updateFilters(&s, n)452 // Trim.453 var ga = s.gain.value; let gb = s.gain.advance(n); var gstep = (gb - ga) / Float(n)454 vDSP_vrampmul2(deckL, deckR, 1, &ga, &gstep, deckL, deckR, 1, vDSP_Length(n))455 if s.eqActive {456 s.low.process(deckL, deckR, n); s.mid.process(deckL, deckR, n); s.high.process(deckL, deckR, n)457 if fourBand { s.lowMid.process(deckL, deckR, n) }458 }459 if s.hpActive { s.hp.process(deckL, deckR, n) }460 if s.lpActive { s.lp.process(deckL, deckR, n) }461 for sIdx in 0 ..< rackSlotCount {462 racks[rackBase + sIdx]?._withUnsafeGuaranteedRef { $0.setTransport(bpm: clockBPM, beatPosition: beat); $0.render(deckL, deckR, n) }463 }464 // Pre-fader listen.465 if s.cue { vDSP_vadd(cL, 1, deckL, 1, cL, 1, vDSP_Length(n)); vDSP_vadd(cR, 1, deckR, 1, cR, 1, vDSP_Length(n)) }466 // Fader.467 var va = s.volume.value; let vb = s.volume.advance(n); var vstep = (vb - va) / Float(n)468 vDSP_vrampmul2(deckL, deckR, 1, &va, &vstep, deckL, deckR, 1, vDSP_Length(n))469 // Meter (post-fader).470 var pk: Float = 0, pk2: Float = 0, ms: Float = 0471 vDSP_maxmgv(deckL, 1, &pk, vDSP_Length(n)); vDSP_maxmgv(deckR, 1, &pk2, vDSP_Length(n)); vDSP_measqv(deckL, 1, &ms, vDSP_Length(n))472 s.peak = max(max(pk, pk2), s.peak * peakFall)473 s.rms = s.rms * 0.9 + sqrtf(ms) * 0.1474 strips[d] = s475 // Crossfader and sum.476 var xa: Float = 1, xb: Float = 1477 if s.assign == 0 { xa = g0.a; xb = g1.a } else if s.assign == 1 { xa = g0.b; xb = g1.b }478 var xstep = (xb - xa) / Float(n)479 var xa2 = xa, xstep2 = xstep480 vDSP_vrampmuladd(deckL, 1, &xa, &xstep, mL, 1, vDSP_Length(n))481 vDSP_vrampmuladd(deckR, 1, &xa2, &xstep2, mR, 1, vDSP_Length(n))482 _ = xstep483 }484485 // Master rack.486 let base = deckCount * rackSlotCount487 for sIdx in 0 ..< rackSlotCount {488 racks[base + sIdx]?._withUnsafeGuaranteedRef { $0.setTransport(bpm: clockBPM, beatPosition: beat); $0.render(mL, mR, n) }489 }490 var ma = masterVolume.value; let mb = masterVolume.advance(n); var mstep = (mb - ma) / Float(n)491 vDSP_vrampmul2(mL, mR, 1, &ma, &mstep, mL, mR, 1, vDSP_Length(n))492 limiter.setEnabled(limiterOn)493 limiter.render(mL, mR, n)494 var pl: Float = 0, pr: Float = 0, ms: Float = 0495 vDSP_maxmgv(mL, 1, &pl, vDSP_Length(n)); vDSP_maxmgv(mR, 1, &pr, vDSP_Length(n)); vDSP_measqv(mL, 1, &ms, vDSP_Length(n))496 let after = max(pl, pr)497 // Gain reduction as the limiter itself applied it, with a short hold so brief reductions stay readable.498 let reduction: Float = limiterOn ? 20 * log10f(max(limiter.lastMinimumGain, 1e-4)) : 0499 state.limiterReductionDB = min(reduction, state.limiterReductionDB * 0.97)500 state.masterPeakL = max(pl, state.masterPeakL * peakFall); state.masterPeakR = max(pr, state.masterPeakR * peakFall)501 state.masterRMS = state.masterRMS * 0.9 + sqrtf(ms) * 0.1502 if after > 1.0 { state.clippedBlocks &+= 1 }503504 if recording {505 if recordRing.write(mL, mR, n) { state.recordedFrames += Int64(n) } else { state.recordOverruns &+= 1 }506 }507508 // Cue bus: pre-fader channels blended with the master.509 let c0 = cueMix.value, c1 = cueMix.advance(n)510 let v0 = cueVolume.value, v1 = cueVolume.advance(n)511 var cuePk: Float = 0512 for i in 0 ..< n {513 let t = Float(i) / Float(n)514 let mixAmount = c0 + (c1 - c0) * t, vol = v0 + (v1 - v0) * t515 cL[i] = (cL[i] * (1 - mixAmount) + mL[i] * mixAmount) * vol516 cR[i] = (cR[i] * (1 - mixAmount) + mR[i] * mixAmount) * vol517 cuePk = max(cuePk, abs(cL[i]))518 }519 state.cuePeak = max(cuePk, state.cuePeak * peakFall)520 }521522 /// Renders `frameCount` frames into the device channels. Real-time safe.523 public func render(frameCount: Int, channels: UnsafePointer<UnsafeMutablePointer<Float>?>, channelCount: Int) {524 let started = mach_absolute_time()525 let total = min(frameCount, Self.maxFrames)526 var done = 0527 intake()528 while done < total {529 applyDue()530 var n = min(Self.chunk, total - done)531 if pendingCount > 0 { n = max(1, min(n, Int(pending[0].time - sampleTime))) }532 renderChunk(done, n)533 sampleTime += Int64(n); done += n534 for d in 0 ..< deckCount {535 if voices[d].reachedEnd { voices[d].reachedEnd = false; notices.push(RenderNotice(kind: NoticeKind.trackEnded.rawValue, deck: Int16(d), pointer: nil)) }536 if voices[d].brakeFinished { voices[d].brakeFinished = false; notices.push(RenderNotice(kind: NoticeKind.brakeFinished.rawValue, deck: Int16(d), pointer: nil)) }537 }538 }539 // Route to the device.540 let ml = masterLeft.load(ordering: .relaxed), mr = masterRight.load(ordering: .relaxed)541 let cl = cueLeft.load(ordering: .relaxed), cr = cueRight.load(ordering: .relaxed)542 for c in 0 ..< channelCount { if let p = channels[c] { vDSP_vclr(p, 1, vDSP_Length(frameCount)) } }543 if splitCue, cl < 0, channelCount >= 2, let l = channels[0], let r = channels[1] {544 // Split cue for stereo-only devices: master in the left ear, cue in the right, both mono.545 for i in 0 ..< total { l[i] = 0.5 * (mixL[i] + mixR[i]); r[i] = 0.5 * (cueL[i] + cueR[i]) }546 } else {547 if ml >= 0, ml < channelCount, let p = channels[ml] { p.update(from: mixL, count: total) }548 if mr >= 0, mr < channelCount, let p = channels[mr] {549 if mr == ml { vDSP_vadd(p, 1, mixR, 1, p, 1, vDSP_Length(total)) } else { p.update(from: mixR, count: total) }550 }551 if cl >= 0, cl < channelCount, cl != ml, cl != mr, let p = channels[cl] { p.update(from: cueL, count: total) }552 if cr >= 0, cr < channelCount, cr != ml, cr != mr, let p = channels[cr] { p.update(from: cueR, count: total) }553 }554 // Publish.555 let elapsed = mach_absolute_time() - started556 state.sampleTime = sampleTime; state.hostTime = started; state.recording = recording557 state.renderCalls &+= 1; state.lastRenderNanos = elapsed &* Self.timebaseNumer / Self.timebaseDenom558 state.totalRenderNanos &+= state.lastRenderNanos559 state.maxRenderNanos = max(state.maxRenderNanos, state.lastRenderNanos)560 if Double(state.lastRenderNanos) > Double(frameCount) / sampleRate * 1e9 { state.overloads &+= 1 }561 let snapshot = state562 engineState.write { $0[0] = snapshot }563 deckStates.write { out in564 for d in 0 ..< deckCount {565 let v = voices[d]566 var ds = DeckRenderState()567 ds.position = v.playhead; ds.rate = v.currentRate; ds.playing = v.playing; ds.loaded = v.isLoaded; ds.loopActive = v.loopActive568 ds.loopStart = v.loopStart; ds.loopEnd = v.loopEnd; ds.peak = strips[d].peak; ds.rms = strips[d].rms569 out[d] = ds570 }571 }572 }573574 private static let timebase: mach_timebase_info_data_t = { var t = mach_timebase_info_data_t(); mach_timebase_info(&t); return t }()575 private static let timebaseNumer = UInt64(timebase.numer)576 private static let timebaseDenom = UInt64(timebase.denom)577578 /// Resets the measurement counters (benchmarks).579 /// Public entry point for the benchmark tool.580 public func resetCountersForBenchmark() { resetCounters() }581582 func resetCounters() {583 // Called from the control plane while the device is stopped, or accepted as a benign race in diagnostics.584 state.maxRenderNanos = 0; state.totalRenderNanos = 0; state.renderCalls = 0; state.overloads = 0585 state.lateEvents = 0; state.maxLateSamples = 0; state.totalLateSamples = 0; state.trackedEvents = 0; state.clippedBlocks = 0586 }587}588