SPB Git

Repository Public

RealMusic.swift 15.6 KB 262 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX DJ9// File             : Packages/ORIXDJCore/Sources/orix-dj-bench/RealMusic.swift10// Description      : Validation on real audio files chosen by the user: batch11//                    analysis table, and an offline render of an automated12//                    transition (decode, analyse, sync, run a preset script,13//                    record) to listen to afterwards.14// Module           : orix-dj-bench15// 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 AVFoundation92import Foundation93import ORIXAnalysis94import ORIXDJEngine95import ORIXLibrary96import ORIXScript9798func audioFiles(in folder: String) -> [URL] {99    let exts: Set<String> = ["flac", "mp3", "m4a", "wav", "aif", "aiff", "caf", "aac"]100    let items = (try? FileManager.default.contentsOfDirectory(at: URL(fileURLWithPath: folder), includingPropertiesForKeys: nil)) ?? []101    return items.filter { exts.contains($0.pathExtension.lowercased()) }.sorted { $0.lastPathComponent < $1.lastPathComponent }102}103104func analyzeFolder(_ folder: String) {105    let files = audioFiles(in: folder)106    print("file\tseconds\tbpm\tbpm_conf\tstability\tfirst_beat\tkey\tcamelot\tkey_conf\tLUFS\tpeak_dBFS\tdecode_s\tanalyse_s")107    var totalAudio = 0.0, totalAnalysis = 0.0, failed = 0108    for url in files {109        let t0 = Date()110        guard let buffer = try? TrackBuffer.load(url: url) else { print("\(url.lastPathComponent)\tUNREADABLE"); failed += 1; continue }111        let t1 = Date()112        guard let r = try? TrackAnalyzer.analyze(left: buffer.leftBuffer, right: buffer.rightBuffer, sampleRate: buffer.sampleRate, options: DJSession.analysisOptions) else { print("\(url.lastPathComponent)\tANALYSIS FAILED"); failed += 1; continue }113        let t2 = Date()114        totalAudio += buffer.duration; totalAnalysis += t2.timeIntervalSince(t1)115        let name = url.deletingPathExtension().lastPathComponent116        print(String(format: "%@\t%.0f\t%@\t%.2f\t%.2f\t%.3f\t%@\t%@\t%.2f\t%.1f\t%.1f\t%.2f\t%.2f", name as NSString, buffer.duration,117                     (r.grid.map { String(format: "%.2f", $0.bpm) } ?? "none") as NSString, r.bpmConfidence, r.tempoStability, r.grid?.firstBeatSeconds ?? 0,118                     (r.key?.name ?? "none") as NSString, (r.key?.camelot ?? "-") as NSString, r.key?.confidence ?? 0, r.integratedLUFS, r.peakDBFS, t1.timeIntervalSince(t0), t2.timeIntervalSince(t1)))119    }120    print(String(format: "# %d files, %d failed, %.0f s of audio analysed in %.1f s (%.0f× real time)", files.count, failed, totalAudio, totalAnalysis, totalAudio / max(0.001, totalAnalysis)))121}122123func renderMix(_ a: String, _ b: String, _ out: String, preset: String) {124    var c = EngineConfiguration(); c.sampleRate = 48000; c.bufferFrames = 256125    let engine = DJEngine(configuration: c)126    let host = AutomationHost(engine: engine)127    var infos: [LoadedTrack] = []128    for (d, path) in [a, b].enumerated() {129        let url = URL(fileURLWithPath: path)130        guard let buffer = try? TrackBuffer.load(url: url), let r = try? TrackAnalyzer.analyze(left: buffer.leftBuffer, right: buffer.rightBuffer, sampleRate: buffer.sampleRate, options: DJSession.analysisOptions) else { print("cannot read \(path)"); exit(1) }131        let info = LoadedTrack(url: url, title: url.deletingPathExtension().lastPathComponent, duration: buffer.duration, sampleRate: buffer.sampleRate, grid: r.grid, key: r.key, bpmConfidence: r.bpmConfidence)132        _ = engine.load(deck: d, buffer: buffer, info: info)133        engine.set(.deck(d, "gain"), .gain(min(6, max(-12, r.suggestedGainDB))))134        engine.set(.deck(d, "keylock"), .bool(true))135        infos.append(info)136        print("deck \(deckLetters[d]): \(info.title) — \(r.grid.map { String(format: "%.2f BPM", $0.bpm) } ?? "no tempo"), key \(r.key?.camelot ?? "?"), gain \(String(format: "%+.1f dB", r.suggestedGainDB))")137    }138    guard let script = PresetLibrary.preset(named: preset), let program = ScriptCompiler.compile(script.source).program else { print("unknown preset \(preset)"); exit(1) }139    let sr = 48000140    // 40 s of the first track from 60 s in, the transition, then 30 s of the second track.141    engine.seek(deck: 0, seconds: min(60, max(0, infos[0].duration - 120)))142    if let g = infos[1].grid { engine.seek(deck: 1, seconds: g.barStartSeconds(atOrBefore: min(30, infos[1].duration / 4))) }143    engine.play(deck: 0)144    var left: [Float] = [], right: [Float] = []145    func render(_ seconds: Double) { let o = host.renderOffline(frames: Int(seconds * Double(sr))); left += o[0]; right += o[1] }146    render(40)147    let run = host.start(program)148    print("started \"\(preset)\" at \(left.count / sr) s (run \(run ?? -1))")149    var guardSeconds = 0.0150    while !host.activeRuns.isEmpty, guardSeconds < 240 { render(1); guardSeconds += 1 }151    render(30)152    let s = host.stats153    let peak = left.reduce(Float(0)) { max($0, abs($1)) }154    do { try DJSession.writeWAV(left: left, right: right, sampleRate: Double(sr), to: URL(fileURLWithPath: out)) } catch { print("write failed: \(error)"); exit(1) }155    let b1 = engine.deckStatus(1)156    print(String(format: "wrote %@: %.0f s, peak %.2f dBFS, clipped blocks %d, transition %.0f s, timed commands %d, late %d, runtime errors %d, deck B at %.2f BPM (track %.2f)",157                 out as NSString, Double(left.count) / Double(sr), 20 * log10(max(peak, 1e-6)), engine.renderState.clippedBlocks, guardSeconds, s.trackedEvents, s.lateEvents, s.runtimeErrors, b1.bpm, b1.trackBPM))158}159160/// Renders a scripted four-deck performance offline and saves the rig, cued at the start of the performance, as a project161/// that embeds the script and references the rendered take.162func renderSet(script scriptPath: String, out: String, project: String, tracks: [String]) {163    var c = EngineConfiguration(); c.sampleRate = 48000; c.bufferFrames = 256164    let engine = DJEngine(configuration: c)165    let host = AutomationHost(engine: engine)166    guard let source = try? String(contentsOfFile: scriptPath, encoding: .utf8) else { print("cannot read \(scriptPath)"); exit(1) }167    let compiled = ScriptCompiler.compile(source)168    guard let program = compiled.program else { print("the script does not compile: \(compiled.diagnostics)"); exit(1) }169    var doc = ProjectDocument()170    for (d, spec) in tracks.enumerated() {171        // "<file>@drop", "<file>@drop-8" (bars before the drop) or "<file>@<seconds>"; without a suffix, the default cue.172        var path = spec, cueSpec = ""173        if let at = spec.lastIndex(of: "@"), !spec[at...].contains("/") { path = String(spec[..<at]); cueSpec = String(spec[spec.index(after: at)...]) }174        let url = URL(fileURLWithPath: path)175        guard let buffer = try? TrackBuffer.load(url: url), let r = try? TrackAnalyzer.analyze(left: buffer.leftBuffer, right: buffer.rightBuffer, sampleRate: buffer.sampleRate, options: DJSession.analysisOptions) else { print("cannot read \(path)"); exit(1) }176        let info = LoadedTrack(url: url, title: url.deletingPathExtension().lastPathComponent, duration: buffer.duration, sampleRate: buffer.sampleRate, grid: r.grid, key: r.key, bpmConfidence: r.bpmConfidence)177        _ = engine.load(deck: d, buffer: buffer, info: info)178        let gain = min(6, max(-12, r.suggestedGainDB))179        engine.set(.deck(d, "gain"), .gain(gain))180        engine.set(.deck(d, "keylock"), .bool(true))181        // Deck A starts 45 s in; the others wait on the bar at or before 20 s, past their intro.182        var start = r.grid?.barStartSeconds(atOrBefore: d == 0 ? 45 : 20) ?? 0183        var cueNote = ""184        if cueSpec.hasPrefix("drop"), let grid = r.grid, let drop = dropBar(buffer, grid) {185            let before = Double(cueSpec.dropFirst(4)).map { -$0 } ?? 0186            start = max(0, drop.seconds - before * 4 * grid.beatDuration)187            cueNote = String(format: ", drop found at %.1f s (bass +%.1f dB over the 4 bars before)", drop.seconds, drop.jumpDB)188        } else if let x = Double(cueSpec), let grid = r.grid { start = grid.barStartSeconds(atOrBefore: x) }189        engine.seek(deck: d, seconds: start)190        _ = host.renderOffline(frames: 512)191        engine.setCue(deck: d); engine.setHotcue(deck: d, index: 0)192        var pd = ProjectDeck()193        pd.trackPath = url.path; pd.trackTitle = info.title; pd.bookmark = try? url.bookmarkData()194        pd.position = start; pd.cuePoint = start; pd.hotcues = [start] + Array(repeating: nil, count: 7)195        pd.keylock = true; pd.values["gain"] = gain196        doc.decks.append(pd)197        print("deck \(deckLetters[d]): \(info.title), \(r.grid.map { String(format: "%.2f BPM", $0.bpm) } ?? "no tempo"), key \(r.key?.camelot ?? "?"), gain \(String(format: "%+.1f dB", gain)), cued at \(String(format: "%.2f s", start))\(cueNote)")198    }199    let name = URL(fileURLWithPath: project).deletingPathExtension().lastPathComponent200    doc.name = name201    doc.notes = "Four-deck scripted performance. Load the project, press play on deck A, then run the script \"\(program.automations.first?.name ?? name)\"."202    doc.scripts = [ProjectScript(name: URL(fileURLWithPath: scriptPath).deletingPathExtension().lastPathComponent, source: source)]203    doc.recordings = [URL(fileURLWithPath: out).path]204    do { try ProjectStore.save(doc, to: URL(fileURLWithPath: project)) } catch { print("project not saved: \(error)"); exit(1) }205    print("saved project \(project)")206207    let sr = 48000208    var left: [Float] = [], right: [Float] = []209    func render(_ seconds: Double) { let o = host.renderOffline(frames: Int(seconds * Double(sr))); left += o[0]; right += o[1] }210    engine.play(deck: 0)211    render(2)212    let run = host.start(program)213    print("started the script at \(left.count / sr) s (run \(run ?? -1))")214    var elapsed = 0.0, shown = 0215    while !host.activeRuns.isEmpty, elapsed < 900 {216        render(1); elapsed += 1217        let lines = host.logLines218        for l in lines[min(shown, lines.count)...] { print(String(format: "  %4.0f s  ", Double(left.count) / Double(sr)) + "\(l.text)") }219        shown = lines.count220        if Int(elapsed) % 30 == 0 {221            let s = (0 ..< 4).map { d -> String in let st = engine.deckStatus(d); return st.playing ? String(format: "%@ %.2f BPM", deckLetters[d], st.bpm) : "\(deckLetters[d]) -" }222            print(String(format: "  %4.0f s  ", Double(left.count) / Double(sr)) + s.joined(separator: "  "))223        }224    }225    render(2)226    let s = host.stats227    let peak = max(left.reduce(Float(0)) { max($0, abs($1)) }, right.reduce(Float(0)) { max($0, abs($1)) })228    do { try DJSession.writeWAV(left: left, right: right, sampleRate: Double(sr), to: URL(fileURLWithPath: out)) } catch { print("write failed: \(error)"); exit(1) }229    print(String(format: "wrote %@: %.0f s, peak %.2f dBFS, clipped blocks %d, timed commands %d, late %d, runtime errors %d",230                 out as NSString, Double(left.count) / Double(sr), 20 * log10(max(peak, 1e-6)), engine.renderState.clippedBlocks, s.trackedEvents, s.lateEvents, s.runtimeErrors))231}232233/// The bar where the low end comes in hardest: the bar start that maximises the bass energy of the following eight bars234/// over the four bars before it, searched between 10 % and 60 % of the track. A measurement, not a musical judgement.235func dropBar(_ buffer: TrackBuffer, _ grid: BeatGrid) -> (seconds: Double, jumpDB: Double)? {236    let sr = buffer.sampleRate, l = buffer.leftBuffer, r = buffer.rightBuffer237    let bar = 4 * grid.beatDuration238    guard bar > 0 else { return nil }239    let first = grid.barStartSeconds(atOrBefore: grid.firstBeatSeconds + bar)240    let count = Int((buffer.duration - first) / bar)241    guard count > 24 else { return nil }242    // One-pole low-pass at about 150 Hz, energy per bar.243    let k = Float(1 - exp(-2 * Double.pi * 150 / sr))244    var energy = [Double](repeating: 0, count: count)245    var y: Float = 0246    var frame = max(0, Int(first * sr))247    for b in 0 ..< count {248        let end = min(buffer.frameCount, Int((first + Double(b + 1) * bar) * sr))249        var sum = 0.0250        while frame < end { y += k * ((l[frame] + r[frame]) * 0.5 - y); sum += Double(y * y); frame += 1 }251        energy[b] = sum252    }253    func mean(_ range: Range<Int>) -> Double { range.reduce(0.0) { $0 + energy[$1] } / Double(range.count) }254    var best = -1, bestRatio = 0.0255    for b in max(8, count / 10) ..< min(count - 8, count * 6 / 10) {256        let ratio = mean(b ..< b + 8) / max(1e-12, mean(b - 4 ..< b))257        if ratio > bestRatio { bestRatio = ratio; best = b }258    }259    guard best >= 0 else { return nil }260    return (first + Double(best) * bar, 10 * log10(bestRatio))261}262
Files main
Menu

Theme