SPB Git

Repository Public

Project.swift 14.5 KB 296 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX DJ9// File             : Packages/ORIXDJCore/Sources/ORIXDJEngine/Project.swift10// Description      : Native ORIX DJ projects (.orixdjproject packages):11//                    versioned capture and restore of decks, mixer, effect12//                    chains, routing, automation scripts and MIDI mapping.13//                    Audio is referenced, never copied.14// Module           : ORIXDJEngine15// Repository       : https://git.spboucher.ai/orix-dj16// Created          : 2026-11-2117// Last Modified    : 2026-11-2118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import ORIXDSP93import ORIXLibrary94import ORIXMIDI95import ORIXScript9697public struct ProjectDeck: Codable, Sendable, Equatable {98    public var trackPath: String?99    public var trackTitle: String?100    public var bookmark: Data?101    public var position = 0.0102    public var cuePoint = 0.0103    public var hotcues: [Double?] = []104    public var loopStart: Double?105    public var loopEnd: Double?106    public var rate = 1.0107    public var keylock = false108    public var keyShift = 0.0109    public var sync = false110    public var quantize = true111    public var values: [String: Double] = [:]112113    public init() {}114}115116public struct ProjectScript: Codable, Sendable, Equatable {117    public var name: String118    public var source: String119120    public init(name: String, source: String) { self.name = name; self.source = source }121}122123public struct ProjectDocument: Codable, Sendable, Equatable {124    public static let currentFormat = 1125    public static let fileExtension = "orixdjproject"126127    public var formatVersion = ProjectDocument.currentFormat128    public var languageVersion = ORIXScriptLanguage.version129    public var name = "Untitled"130    public var notes = ""131    public var savedAt = Date()132    public var decks: [ProjectDeck] = []133    public var mixer: [String: Double] = [:]134    public var crossfaderCurve = "smooth"135    public var racks: [EffectChain] = []136    public var masterLeft = 0, masterRight = 1, cueLeft = -1, cueRight = -1137    public var splitCue = false138    public var autoDJ = AutoDJSettings()139    public var autoDJQueue: [String] = []140    public var scripts: [ProjectScript] = []141    public var midiProfile: MIDIMappingProfile?142    public var recordings: [String] = []143144    public init() {}145}146147public enum ProjectError: Error, LocalizedError, Equatable {148    case unreadable(String)149    case newerFormat(Int)150    case io(String)151152    public var errorDescription: String? {153        switch self {154        case let .unreadable(reason): "The project could not be read: \(reason)"155        case let .newerFormat(v): "This project was saved by a newer version of ORIX DJ (format \(v))."156        case let .io(reason): "The project could not be saved: \(reason)"157        }158    }159}160161public struct ProjectRestoreReport: Sendable, Equatable {162    /// Audio files referenced by the project that could not be found.163    public var missingMedia: [String] = []164    public var loadedDecks: [Int] = []165    public var scriptsRestored = 0166}167168public enum ProjectStore {169    /// Captures the live session.170    public static func capture(_ session: DJSession, name: String, notes: String = "", scriptNames: [String] = []) -> ProjectDocument {171        var doc = ProjectDocument()172        doc.name = name; doc.notes = notes; doc.savedAt = Date()173        let engine = session.engine174        for d in 0 ..< deckCount {175            let s = engine.deckStatus(d)176            var pd = ProjectDeck()177            if let t = s.track { pd.trackPath = t.url?.path; pd.trackTitle = t.title; pd.bookmark = try? t.url?.bookmarkData() }178            pd.position = s.position; pd.cuePoint = s.cuePoint; pd.hotcues = s.hotcues179            pd.loopStart = s.loop?.start; pd.loopEnd = s.loop?.end180            pd.rate = s.sync ? 1 : s.rate; pd.keylock = s.keylock; pd.keyShift = s.keyShift; pd.sync = s.sync; pd.quantize = s.quantize181            for p in ScriptSchema.deckParams where p.writable && !["rate", "bpm", "keyShift", "keylock", "sync", "quantize", "reverse"].contains(p.key) {182                if let x = engine.value(of: .deck(d, p.key))?.scalar { pd.values[p.key] = x }183            }184            doc.decks.append(pd)185        }186        for p in ScriptSchema.mixerParams where p.writable && p.key != "curve" { if let x = engine.value(of: .mixer(p.key))?.scalar { doc.mixer[p.key] = x } }187        doc.crossfaderCurve = engine.value(of: .mixer("curve"))?.stringValue ?? "smooth"188        for r in 0 ... deckCount { doc.racks.append(EffectChain(name: r == deckCount ? "Master" : "Deck \(deckLetters[r])", slots: engine.rackStatus(r == deckCount ? nil : r))) }189        let routing = engine.routing190        doc.masterLeft = routing.masterLeft; doc.masterRight = routing.masterRight; doc.cueLeft = routing.cueLeft; doc.cueRight = routing.cueRight; doc.splitCue = routing.splitCue191        doc.autoDJ = session.autoDJConfiguration192        doc.midiProfile = session.midi.activeProfile193        for n in scriptNames { if let s = try? session.library.script(named: n) { doc.scripts.append(ProjectScript(name: s.name, source: s.source)) } }194        return doc195    }196197    /// Writes the package atomically: a complete copy is built next to the destination, then swapped in.198    public static func save(_ document: ProjectDocument, to url: URL) throws {199        let fm = FileManager.default200        let temp = url.deletingLastPathComponent().appendingPathComponent(".\(UUID().uuidString).tmp", isDirectory: true)201        do {202            try fm.createDirectory(at: temp.appendingPathComponent("Scripts"), withIntermediateDirectories: true)203            let encoder = JSONEncoder()204            encoder.outputFormatting = [.prettyPrinted, .sortedKeys]; encoder.dateEncodingStrategy = .iso8601205            try encoder.encode(document).write(to: temp.appendingPathComponent("project.json"), options: .atomic)206            for s in document.scripts {207                let safe = s.name.replacingOccurrences(of: "/", with: "-")208                try Data(s.source.utf8).write(to: temp.appendingPathComponent("Scripts").appendingPathComponent(safe).appendingPathExtension(ORIXScriptLanguage.fileExtension))209            }210            if fm.fileExists(atPath: url.path) { _ = try fm.replaceItemAt(url, withItemAt: temp) } else { try fm.moveItem(at: temp, to: url) }211        } catch {212            try? fm.removeItem(at: temp)213            throw ProjectError.io(error.localizedDescription)214        }215    }216217    public static func load(_ url: URL) throws -> ProjectDocument {218        let file = url.appendingPathComponent("project.json")219        guard let data = try? Data(contentsOf: file) else { throw ProjectError.unreadable("project.json is missing") }220        // Read the version first so a newer project is reported as such, not as corruption.221        struct Header: Decodable { var formatVersion: Int }222        guard let header = try? JSONDecoder().decode(Header.self, from: data) else { throw ProjectError.unreadable("project.json is not valid") }223        guard header.formatVersion <= ProjectDocument.currentFormat else { throw ProjectError.newerFormat(header.formatVersion) }224        let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .iso8601225        do { return try decoder.decode(ProjectDocument.self, from: data) } catch { throw ProjectError.unreadable("\(error)") }226    }227228    /// Applies a project to the session. Decks are loaded asynchronously; `completion` reports what was restored.229    public static func apply(_ doc: ProjectDocument, to session: DJSession, completion: (@Sendable (ProjectRestoreReport) -> Void)? = nil) {230        let engine = session.engine231        session.host.stopAll()232        for d in 0 ..< deckCount { engine.pause(deck: d) }233        for (key, x) in doc.mixer {234            guard let def = ScriptSchema.mixerParam(key) else { continue }235            engine.set(.mixer(key), def.type == .gain ? .gain(x) : (def.type == .bool ? .bool(x >= 0.5) : .number(x)))236        }237        engine.set(.mixer("curve"), .string(doc.crossfaderCurve))238        for (r, chain) in doc.racks.prefix(deckCount + 1).enumerated() { engine.applyChain(chain, rack: r == deckCount ? nil : r) }239        var routing = DJEngine.Routing()240        routing.masterLeft = doc.masterLeft; routing.masterRight = doc.masterRight; routing.cueLeft = doc.cueLeft; routing.cueRight = doc.cueRight; routing.splitCue = doc.splitCue241        engine.setRouting(routing)242        session.autoDJConfiguration = doc.autoDJ243        if let profile = doc.midiProfile { session.midi.activeProfile = profile }244245        let report = Box(ProjectRestoreReport())246        for s in doc.scripts {247            if let existing = try? session.library.script(named: s.name) {248                if existing.source != s.source { _ = try? session.library.saveScript(id: existing.id, source: s.source, expectedUpdatedAt: existing.updatedAt) }249            } else { _ = try? session.library.createScript(name: s.name, source: s.source) }250            report.value.scriptsRestored += 1251        }252        let group = DispatchGroup()253        for (d, pd) in doc.decks.prefix(deckCount).enumerated() {254            for (key, x) in pd.values {255                guard let def = ScriptSchema.deckParam(key) else { continue }256                let v: Value = switch def.type { case .gain: .gain(x); case .frequency: .frequency(x); case .bool: .bool(x >= 0.5); default: .number(x) }257                engine.set(.deck(d, key), v)258            }259            engine.set(.deck(d, "keylock"), .bool(pd.keylock)); engine.set(.deck(d, "keyShift"), .number(pd.keyShift))260            engine.set(.deck(d, "quantize"), .bool(pd.quantize)); engine.set(.deck(d, "sync"), .bool(pd.sync))261            guard let path = pd.trackPath else { _ = engine.unload(deck: d); continue }262            // Follow a moved file through its bookmark, then make sure the library knows the track.263            var url = URL(fileURLWithPath: path)264            if !FileManager.default.fileExists(atPath: url.path), let b = pd.bookmark {265                var stale = false266                if let resolved = try? URL(resolvingBookmarkData: b, bookmarkDataIsStale: &stale) { url = resolved }267            }268            guard FileManager.default.fileExists(atPath: url.path) else { report.lock.withLock { report.value.missingMedia.append(path) }; continue }269            var track = (try? session.library.track(path: url.path)) ?? nil270            if track == nil { track = try? session.library.upsertTrack(Track(path: url.path, title: pd.trackTitle ?? url.deletingPathExtension().lastPathComponent, format: url.pathExtension.lowercased())) }271            guard let track else { continue }272            group.enter()273            session.load(trackID: track.id, deck: d) { result in274                if case .success = result {275                    engine.restore(deck: d, cuePoint: pd.cuePoint, hotcues: pd.hotcues)276                    engine.seek(deck: d, seconds: pd.position)277                    if !pd.sync { engine.set(.deck(d, "rate"), .number(pd.rate)) }278                    report.lock.withLock { report.value.loadedDecks.append(d) }279                } else { report.lock.withLock { report.value.missingMedia.append(path) } }280                group.leave()281            }282        }283        group.notify(queue: .global()) {284            var final = report.lock.withLock { report.value }285            final.loadedDecks.sort(); final.missingMedia.sort()286            completion?(final)287        }288    }289290    private final class Box<T>: @unchecked Sendable {291        var value: T292        let lock = NSLock()293        init(_ v: T) { value = v }294    }295}296
Files main
Menu

Theme