SPB Git

Repository Public

TrackAnalyzer.swift 6.3 KB 139 lines swift

1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXAnalysis/TrackAnalyzer.swift3// Description: Public entry point: analysis result model and the full-track analysis pipeline.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Accelerate89public struct AnalysisResult: Codable, Sendable {10    public static let currentVersion: Int = 111    /// Target of `suggestedGainDB`.12    public static let targetLUFS: Double = -1413    /// Value reported for digital silence (instead of minus infinity, which JSON cannot carry).14    public static let silenceLUFS: Double = -701516    public var version: Int17    public var duration: Double18    /// nil when no tempo could be estimated19    public var grid: BeatGrid?20    /// 0...121    public var bpmConfidence: Double22    /// 0...1, low when the tempo drifts (live drummers, rubato)23    public var tempoStability: Double24    public var downbeatConfidence: Double25    public var key: KeyEstimate?26    /// ITU-R BS.1770 K-weighted, gated. Never below `silenceLUFS`.27    public var integratedLUFS: Double28    /// Sample peak (not true peak). Never below -120.29    public var peakDBFS: Double30    /// Gain to reach -14 LUFS, clamped so the peak stays <= -1 dBFS. 0 for silence.31    public var suggestedGainDB: Double32    /// Onset times in seconds, ascending (strongest first-pass onsets, at most 4096).33    public var transients: [Float]34    public var waveform: WaveformSummary3536    public init(version: Int = AnalysisResult.currentVersion, duration: Double = 0, grid: BeatGrid? = nil,37                bpmConfidence: Double = 0, tempoStability: Double = 0, downbeatConfidence: Double = 0,38                key: KeyEstimate? = nil, integratedLUFS: Double = AnalysisResult.silenceLUFS, peakDBFS: Double = -120,39                suggestedGainDB: Double = 0, transients: [Float] = [], waveform: WaveformSummary = WaveformSummary()) {40        self.version = version41        self.duration = duration42        self.grid = grid43        self.bpmConfidence = bpmConfidence44        self.tempoStability = tempoStability45        self.downbeatConfidence = downbeatConfidence46        self.key = key47        self.integratedLUFS = integratedLUFS48        self.peakDBFS = peakDBFS49        self.suggestedGainDB = suggestedGainDB50        self.transients = transients51        self.waveform = waveform52    }53}5455public struct AnalysisOptions: Sendable {56    /// Tempi are folded into this range (half-time / double-time resolution).57    public var bpmRange: ClosedRange<Double> = 70...18058    public init() {}59}6061public enum TrackAnalyzer {62    public static let maximumTransients = 40966364    /// Planar float input; `right` may equal `left` for mono. Synchronous, CPU-bound, call off the main thread.65    /// `progress` is called with 0...1 occasionally; `isCancelled` is polled and makes the function throw CancellationError.66    public static func analyze(left: UnsafeBufferPointer<Float>, right: UnsafeBufferPointer<Float>, sampleRate: Double,67                               options: AnalysisOptions = .init(), progress: ((Double) -> Void)? = nil,68                               isCancelled: (() -> Bool)? = nil) throws -> AnalysisResult {69        func check() throws { if isCancelled?() == true { throw CancellationError() } }70        try check()71        progress?(0)72        let n = min(left.count, right.count)73        guard n > 0, sampleRate.isFinite, sampleRate >= 1000, let lBase = left.baseAddress, let rBase = right.baseAddress else {74            progress?(1)75            return AnalysisResult()76        }77        let l = UnsafeBufferPointer(start: lBase, count: n)78        let r = UnsafeBufferPointer(start: rBase, count: n)79        let duration = Double(n) / sampleRate80        var result = AnalysisResult(duration: duration)8182        // Loudness and peak.83        let loudness = try Loudness.measure(left: l, right: r, sampleRate: sampleRate, check: check)84        result.integratedLUFS = loudness.integratedLUFS85        result.peakDBFS = loudness.peakDBFS86        if loudness.integratedLUFS > Loudness.silenceLUFS {87            result.suggestedGainDB = min(AnalysisResult.targetLUFS - loudness.integratedLUFS, -1 - loudness.peakDBFS)88        }89        progress?(0.15)9091        // Mono mix (one extra copy; none for mono input).92        var mixBuffer: UnsafeMutableBufferPointer<Float>?93        defer { mixBuffer?.deallocate() }94        let mono: UnsafeBufferPointer<Float>95        if lBase == rBase {96            mono = l97        } else {98            let buffer = UnsafeMutableBufferPointer<Float>.allocate(capacity: n)99            mixBuffer = buffer100            var half: Float = 0.5101            vDSP_vasm(lBase, 1, rBase, 1, &half, buffer.baseAddress!, 1, vDSP_Length(n))102            mono = UnsafeBufferPointer(buffer)103        }104        try check()105106        result.waveform = try WaveformBuilder.build(mono: mono, left: l, right: r, sampleRate: sampleRate, check: check)107        progress?(0.4)108109        let features = try OnsetAnalyzer.analyze(mono: mono, sampleRate: sampleRate, check: check)110        let detrended = OnsetAnalyzer.detrended(features.full, frameRate: features.frameRate)111        progress?(0.7)112113        if let tempo = try TempoEstimator.estimate(features: features, detrended: detrended, duration: duration,114                                                   range: options.bpmRange, check: check) {115            result.grid = tempo.grid116            result.bpmConfidence = tempo.bpmConfidence117            result.tempoStability = tempo.tempoStability118            result.downbeatConfidence = tempo.downbeatConfidence119        }120        result.transients = OnsetAnalyzer.transients(features, detrended: detrended, limit: maximumTransients)121        progress?(0.8)122123        result.key = try KeyEstimator.estimate(mono: mono, sampleRate: sampleRate, check: check)124        try check()125        progress?(1)126        return result127    }128129    /// Convenience for array input.130    public static func analyze(left: [Float], right: [Float], sampleRate: Double, options: AnalysisOptions = .init(),131                               progress: ((Double) -> Void)? = nil, isCancelled: (() -> Bool)? = nil) throws -> AnalysisResult {132        try left.withUnsafeBufferPointer { l in133            try right.withUnsafeBufferPointer { r in134                try analyze(left: l, right: r, sampleRate: sampleRate, options: options, progress: progress, isCancelled: isCancelled)135            }136        }137    }138}139
Files main
Menu

Theme