Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXScript/Schema.swift3// Description: The ORIX Script standard library schema: every parameter, property, action and event a script can reach.4// The compiler, the runtime bindings, autocomplete, the reference documentation and the Claude context5// are all derived from this single table, so they cannot drift apart.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import ORIXDSP1112public enum SchemaArea: String, Sendable, Codable, Hashable { case deck, mixer, master, fx }1314/// Address of a parameter or property at run time.15public struct ParamAddress: Hashable, Sendable, Codable, CustomStringConvertible {16 public var area: SchemaArea17 /// Zero-based deck. For `fx`, nil addresses the master rack.18 public var deck: Int?19 public var effect: EffectKind?20 public var key: String2122 public init(area: SchemaArea, deck: Int? = nil, effect: EffectKind? = nil, key: String) {23 self.area = area; self.deck = deck; self.effect = effect; self.key = key24 }2526 public static func deck(_ d: Int, _ key: String) -> ParamAddress { .init(area: .deck, deck: d, key: key) }27 public static func mixer(_ key: String) -> ParamAddress { .init(area: .mixer, key: key) }28 public static func master(_ key: String) -> ParamAddress { .init(area: .master, key: key) }29 public static func fx(_ kind: EffectKind, deck: Int? = nil, _ key: String) -> ParamAddress { .init(area: .fx, deck: deck, effect: kind, key: key) }3031 /// Script path of the address, e.g. `deck.A.filter.highpass` or `fx.delay.time`.32 public var description: String {33 let d = deck.map { deckLetters.indices.contains($0) ? deckLetters[$0] : "?" }34 switch area {35 case .deck: return "deck.\(d ?? "?").\(key)"36 case .mixer: return "mixer.\(key)"37 case .master: return "master.\(key)"38 case .fx: return (d.map { "deck.\($0)." } ?? "") + "fx.\(effect?.rawValue ?? "?").\(key)"39 }40 }41}4243public enum DurationUnit: Sendable, Equatable { case beats, milliseconds, seconds }4445public struct ParamDef: Sendable {46 public let key: String47 public let type: ScriptType48 /// Bounds in the canonical unit (dB, Hz, beats / ms / s, plain number).49 public let min: Double50 public let max: Double51 public let defaultValue: Value52 public let writable: Bool53 /// True when `over` blocks may ramp it.54 public let rampable: Bool55 /// Display unit for plain numbers ("BPM", "%", "st").56 public let unit: String57 public let durationUnit: DurationUnit58 /// Accepted values for string parameters.59 public let allowed: [String]60 public let doc: String6162 init(_ key: String, _ type: ScriptType, _ min: Double = 0, _ max: Double = 0, default d: Value, writable: Bool = true, rampable: Bool? = nil,63 unit: String = "", durationUnit: DurationUnit = .beats, allowed: [String] = [], _ doc: String) {64 self.key = key; self.type = type; self.min = min; self.max = max; defaultValue = d; self.writable = writable65 self.rampable = rampable ?? (writable && (type == .number || type == .gain || type == .frequency))66 self.unit = unit; self.durationUnit = durationUnit; self.allowed = allowed; self.doc = doc67 }6869 public var rangeText: String {70 switch type {71 case .gain: return "\(formatNumber(min)) dB … \(formatNumber(max)) dB"72 case .frequency: return "\(formatNumber(min)) Hz … \(formatNumber(max)) Hz"73 case .number: return unit == "%" ? "\(formatNumber(min * 100)) % … \(formatNumber(max * 100)) %" : "\(formatNumber(min)) … \(formatNumber(max))" + (unit.isEmpty ? "" : " " + unit)74 case .duration: return durationUnit == .beats ? "\(formatNumber(min)) … \(formatNumber(max)) beats" : "\(formatNumber(min)) … \(formatNumber(max)) ms"75 case .bool: return "true / false"76 case .string: return allowed.isEmpty ? "text" : allowed.map { "\"\($0)\"" }.joined(separator: " / ")77 default: return ""78 }79 }80}8182public struct ActionParamDef: Sendable {83 public let name: String84 public let type: ScriptType85 public let optional: Bool86 public let doc: String87}8889public struct ActionDef: Sendable {90 public let name: String91 public let params: [ActionParamDef]92 public let doc: String9394 init(_ name: String, _ params: [ActionParamDef], _ doc: String) { self.name = name; self.params = params; self.doc = doc }95 init(_ name: String, _ doc: String) { self.init(name, [], doc) }9697 public var signature: String {98 name + "(" + params.map { "\($0.name): \($0.type)" + ($0.optional ? "?" : "") }.joined(separator: ", ") + ")"99 }100}101102public struct EventDef: Sendable {103 public let name: String104 public let doc: String105}106107public struct BuiltinDef: Sendable {108 public let name: String109 public let signature: String110 public let doc: String111}112113public struct ActionAddress: Hashable, Sendable, CustomStringConvertible {114 public var area: SchemaArea115 public var deck: Int?116 public var effect: EffectKind?117 public var name: String118119 public init(area: SchemaArea, deck: Int? = nil, effect: EffectKind? = nil, name: String) {120 self.area = area; self.deck = deck; self.effect = effect; self.name = name121 }122123 public var description: String { ParamAddress(area: area, deck: deck, effect: effect, key: name).description }124}125126public enum EventKey: Hashable, Sendable, CustomStringConvertible {127 case deck(Int, String)128 case beat129 case bar130 case trigger(Int)131132 public var description: String {133 switch self {134 case let .deck(d, n): "deck.\(deckLetters.indices.contains(d) ? deckLetters[d] : "?").\(n)"135 case .beat: "beat"136 case .bar: "bar"137 case let .trigger(n): "trigger(\(n))"138 }139 }140}141142private func p(_ name: String, _ type: ScriptType, optional: Bool = false, _ doc: String) -> ActionParamDef {143 ActionParamDef(name: name, type: type, optional: optional, doc: doc)144}145146public enum ScriptSchema {147 public static let deckCount = 4148 public static let hotCueCount = 8149 public static let triggerCount = 16150 public static let crossfaderCurves = ["smooth", "linear", "cut"]151 public static let rampCurves = ["linear", "easeIn", "easeOut", "smooth", "exp"]152153 // MARK: Deck154155 public static let deckParams: [ParamDef] = [156 ParamDef("volume", .gain, -60, 0, default: .gain(0), "Channel fader. -60 dB is silence. A plain number or percentage is taken as a linear fader position."),157 ParamDef("gain", .gain, -24, 12, default: .gain(0), "Input trim before the EQ."),158 ParamDef("eq.low", .gain, -26, 6, default: .gain(0), "Low band of the channel EQ (-26 dB is a full kill)."),159 ParamDef("eq.mid", .gain, -26, 6, default: .gain(0), "Mid band of the channel EQ."),160 ParamDef("eq.high", .gain, -26, 6, default: .gain(0), "High band of the channel EQ."),161 ParamDef("filter", .number, -1, 1, default: .number(0), "Bipolar filter knob: negative closes a low-pass, positive opens a high-pass, 0 is off."),162 ParamDef("filter.highpass", .frequency, 20, 20000, default: .frequency(20), "Channel high-pass corner. 20 Hz is off."),163 ParamDef("filter.lowpass", .frequency, 20, 20000, default: .frequency(20000), "Channel low-pass corner. 20 kHz is off."),164 ParamDef("filter.resonance", .number, 0.5, 10, default: .number(0.9), "Resonance (Q) of the channel filters."),165 ParamDef("rate", .number, 0.5, 2, default: .number(1), "Playback speed factor (1 = original tempo)."),166 ParamDef("bpm", .number, 20, 400, default: .number(120), rampable: true, unit: "BPM", "Effective tempo of the deck. Writing it changes the playback rate; needs an analysed track."),167 ParamDef("keyShift", .number, -12, 12, default: .number(0), unit: "st", "Pitch shift in semitones, independent of tempo."),168 ParamDef("keylock", .bool, default: .bool(false), "Keeps the musical key when the tempo changes (time stretching)."),169 ParamDef("sync", .bool, default: .bool(false), "Follows the tempo and beat phase of the master deck."),170 ParamDef("quantize", .bool, default: .bool(true), "Snaps cues, loops and jumps to the beat grid."),171 ParamDef("reverse", .bool, default: .bool(false), "Plays the track backwards."),172 ParamDef("cue", .bool, default: .bool(false), "Sends the channel to the headphone cue bus."),173 ParamDef("trackBpm", .number, default: .number(0), writable: false, unit: "BPM", "Analysed tempo of the loaded track at original speed (0 when unknown)."),174 ParamDef("position", .duration, default: .duration(.seconds(0)), writable: false, durationUnit: .seconds, "Playhead position."),175 ParamDef("remaining", .duration, default: .duration(.seconds(0)), writable: false, durationUnit: .seconds, "Time left until the end of the track."),176 ParamDef("duration", .duration, default: .duration(.seconds(0)), writable: false, durationUnit: .seconds, "Length of the loaded track."),177 ParamDef("beat", .number, default: .number(0), writable: false, "Fractional beat index of the playhead on the track's beat grid."),178 ParamDef("playing", .bool, default: .bool(false), writable: false, "True while the deck is playing."),179 ParamDef("loaded", .bool, default: .bool(false), writable: false, "True when a track is loaded."),180 ParamDef("looping", .bool, default: .bool(false), writable: false, "True while a loop is active."),181 ParamDef("level", .gain, -60, 6, default: .gain(-60), writable: false, "Post-fader peak level of the channel."),182 ParamDef("key", .string, default: .string(""), writable: false, "Estimated musical key of the loaded track (\"8A\" notation), empty when unknown."),183 ParamDef("title", .string, default: .string(""), writable: false, "Title of the loaded track."),184 ]185186 public static let deckActions: [ActionDef] = [187 ActionDef("play", "Starts playback (on the next beat of the master clock when quantize and sync are on)."),188 ActionDef("pause", "Pauses playback."),189 ActionDef("toggle", "Plays when paused, pauses when playing."),190 ActionDef("stop", "Pauses and returns to the start of the track."),191 ActionDef("cue", "Jumps to the cue point and pauses."),192 ActionDef("setCue", "Stores the current position as the cue point."),193 ActionDef("seek", [p("position", .duration, "Beats count from the first beat of the grid, seconds from the start of the file.")], "Moves the playhead."),194 ActionDef("jump", [p("amount", .duration, "Signed distance, e.g. 4beats or -1bar.")], "Beat jump relative to the playhead."),195 ActionDef("loop", [p("length", .duration, "Loop length, e.g. 4beats.")], "Starts a loop of the given length at the playhead."),196 ActionDef("loopIn", "Marks the loop start at the playhead."),197 ActionDef("loopOut", "Marks the loop end at the playhead and starts looping."),198 ActionDef("loopExit", "Leaves the active loop."),199 ActionDef("reloop", "Re-enters the last loop."),200 ActionDef("loopHalve", "Halves the active loop length."),201 ActionDef("loopDouble", "Doubles the active loop length."),202 ActionDef("hotcue", [p("index", .number, "1 to 8.")], "Jumps to a hot cue and plays."),203 ActionDef("setHotcue", [p("index", .number, "1 to 8.")], "Stores the playhead in a hot cue."),204 ActionDef("clearHotcue", [p("index", .number, "1 to 8.")], "Deletes a hot cue."),205 ActionDef("sync", [p("on", .bool, optional: true, "Defaults to true.")], "Turns tempo and phase sync on or off."),206 ActionDef("brake", [p("length", .duration, optional: true, "Time to stop, default 1beat.")], "Tape-stop: slows the deck to a halt, then pauses."),207 ActionDef("load", [p("title", .string, "Title, or part of it, of a library track.")], "Loads the best matching library track."),208 ActionDef("loadNext", "Loads the next track of the Auto DJ queue."),209 ActionDef("eject", "Unloads the track (only while paused)."),210 ]211212 public static let deckEvents: [EventDef] = [213 EventDef(name: "trackEnd", doc: "The playhead reached the end of the track."),214 EventDef(name: "play", doc: "The deck started playing."),215 EventDef(name: "pause", doc: "The deck paused."),216 EventDef(name: "loaded", doc: "A track finished loading."),217 EventDef(name: "beat", doc: "The playhead crossed a beat of the track's grid."),218 ]219220 public static let globalEvents: [EventDef] = [221 EventDef(name: "beat", doc: "Every beat of the master clock."),222 EventDef(name: "bar", doc: "Every bar of the master clock."),223 EventDef(name: "trigger(n)", doc: "Automation trigger n (1 to 16) fired from a MIDI mapping, the keyboard or the console."),224 ]225226 // MARK: Mixer and master227228 public static let mixerParams: [ParamDef] = [229 ParamDef("crossfader", .number, 0, 1, default: .number(0.5), "Crossfader position: 0 is the A side, 1 is the B side."),230 ParamDef("curve", .string, default: .string("smooth"), allowed: crossfaderCurves, "Crossfader curve."),231 ParamDef("master.volume", .gain, -60, 6, default: .gain(0), "Master output level."),232 ParamDef("master.limiter", .bool, default: .bool(true), "Master peak limiter."),233 ParamDef("master.level", .gain, -60, 6, default: .gain(-60), writable: false, "Master output peak level."),234 ParamDef("cue.mix", .number, 0, 1, default: .number(0), "Headphone blend: 0 is cue only, 1 is master only."),235 ParamDef("cue.volume", .gain, -60, 6, default: .gain(0), "Headphone level."),236 ]237238 /// `mixer.channel.X.<alias>` maps to these deck parameters.239 public static let mixerChannelAliases: [String: String] = [240 "volume": "volume", "gain": "gain", "eq.low": "eq.low", "eq.mid": "eq.mid", "eq.high": "eq.high",241 "filter": "filter", "cue": "cue", "level": "level",242 ]243244 public static let masterParams: [ParamDef] = [245 ParamDef("bpm", .number, 20, 400, default: .number(120), rampable: false, unit: "BPM", "Tempo of the master clock. It follows the master deck while one is playing; writing it sets the free-running tempo."),246 ParamDef("beat", .number, default: .number(0), writable: false, "Beat counter of the master clock."),247 ParamDef("bar", .number, default: .number(0), writable: false, "Bar counter of the master clock (4 beats per bar)."),248 ParamDef("deck", .string, default: .string(""), writable: false, "Letter of the deck currently driving the master clock, empty when free-running."),249 ]250251 // MARK: Effects252253 public static let fxCommonParams: [ParamDef] = [254 ParamDef("mix", .number, 0, 1, default: .number(1), "Wet/dry balance: 0 is dry, 1 is fully wet."),255 ParamDef("enabled", .bool, default: .bool(false), "True while the effect is switched on."),256 ]257258 public static let fxActions: [ActionDef] = [259 ActionDef("enable", "Adds the effect to the rack when needed and switches it on."),260 ActionDef("disable", "Switches the effect off (it stays in the rack)."),261 ActionDef("toggle", "Switches the effect on or off."),262 ]263264 public static func fxParams(_ kind: EffectKind) -> [ParamDef] {265 EffectCatalog.descriptor(kind).params.map { s in266 switch s.unit {267 case .ratio: ParamDef(s.id, .number, Double(s.min), Double(s.max), default: .number(Double(s.defaultValue)), s.doc)268 case .number: ParamDef(s.id, .number, Double(s.min), Double(s.max), default: .number(Double(s.defaultValue)), s.doc)269 case .hertz: ParamDef(s.id, .frequency, Double(s.min), Double(s.max), default: .frequency(Double(s.defaultValue)), s.doc)270 case .decibels: ParamDef(s.id, .gain, Double(s.min), Double(s.max), default: .gain(Double(s.defaultValue)), s.doc)271 case .beats: ParamDef(s.id, .duration, Double(s.min), Double(s.max), default: .duration(.beats(Double(s.defaultValue))), rampable: false, durationUnit: .beats, s.doc + " Seconds are converted with the current tempo.")272 case .milliseconds: ParamDef(s.id, .duration, Double(s.min), Double(s.max), default: .duration(.seconds(Double(s.defaultValue) / 1000)), rampable: false, durationUnit: .milliseconds, s.doc)273 case .toggle: ParamDef(s.id, .bool, default: .bool(s.defaultValue >= 0.5), s.doc)274 }275 } + [ParamDef("mix", .number, 0, 1, default: .number(Double(EffectCatalog.descriptor(kind).defaultMix)), fxCommonParams[0].doc), fxCommonParams[1]]276 }277278 // MARK: Builtins279280 public static let builtins: [BuiltinDef] = [281 BuiltinDef(name: "min", signature: "min(a, b) -> same type", doc: "Smaller of two values of the same type."),282 BuiltinDef(name: "max", signature: "max(a, b) -> same type", doc: "Larger of two values of the same type."),283 BuiltinDef(name: "clamp", signature: "clamp(x, low, high) -> same type", doc: "Limits x to the range low…high."),284 BuiltinDef(name: "abs", signature: "abs(x: number) -> number", doc: "Absolute value."),285 BuiltinDef(name: "round", signature: "round(x: number) -> number", doc: "Nearest integer."),286 BuiltinDef(name: "floor", signature: "floor(x: number) -> number", doc: "Largest integer not above x."),287 BuiltinDef(name: "ceil", signature: "ceil(x: number) -> number", doc: "Smallest integer not below x."),288 BuiltinDef(name: "lerp", signature: "lerp(a, b, t: number) -> same type", doc: "Linear interpolation between a and b."),289 BuiltinDef(name: "random", signature: "random() -> number", doc: "Pseudo-random number in 0…1. The sequence is the same on every run of an automation."),290 BuiltinDef(name: "len", signature: "len(a: array) -> number", doc: "Number of elements of an array."),291 BuiltinDef(name: "db", signature: "db(x: number) -> gain", doc: "Makes a gain from a number of decibels."),292 BuiltinDef(name: "hz", signature: "hz(x: number) -> frequency", doc: "Makes a frequency from a number of hertz."),293 BuiltinDef(name: "beats", signature: "beats(x: number) -> duration", doc: "Makes a musical duration from a number of beats."),294 BuiltinDef(name: "bars", signature: "bars(x: number) -> duration", doc: "Makes a musical duration from a number of bars."),295 BuiltinDef(name: "seconds", signature: "seconds(x: number) -> duration", doc: "Makes an absolute duration from a number of seconds."),296 BuiltinDef(name: "toBeats", signature: "toBeats(d: duration) -> number", doc: "Length of a duration in beats at the current tempo."),297 BuiltinDef(name: "toSeconds", signature: "toSeconds(d: duration) -> number", doc: "Length of a duration in seconds at the current tempo."),298 BuiltinDef(name: "toNumber", signature: "toNumber(x: gain | frequency) -> number", doc: "Plain number of decibels or hertz."),299 BuiltinDef(name: "print", signature: "print(values…)", doc: "Writes the values to the automation console."),300 ]301302 public static let keywords: [String] = [303 "automation", "quantize", "let", "var", "fn", "return", "if", "else", "repeat", "for", "in", "while", "limit", "every", "wait", "until",304 "at", "over", "curve", "on", "once", "stop", "break", "continue", "true", "false", "and", "or", "not", "bar", "beat", "bars", "beats",305 "nextBeat", "nextBar", "deck", "mixer", "fx", "master", "trigger", "none",306 ]307308 // MARK: Lookup309310 public static func deckParam(_ key: String) -> ParamDef? { deckParamTable[key] }311 public static func mixerParam(_ key: String) -> ParamDef? { mixerParamTable[key] }312 public static func masterParam(_ key: String) -> ParamDef? { masterParamTable[key] }313 public static func fxParam(_ kind: EffectKind, _ key: String) -> ParamDef? { fxParamTable[kind]?[key] }314 public static func deckAction(_ name: String) -> ActionDef? { deckActions.first { $0.name == name } }315 public static func fxAction(_ name: String) -> ActionDef? { fxActions.first { $0.name == name } }316317 public static func definition(for address: ParamAddress) -> ParamDef? {318 switch address.area {319 case .deck: deckParam(address.key)320 case .mixer: mixerParam(address.key)321 case .master: masterParam(address.key)322 case .fx: address.effect.flatMap { fxParam($0, address.key) }323 }324 }325326 private static let deckParamTable = Dictionary(uniqueKeysWithValues: deckParams.map { ($0.key, $0) })327 private static let mixerParamTable = Dictionary(uniqueKeysWithValues: mixerParams.map { ($0.key, $0) })328 private static let masterParamTable = Dictionary(uniqueKeysWithValues: masterParams.map { ($0.key, $0) })329 private static let fxParamTable: [EffectKind: [String: ParamDef]] = Dictionary(uniqueKeysWithValues: EffectKind.allCases.map { k in330 (k, Dictionary(uniqueKeysWithValues: fxParams(k).map { ($0.key, $0) }))331 })332333 /// Every completable path, for the editor's autocomplete (decks spelled with the given letter).334 public static func completionPaths(deck letter: String = "A") -> [(path: String, detail: String, doc: String)] {335 var out: [(String, String, String)] = []336 for d in deckParams { out.append(("deck.\(letter).\(d.key)", "\(d.type)" + (d.writable ? "" : " (read-only)"), d.doc)) }337 for a in deckActions { out.append(("deck.\(letter).\(a.signature)", "action", a.doc)) }338 for e in deckEvents { out.append(("deck.\(letter).\(e.name)", "event", e.doc)) }339 for m in mixerParams { out.append(("mixer.\(m.key)", "\(m.type)" + (m.writable ? "" : " (read-only)"), m.doc)) }340 for (alias, _) in mixerChannelAliases.sorted(by: { $0.key < $1.key }) { out.append(("mixer.channel.\(letter).\(alias)", "alias", "Same as deck.\(letter).\(mixerChannelAliases[alias]!).")) }341 for m in masterParams { out.append(("master.\(m.key)", "\(m.type)" + (m.writable ? "" : " (read-only)"), m.doc)) }342 for k in EffectKind.allCases {343 for d in fxParams(k) { out.append(("fx.\(k.rawValue).\(d.key)", "\(d.type)", d.doc)) }344 for a in fxActions { out.append(("fx.\(k.rawValue).\(a.name)()", "action", a.doc)) }345 }346 return out347 }348}349