SPB Git

Repository Public

Waveform.swift 6.1 KB 136 lines swift

1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXAnalysis/Waveform.swift3// Description: Three-band waveform summary (low / mid / high + full-band peak) for scrolling and overview displays.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Accelerate89public struct WaveformSummary: Codable, Sendable {10    /// Columns per second of audio (150 for a fresh analysis; lower after `overview(columns:)`).11    public var columnsPerSecond: Double12    /// Per-column band peak amplitude, square-root scaled: value = 255 * sqrt(linear amplitude).13    /// Bands: below ~200 Hz, 200–2500 Hz, above ~2500 Hz (8th-order Butterworth crossovers).14    public var low: [UInt8]15    public var mid: [UInt8]16    public var high: [UInt8]17    /// Per-column full-band sample peak over both channels, linear: value = 255 * |amplitude| (255 = 0 dBFS).18    public var peak: [UInt8]1920    public var count: Int { peak.count }2122    public init(columnsPerSecond: Double = 150, low: [UInt8] = [], mid: [UInt8] = [], high: [UInt8] = [], peak: [UInt8] = []) {23        self.columnsPerSecond = columnsPerSecond24        self.low = low25        self.mid = mid26        self.high = high27        self.peak = peak28    }2930    /// Max-pooled down-sample for the full-track overview. Returns `self` when `columns >= count`.31    public func overview(columns: Int) -> WaveformSummary {32        let n = count33        guard columns > 0, n > 0 else { return WaveformSummary(columnsPerSecond: columnsPerSecond) }34        guard columns < n else { return self }35        func pool(_ a: [UInt8]) -> [UInt8] {36            guard a.count == n else { return [] }37            var out = [UInt8](repeating: 0, count: columns)38            for c in 0..<columns {39                let start = c * n / columns40                let end = max(start + 1, (c + 1) * n / columns)41                var m: UInt8 = 042                for i in start..<min(end, n) where a[i] > m { m = a[i] }43                out[c] = m44            }45            return out46        }47        return WaveformSummary(columnsPerSecond: columnsPerSecond * Double(columns) / Double(n),48                               low: pool(low), mid: pool(mid), high: pool(high), peak: pool(peak))49    }50}5152enum WaveformBuilder {53    static let columnsPerSecond = 150.054    static let lowCrossover = 200.055    static let highCrossover = 2500.05657    enum FilterKind { case lowpass, highpass }5859    /// 8th-order Butterworth filter as four biquad sections (-3 dB at `frequency`, 48 dB/octave), vDSP coefficient layout.60    static func sections(_ kind: FilterKind, frequency: Double, sampleRate: Double) -> [Double] {61        let f = min(frequency, sampleRate * 0.45)62        let w0 = 2 * Double.pi * f / sampleRate63        let cosw = cos(w0)64        var out: [Double] = []65        for q in [0.5097955791041592, 0.6013448869350453, 0.8999762231364156, 2.562915447741506] {66            let alpha = sin(w0) / (2 * q)67            let a0 = 1 + alpha68            let b: [Double]69            switch kind {70            case .lowpass: b = [(1 - cosw) / 2, 1 - cosw, (1 - cosw) / 2]71            case .highpass: b = [(1 + cosw) / 2, -(1 + cosw), (1 + cosw) / 2]72            }73            out += [b[0] / a0, b[1] / a0, b[2] / a0, -2 * cosw / a0, (1 - alpha) / a0]74        }75        return out76    }7778    static func build(mono: UnsafeBufferPointer<Float>, left: UnsafeBufferPointer<Float>, right: UnsafeBufferPointer<Float>,79                      sampleRate: Double, check: () throws -> Void) throws -> WaveformSummary {80        let n = mono.count81        guard n > 0, let base = mono.baseAddress, let l = left.baseAddress, let r = right.baseAddress else {82            return WaveformSummary(columnsPerSecond: columnsPerSecond)83        }84        let columns = Int((Double(n) * columnsPerSecond / sampleRate).rounded(.up))85        let samplesPerColumn = sampleRate / columnsPerSecond86        @inline(__always) func bounds(_ c: Int) -> (Int, Int) {87            let s = min(n - 1, Int(Double(c) * samplesPerColumn))88            let e = min(n, max(s + 1, Int(Double(c + 1) * samplesPerColumn)))89            return (s, e)90        }91        @inline(__always) func quantizeSqrt(_ v: Float) -> UInt8 { UInt8(min(255, (max(0, v).squareRoot() * 255).rounded())) }9293        var peak = [UInt8](repeating: 0, count: columns)94        let isMono = l == r95        for c in 0..<columns {96            let (s, e) = bounds(c)97            var a: Float = 0, b: Float = 098            vDSP_maxmgv(l + s, 1, &a, vDSP_Length(e - s))99            if !isMono { vDSP_maxmgv(r + s, 1, &b, vDSP_Length(e - s)) }100            peak[c] = UInt8(min(255, (max(a, b) * 255).rounded()))101        }102        try check()103104        let scratch = UnsafeMutablePointer<Float>.allocate(capacity: n)105        defer { scratch.deallocate() }106107        func band(_ chains: [[Double]]) -> [UInt8] {108            var source = base109            for coefficients in chains {110                let sectionCount = coefficients.count / 5111                guard let setup = vDSP_biquad_CreateSetup(coefficients, vDSP_Length(sectionCount)) else { continue }112                var delay = [Float](repeating: 0, count: 2 * sectionCount + 2)113                vDSP_biquad(setup, &delay, source, 1, scratch, 1, vDSP_Length(n))114                vDSP_biquad_DestroySetup(setup)115                source = UnsafePointer(scratch)116            }117            var out = [UInt8](repeating: 0, count: columns)118            for c in 0..<columns {119                let (s, e) = bounds(c)120                var m: Float = 0121                vDSP_maxmgv(scratch + s, 1, &m, vDSP_Length(e - s))122                out[c] = quantizeSqrt(m)123            }124            return out125        }126127        let low = band([sections(.lowpass, frequency: lowCrossover, sampleRate: sampleRate)])128        try check()129        let mid = band([sections(.highpass, frequency: lowCrossover, sampleRate: sampleRate),130                        sections(.lowpass, frequency: highCrossover, sampleRate: sampleRate)])131        try check()132        let high = band([sections(.highpass, frequency: highCrossover, sampleRate: sampleRate)])133        return WaveformSummary(columnsPerSecond: columnsPerSecond, low: low, mid: mid, high: high, peak: peak)134    }135}136
Files main
Menu

Theme