SPB Git

Repository Public

AutoDJ.swift 7.8 KB 195 lines swift

1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXDJEngine/AutoDJ.swift3// Description: Auto DJ planning: deterministic ordering of a queue by tempo and key compatibility, and generation of4//              the transition as ordinary ORIX Script. No network, no model: the same analysis the decks display.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXAnalysis10import ORIXLibrary11import ORIXScript1213public enum AutoDJStyle: String, Sendable, Codable, CaseIterable, Identifiable {14    case blend, bassSwap, echoOut, filterSweep, cut15    public var id: String { rawValue }1617    public var displayName: String {18        switch self {19        case .blend: "Smooth blend"20        case .bassSwap: "Bass swap"21        case .echoOut: "Echo out"22        case .filterSweep: "Filter sweep"23        case .cut: "Cut on the bar"24        }25    }26}2728public struct AutoDJSettings: Sendable, Codable, Equatable {29    public var style = AutoDJStyle.bassSwap30    /// Length of the transition in bars.31    public var bars = 832    /// Reorder the queue so neighbouring tracks are close in tempo and compatible in key.33    public var smartOrder = true34    /// Match the incoming deck's tempo and phase to the outgoing one.35    public var sync = true36    /// Apply each track's analysed gain so tracks play at a similar loudness.37    public var autoGain = true38    /// Largest tempo change accepted when ordering, in percent.39    public var maxTempoChange = 8.040    public init() {}41}4243public struct AutoDJCandidate: Sendable, Equatable {44    public var id: Int6445    public var bpm: Double?46    public var camelot: String?47    public init(id: Int64, bpm: Double?, camelot: String?) { self.id = id; self.bpm = bpm; self.camelot = camelot }48}4950public enum AutoDJPlanner {51    /// Wheel distance between two "8A"-style codes: 0 same, 1 neighbour or relative, larger = clash. Nil when unknown.52    public static func keyDistance(_ a: String?, _ b: String?) -> Int? {53        func parse(_ s: String?) -> (Int, Character)? {54            guard let s, let letter = s.last, letter == "A" || letter == "B", let n = Int(s.dropLast()), (1 ... 12).contains(n) else { return nil }55            return (n, letter)56        }57        guard let x = parse(a), let y = parse(b) else { return nil }58        let ring = min((x.0 - y.0 + 12) % 12, (y.0 - x.0 + 12) % 12)59        return ring + (x.1 == y.1 ? 0 : 1)60    }6162    /// Tempo change in percent needed to play `to` at the tempo of `from`, folding half and double time.63    public static func tempoChange(from: Double?, to: Double?) -> Double? {64        guard let from, let to, from > 0, to > 0 else { return nil }65        var ratio = from / to66        while ratio > 1.42 { ratio /= 2 }67        while ratio < 0.71 { ratio *= 2 }68        return abs(ratio - 1) * 10069    }7071    /// Cost of playing `b` after `a`: lower is smoother. Unknown values cost a fixed moderate amount.72    public static func cost(_ a: AutoDJCandidate, _ b: AutoDJCandidate, settings: AutoDJSettings) -> Double {73        let tempo = tempoChange(from: a.bpm, to: b.bpm).map { $0 > settings.maxTempoChange ? 20 + $0 : $0 } ?? 674        let key: Double = keyDistance(a.camelot, b.camelot).map { $0 <= 1 ? Double($0) * 0.5 : Double($0) * 2 } ?? 375        return tempo + key76    }7778    /// Greedy nearest-neighbour ordering starting from the first track. Deterministic: ties keep the original order.79    public static func order(_ tracks: [AutoDJCandidate], settings: AutoDJSettings) -> [AutoDJCandidate] {80        guard settings.smartOrder, tracks.count > 2 else { return tracks }81        var remaining = Array(tracks.dropFirst())82        var out = [tracks[0]]83        while !remaining.isEmpty {84            let last = out[out.count - 1]85            var best = 0; var bestCost = Double.infinity86            for (i, c) in remaining.enumerated() {87                let k = cost(last, c, settings: settings)88                if k < bestCost - 1e-9 { best = i; bestCost = k }89            }90            out.append(remaining.remove(at: best))91        }92        return out93    }9495    /// The transition as ORIX Script. Auto DJ runs exactly this text through the automation runtime.96    public static func transitionScript(from: String, to: String, settings: AutoDJSettings) -> String {97        let bars = max(1, min(64, settings.bars))98        let half = max(1, bars / 2)99        let rest = max(1, bars - half)100        let sync = settings.sync ? "    deck.\(to).sync(true)\n" : ""101        let name = "Auto DJ \(from) to \(to)"102        switch settings.style {103        case .blend:104            return """105            // Generated by Auto DJ: smooth blend, \(bars) bars.106            automation "\(name)" quantize bar {107            \(sync)    deck.\(to).volume = -60dB108                deck.\(to).play()109                over \(bars)bars curve smooth {110                    deck.\(to).volume -> 0dB111                    deck.\(from).volume -> -60dB112                }113                deck.\(from).pause()114                deck.\(from).volume = 0dB115            }116117            """118        case .bassSwap:119            return """120            // Generated by Auto DJ: bass swap, \(bars) bars.121            automation "\(name)" quantize bar {122            \(sync)    deck.\(to).volume = -60dB123                deck.\(to).eq.low = -26dB124                deck.\(to).play()125                over \(half)bars { deck.\(to).volume -> 0dB }126                deck.\(from).eq.low = -26dB127                deck.\(to).eq.low = 0dB128                over \(rest)bars { deck.\(from).volume -> -60dB }129                deck.\(from).pause()130                deck.\(from).eq.low = 0dB131                deck.\(from).volume = 0dB132            }133134            """135        case .echoOut:136            return """137            // Generated by Auto DJ: echo out, \(bars) bars.138            automation "\(name)" quantize bar {139            \(sync)    deck.\(to).volume = -60dB140                deck.\(to).play()141                deck.\(from).fx.echo.time = 3/4beat142                deck.\(from).fx.echo.feedback = 0.55143                deck.\(from).fx.echo.mix = 0144                deck.\(from).fx.echo.enable()145                over \(half)bars {146                    deck.\(to).volume -> 0dB147                    deck.\(from).fx.echo.mix -> 0.5148                }149                deck.\(from).pause()150                over \(rest)bars { deck.\(from).fx.echo.feedback -> 0.1 }151                deck.\(from).fx.echo.disable()152                deck.\(from).fx.echo.mix = 0153            }154155            """156        case .filterSweep:157            return """158            // Generated by Auto DJ: filter sweep, \(bars) bars.159            automation "\(name)" quantize bar {160            \(sync)    deck.\(to).volume = -60dB161                deck.\(to).filter.lowpass = 300Hz162                deck.\(to).play()163                over \(bars)bars {164                    deck.\(to).volume -> 0dB165                    deck.\(to).filter.lowpass -> 20kHz166                    deck.\(from).filter.highpass -> 8kHz167                    deck.\(from).volume -> -60dB168                }169                deck.\(from).pause()170                deck.\(from).filter.highpass = 20Hz171                deck.\(from).volume = 0dB172            }173174            """175        case .cut:176            return """177            // Generated by Auto DJ: cut on the bar.178            automation "\(name)" quantize bar {179            \(sync)    deck.\(to).volume = 0dB180                deck.\(to).play()181                deck.\(from).pause()182            }183184            """185        }186    }187188    /// Seconds before the end of the outgoing track at which the transition must start, at the deck's current tempo.189    public static func leadSeconds(settings: AutoDJSettings, bpm: Double) -> Double {190        let bars = settings.style == .cut ? 1 : settings.bars191        // The transition itself, one bar of quantisation, and two bars of margin before the track runs out.192        return Double(bars + 3) * 4 * 60 / max(60, bpm)193    }194}195
Files main
Menu

Theme