SPB Git

Repository Public

AutoDJController.swift 8.0 KB 184 lines swift

1// ORIX DJ2// File: App/Sources/Features/AutoDJ/AutoDJController.swift3// Description: State of the Auto DJ screen: the queue source, the hand-made order, the order Auto DJ will really play4//              (the planner's), the settings mirrored into the session, and the wording of each transition.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011enum AutoDJSource: Hashable, Sendable {12    case selection, allTracks13    case playlist(Int64)14    case crate(Int64)15    case smartCrate(Int64)16}1718/// How one track follows another, in numbers and words.19struct AutoDJStep: Equatable {20    var tempoPercent: Double?21    var keyDistance: Int?22    var overLimit: Bool2324    var keyWords: String {25        switch keyDistance {26        case .none: String(localized: "key unknown")27        case 0: String(localized: "same key")28        case 1: String(localized: "neighbour")29        default: String(localized: "clash")30        }31    }3233    var tempoWords: String { tempoPercent.map { String(format: "%.1f %%", $0) } ?? String(localized: "tempo unknown") }3435    var symbol: String {36        guard let k = keyDistance, tempoPercent != nil else { return "questionmark.circle" }37        if overLimit || k > 1 { return "exclamationmark.triangle" }38        return k == 0 ? "equal.circle" : "checkmark.circle"39    }4041    var tint: Color {42        guard let k = keyDistance, tempoPercent != nil else { return ORIX.Palette.textTertiary }43        return overLimit || k > 1 ? ORIX.Palette.warning : ORIX.Palette.success44    }45}4647@MainActor @Observable48final class AutoDJController {49    var source: AutoDJSource = .allTracks50    var settings = AutoDJSettings() { didSet { if settings != oldValue { recomputeOrder() } } }51    /// Tracks of the source in the order arranged by hand (removed tracks are left out).52    var manual: [Track] = [] { didSet { if manual != oldValue { recomputeOrder() } } }53    var crates: [Crate] = []54    var playlists: [Playlist] = []55    var smartCrates: [SmartCrate] = []56    var loaded = false57    /// Titles of the tracks still waiting in the running Auto DJ queue.58    var remaining: [Track] = []5960    @ObservationIgnored private var removed = Set<Int64>()61    @ObservationIgnored private var orderSource: AutoDJSource?62    @ObservationIgnored private var generation = 06364    private struct Snapshot: Sendable {65        var tracks: [Track]66        var crates: [Crate]67        var playlists: [Playlist]68        var smartCrates: [SmartCrate]69    }7071    /// The queue exactly as `DJSession.startAutoDJ` will order it. Recomputed off the main thread (the planner is72    /// quadratic in the queue length) whenever the hand-made order or the settings change.73    private(set) var playOrder: [Track] = []74    @ObservationIgnored private var orderGeneration = 07576    func recomputeOrder() {77        orderGeneration += 178        let mine = orderGeneration79        let tracks = manual, settings = settings80        guard settings.smartOrder, tracks.count > 2 else { if playOrder != tracks { playOrder = tracks }; return }81        Task {82            let ordered = await Task.detached(priority: .userInitiated) { () -> [Track] in83                let byID = Dictionary(tracks.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })84                return AutoDJPlanner.order(tracks.map { AutoDJCandidate(id: $0.id, bpm: $0.bpm, camelot: $0.camelot) }, settings: settings).compactMap { byID[$0.id] }85            }.value86            if mine == orderGeneration, playOrder != ordered { playOrder = ordered }87        }88    }8990    func step(from a: Track, to b: Track) -> AutoDJStep {91        let tempo = AutoDJPlanner.tempoChange(from: a.bpm, to: b.bpm)92        return AutoDJStep(tempoPercent: tempo, keyDistance: AutoDJPlanner.keyDistance(a.camelot, b.camelot), overLimit: (tempo ?? 0) > settings.maxTempoChange)93    }9495    func reload(model: AppModel) async {96        let library = model.library97        let source = source98        let selection = Array(model.selectedTrackIDs).sorted()99        generation += 1100        let mine = generation101        let snapshot = await Task.detached(priority: .userInitiated) { () -> Snapshot in102            let tracks: [Track]103            switch source {104            case .selection: tracks = (try? library.tracks(ids: selection)) ?? []105            case .allTracks: tracks = (try? library.tracks(query: TrackQuery(scope: .all))) ?? []106            case let .playlist(id): tracks = (try? library.tracks(query: TrackQuery(scope: .playlist(id)))) ?? []107            case let .crate(id): tracks = (try? library.tracks(query: TrackQuery(scope: .crate(id)))) ?? []108            case let .smartCrate(id): tracks = (try? library.tracks(query: TrackQuery(scope: .smartCrate(id)))) ?? []109            }110            var seen = Set<Int64>()111            return Snapshot(tracks: tracks.filter { !$0.missing && seen.insert($0.id).inserted }, crates: (try? library.crates()) ?? [],112                            playlists: (try? library.playlists()) ?? [], smartCrates: (try? library.smartCrates()) ?? [])113        }.value114        guard mine == generation else { return }115        crates = snapshot.crates; playlists = snapshot.playlists; smartCrates = snapshot.smartCrates116        if orderSource != source { orderSource = source; removed.removeAll(); manual = snapshot.tracks }117        else {118            // Same source: keep the hand-made order and the removals, refresh the track data, append newcomers.119            let fresh = Dictionary(snapshot.tracks.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })120            var next = manual.compactMap { fresh[$0.id] }121            let known = Set(next.map(\.id))122            next += snapshot.tracks.filter { !known.contains($0.id) && !removed.contains($0.id) }123            if next != manual { manual = next }124        }125        loaded = true126    }127128    func loadRemaining(ids: [Int64], library: LibraryStore) async {129        let tracks = await Task.detached { (try? library.tracks(ids: ids)) ?? [] }.value130        if tracks != remaining { remaining = tracks }131    }132133    func remove(_ id: Int64) { removed.insert(id); manual.removeAll { $0.id == id } }134135    func restoreRemoved(model: AppModel) async { removed.removeAll(); await reload(model: model) }136137    var hasRemovals: Bool { !removed.isEmpty }138139    func move(from offsets: IndexSet, to destination: Int) { manual.move(fromOffsets: offsets, toOffset: destination) }140141    func move(_ id: Int64, by delta: Int) {142        guard let i = manual.firstIndex(where: { $0.id == id }) else { return }143        let j = i + delta144        guard manual.indices.contains(j) else { return }145        manual.swapAt(i, j)146    }147148    /// Puts a track at the head of the queue: Auto DJ always starts with the first track.149    func playFirst(_ id: Int64) {150        guard let i = manual.firstIndex(where: { $0.id == id }), i > 0 else { return }151        manual.insert(manual.remove(at: i), at: 0)152    }153154    func apply(settings new: AutoDJSettings, session: DJSession) {155        settings = new156        session.autoDJConfiguration = new157    }158159    func start(model: AppModel) {160        guard !manual.isEmpty else { return }161        model.session.autoDJConfiguration = settings162        model.session.startAutoDJ(trackIDs: manual.map(\.id))163        model.refreshNow()164    }165166    func stop(model: AppModel) {167        model.session.stopAutoDJ()168        model.refreshNow()169    }170}171172extension AutoDJStyle {173    /// One sentence per style, describing what the generated script does.174    var sentence: LocalizedStringKey {175        switch self {176        case .blend: "Both channel faders cross smoothly over the whole transition."177        case .bassSwap: "The new track comes in without bass; halfway the bass lines are swapped, then the old track fades out."178        case .echoOut: "The old track dissolves into an echo while the new one rises, then the echo dies away."179        case .filterSweep: "The new track opens up through a low-pass filter while the old one thins out through a high-pass filter."180        case .cut: "The new track starts on the next bar and the old one stops at once."181        }182    }183}184
Files main
Menu

Theme