Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXDJEngine/ControlSurface.swift3// Description: The control surface shared by on-screen knobs and MIDI controllers: scaling between a 0...1 control4// position and a parameter value, the catalogue of mappable targets, and the dispatch of MIDI target events.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXDSP10import ORIXMIDI11import ORIXScript1213/// Converts between a control position (0...1) and a parameter value, with the taper a DJ expects.14public enum ParamScale {15 public static func normalized(_ def: ParamDef, _ value: Value) -> Double {16 switch (def.type, value) {17 case let (.gain, .gain(db)):18 if def.min <= -59 {19 // Fader law: -60 dB (silence) at the bottom, 40 dB per decade of travel.20 return db <= def.min ? 0 : min(1, max(0, pow(10, (db - def.max) / 40)))21 }22 // Centre-detent gains (EQ, trim): 0 dB in the middle.23 return db < 0 ? 0.5 * (1 - db / def.min) : 0.5 + 0.5 * (def.max > 0 ? db / def.max : 0)24 case let (.frequency, .frequency(f)): return log(max(f, def.min) / def.min) / log(def.max / def.min)25 case let (.number, .number(x)): return def.max > def.min ? (x - def.min) / (def.max - def.min) : 026 case let (.bool, .bool(b)): return b ? 1 : 027 case let (.duration, .duration(span)):28 let x = def.durationUnit == .beats ? span.magnitude : span.magnitude * 100029 if def.min > 0, def.durationUnit == .beats { return log(max(x, def.min) / def.min) / log(def.max / def.min) }30 return def.max > def.min ? (x - def.min) / (def.max - def.min) : 031 default: return 032 }33 }3435 public static func value(_ def: ParamDef, normalized n: Double) -> Value {36 let x = min(1, max(0, n))37 switch def.type {38 case .gain:39 if def.min <= -59 { return .gain(x <= 0.001 ? def.min : max(def.min, def.max + 40 * log10(x))) }40 return .gain(x < 0.5 ? def.min * (1 - x / 0.5) : def.max * (x - 0.5) / 0.5)41 case .frequency: return .frequency(def.min * pow(def.max / def.min, x))42 case .bool: return .bool(x >= 0.5)43 case .duration:44 if def.durationUnit == .beats, def.min > 0 {45 // Snap to musical lengths: powers of two, with dotted values in between.46 let raw = def.min * pow(def.max / def.min, x)47 let steps = musicalLengths.filter { $0 >= def.min - 1e-9 && $0 <= def.max + 1e-9 }48 return .duration(.beats(steps.min { abs(log($0 / raw)) < abs(log($1 / raw)) } ?? raw))49 }50 return .duration(.seconds((def.min + (def.max - def.min) * x) / 1000))51 default: return .number(def.min + (def.max - def.min) * x)52 }53 }5455 public static let musicalLengths: [Double] = [1.0 / 32, 1.0 / 16, 1.0 / 8, 3.0 / 16, 1.0 / 4, 3.0 / 8, 1.0 / 2, 3.0 / 4, 1, 1.5, 2, 3, 4, 8]5657 /// "1/4", "3/4", "2" for a length in beats.58 public static func beatLabel(_ beats: Double) -> String {59 for (den, name) in [(2.0, "2"), (4, "4"), (8, "8"), (16, "16"), (32, "32")] {60 let num = beats * den61 if abs(num - num.rounded()) < 1e-6, num.rounded() < den { return "\(Int(num.rounded()))/\(name)" }62 }63 return beats == beats.rounded() ? String(Int(beats)) : String(format: "%.2f", beats)64 }65}6667public enum ControlTargetKind: String, Sendable, Codable { case value, toggle, trigger }6869/// Something a hardware control (or a keyboard shortcut) can drive.70public struct ControlTarget: Sendable, Identifiable, Equatable {71 public var id: String72 public var name: String73 public var group: String74 public var kind: ControlTargetKind75}7677public enum ControlTargets {78 /// Tempo fader range: +/- 8 %.79 public static let tempoRange = 0.088081 public static let all: [ControlTarget] = {82 var out: [ControlTarget] = []83 for (d, letter) in deckLetters.enumerated() {84 _ = d85 let g = "Deck \(letter)"86 let p = "deck.\(letter)."87 out += [88 ControlTarget(id: p + "play", name: "Play / pause", group: g, kind: .trigger),89 ControlTarget(id: p + "cue", name: "Cue", group: g, kind: .trigger),90 ControlTarget(id: p + "setCue", name: "Set cue point", group: g, kind: .trigger),91 ControlTarget(id: p + "sync", name: "Sync", group: g, kind: .toggle),92 ControlTarget(id: p + "keylock", name: "Key lock", group: g, kind: .toggle),93 ControlTarget(id: p + "quantize", name: "Quantize", group: g, kind: .toggle),94 ControlTarget(id: p + "reverse", name: "Reverse", group: g, kind: .toggle),95 ControlTarget(id: p + "cueMonitor", name: "Headphone cue", group: g, kind: .toggle),96 ControlTarget(id: p + "volume", name: "Channel fader", group: g, kind: .value),97 ControlTarget(id: p + "gain", name: "Trim", group: g, kind: .value),98 ControlTarget(id: p + "eq.high", name: "EQ high", group: g, kind: .value),99 ControlTarget(id: p + "eq.mid", name: "EQ mid", group: g, kind: .value),100 ControlTarget(id: p + "eq.low", name: "EQ low", group: g, kind: .value),101 ControlTarget(id: p + "filter", name: "Filter", group: g, kind: .value),102 ControlTarget(id: p + "tempo", name: "Tempo fader (±8 %)", group: g, kind: .value),103 ControlTarget(id: p + "keyShift", name: "Key shift", group: g, kind: .value),104 ControlTarget(id: p + "loopExit", name: "Exit loop", group: g, kind: .trigger),105 ControlTarget(id: p + "loopHalve", name: "Halve loop", group: g, kind: .trigger),106 ControlTarget(id: p + "loopDouble", name: "Double loop", group: g, kind: .trigger),107 ControlTarget(id: p + "brake", name: "Tape stop", group: g, kind: .trigger),108 ]109 for beats in [1, 2, 4, 8, 16] { out.append(ControlTarget(id: p + "loop.\(beats)", name: "Loop \(beats) beat\(beats == 1 ? "" : "s")", group: g, kind: .trigger)) }110 for beats in [-4, -1, 1, 4] { out.append(ControlTarget(id: p + "jump.\(beats)", name: "Beat jump \(beats > 0 ? "+" : "")\(beats)", group: g, kind: .trigger)) }111 for i in 1 ... ScriptSchema.hotCueCount { out.append(ControlTarget(id: p + "hotcue.\(i)", name: "Hot cue \(i)", group: g, kind: .trigger)) }112 }113 out += [114 ControlTarget(id: "mixer.crossfader", name: "Crossfader", group: "Mixer", kind: .value),115 ControlTarget(id: "mixer.master.volume", name: "Master volume", group: "Mixer", kind: .value),116 ControlTarget(id: "mixer.cue.mix", name: "Cue / master blend", group: "Mixer", kind: .value),117 ControlTarget(id: "mixer.cue.volume", name: "Headphone volume", group: "Mixer", kind: .value),118 ControlTarget(id: "mixer.master.limiter", name: "Limiter", group: "Mixer", kind: .toggle),119 ]120 for kind in EffectKind.allCases {121 let name = EffectCatalog.descriptor(kind).displayName122 out.append(ControlTarget(id: "fx.\(kind.rawValue).enabled", name: "\(name) on / off", group: "Master effects", kind: .toggle))123 out.append(ControlTarget(id: "fx.\(kind.rawValue).mix", name: "\(name) mix", group: "Master effects", kind: .value))124 }125 for i in 1 ... ScriptSchema.triggerCount { out.append(ControlTarget(id: "automation.trigger.\(i)", name: "Automation trigger \(i)", group: "Automation", kind: .trigger)) }126 out.append(ControlTarget(id: "automation.panic", name: "Emergency stop", group: "Automation", kind: .trigger))127 return out128 }()129130 public static func target(_ id: String) -> ControlTarget? { table[id] }131 private static let table = Dictionary(uniqueKeysWithValues: all.map { ($0.id, $0) })132133 /// Parameter address of a value or toggle target, when it maps straight to a parameter.134 public static func address(_ id: String) -> ParamAddress? {135 let parts = id.split(separator: ".").map(String.init)136 guard parts.count >= 2 else { return nil }137 switch parts[0] {138 case "deck":139 guard parts.count >= 3, let d = deckLetters.firstIndex(of: parts[1]) else { return nil }140 var key = parts.dropFirst(2).joined(separator: ".")141 if key == "cueMonitor" { key = "cue" }142 return ScriptSchema.deckParam(key).map { _ in .deck(d, key) }143 case "mixer":144 let key = parts.dropFirst().joined(separator: ".")145 return ScriptSchema.mixerParam(key).map { _ in .mixer(key) }146 case "fx":147 guard parts.count >= 3, let kind = EffectKind(rawValue: parts[1]) else { return nil }148 let key = parts.dropFirst(2).joined(separator: ".")149 return ScriptSchema.fxParam(kind, key).map { _ in .fx(kind, key) }150 default: return nil151 }152 }153}154155/// Applies control events to the engine. One instance serves every MIDI device and the keyboard.156public final class ControlSurface: @unchecked Sendable {157 public let engine: DJEngine158 public let host: AutomationHost159160 public init(engine: DJEngine, host: AutomationHost) { self.engine = engine; self.host = host }161162 /// Current position (0...1) of a value or toggle target, for soft takeover and relative encoders.163 public func normalizedValue(of id: String) -> Double? {164 let parts = id.split(separator: ".").map(String.init)165 if parts.count == 3, parts[0] == "deck", parts[2] == "tempo", let d = deckLetters.firstIndex(of: parts[1]) {166 let rate = engine.value(of: .deck(d, "rate"))?.numberValue ?? 1167 return min(1, max(0, 0.5 + (rate - 1) / (2 * ControlTargets.tempoRange)))168 }169 guard let address = ControlTargets.address(id), let def = ScriptSchema.definition(for: address), let v = engine.value(of: address) else { return nil }170 return ParamScale.normalized(def, v)171 }172173 public func setNormalized(_ id: String, _ x: Double) {174 let parts = id.split(separator: ".").map(String.init)175 if parts.count == 3, parts[0] == "deck", parts[2] == "tempo", let d = deckLetters.firstIndex(of: parts[1]) {176 engine.set(.deck(d, "sync"), .bool(false))177 engine.set(.deck(d, "rate"), .number(1 + (min(1, max(0, x)) - 0.5) * 2 * ControlTargets.tempoRange))178 return179 }180 guard let address = ControlTargets.address(id), let def = ScriptSchema.definition(for: address) else { return }181 engine.set(address, ParamScale.value(def, normalized: x))182 }183184 public func toggle(_ id: String) {185 guard let address = ControlTargets.address(id), case let .bool(b)? = engine.value(of: address) else { return }186 engine.set(address, .bool(!b))187 }188189 public func trigger(_ id: String) {190 let parts = id.split(separator: ".").map(String.init)191 if parts.count == 3, parts[0] == "automation", parts[1] == "trigger", let n = Int(parts[2]) { host.fire(trigger: n); return }192 if id == "automation.panic" { host.emergencyStop(); return }193 guard parts.count >= 3, parts[0] == "deck", let d = deckLetters.firstIndex(of: parts[1]) else { return }194 let argument = parts.count >= 4 ? Double(parts[3]) : nil195 switch parts[2] {196 case "play": engine.togglePlay(deck: d)197 case "cue": engine.cue(deck: d)198 case "setCue": engine.setCue(deck: d)199 case "loopExit": engine.loopExit(deck: d)200 case "loopHalve": engine.scaleLoop(deck: d, by: 0.5)201 case "loopDouble": engine.scaleLoop(deck: d, by: 2)202 case "brake": engine.brake(deck: d, seconds: 60 / max(60, engine.clock.bpm))203 case "loop": if let b = argument { engine.loop(deck: d, beats: b) }204 case "jump": if let b = argument { engine.jump(deck: d, beats: b) }205 case "hotcue":206 guard let n = argument.map({ Int($0) - 1 }) else { return }207 // An empty pad stores the current position; a stored pad jumps to it.208 if engine.deckStatus(d).hotcues.indices.contains(n), engine.deckStatus(d).hotcues[n] == nil { engine.setHotcue(deck: d, index: n) } else { engine.hotcue(deck: d, index: n) }209 default: break210 }211 }212213 /// Entry point for MIDI mapping output.214 public func apply(_ event: MIDITargetEvent) {215 switch event {216 case let .value(target, normalized): setNormalized(target, normalized)217 case let .toggle(target):218 if ControlTargets.target(target)?.kind == .trigger { trigger(target) } else { toggle(target) }219 case let .trigger(target):220 if ControlTargets.target(target)?.kind == .toggle { toggle(target) } else { trigger(target) }221 case let .momentary(target, pressed):222 if ControlTargets.target(target)?.kind == .trigger { if pressed { trigger(target) } }223 else if let address = ControlTargets.address(target) { engine.set(address, .bool(pressed)) }224 }225 }226}227