Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXAnalysis/Loudness.swift3// Description: ITU-R BS.1770-4 integrated loudness (K-weighting, 400 ms blocks, absolute and relative gating) and sample peak.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Accelerate89enum Loudness {10 /// Reported instead of minus infinity so results stay JSON-encodable.11 static let silenceLUFS = -70.012 static let silencePeakDBFS = -120.01314 struct Measurement {15 var integratedLUFS: Double16 var peakDBFS: Double17 }1819 /// K-weighting (high shelf + RLB high-pass) for an arbitrary sample rate, vDSP coefficient layout.20 static func kWeighting(sampleRate: Double) -> [Double] {21 // Analogue prototypes of the BS.1770 48 kHz filters, re-digitised with the bilinear transform.22 let shelfGainDB = 3.999843853973347, shelfQ = 0.7071752369554196, shelfF = 1681.97445095553323 let k1 = tan(Double.pi * shelfF / sampleRate)24 let vh = pow(10, shelfGainDB / 20)25 let vb = pow(vh, 0.4996667741545416)26 let a0 = 1 + k1 / shelfQ + k1 * k127 let shelf = [(vh + vb * k1 / shelfQ + k1 * k1) / a0, 2 * (k1 * k1 - vh) / a0, (vh - vb * k1 / shelfQ + k1 * k1) / a0,28 2 * (k1 * k1 - 1) / a0, (1 - k1 / shelfQ + k1 * k1) / a0]29 let hpQ = 0.5003270373238773, hpF = 38.1354708760244430 let k2 = tan(Double.pi * hpF / sampleRate)31 let c0 = 1 + k2 / hpQ + k2 * k232 let highpass = [1.0, -2.0, 1.0, 2 * (k2 * k2 - 1) / c0, (1 - k2 / hpQ + k2 * k2) / c0]33 return shelf + highpass34 }3536 /// `left` and `right` have the same length. Identical pointers are measured as dual mono (both channels counted).37 static func measure(left: UnsafeBufferPointer<Float>, right: UnsafeBufferPointer<Float>, sampleRate: Double,38 check: () throws -> Void) throws -> Measurement {39 let n = left.count40 guard n > 0, let l = left.baseAddress, let r = right.baseAddress else {41 return Measurement(integratedLUFS: silenceLUFS, peakDBFS: silencePeakDBFS)42 }43 let isMono = l == r44 var peakL: Float = 0, peakR: Float = 045 vDSP_maxmgv(l, 1, &peakL, vDSP_Length(n))46 if !isMono { vDSP_maxmgv(r, 1, &peakR, vDSP_Length(n)) }47 let peak = Double(max(peakL, peakR))48 let peakDB = peak > 0 ? max(silencePeakDBFS, 20 * log10(peak)) : silencePeakDBFS4950 guard let setup = vDSP_biquad_CreateSetupD(kWeighting(sampleRate: sampleRate), 2) else {51 return Measurement(integratedLUFS: silenceLUFS, peakDBFS: peakDB)52 }53 defer { vDSP_biquad_DestroySetupD(setup) }5455 let step = max(1, Int((sampleRate * 0.1).rounded())) // 100 ms: 400 ms blocks with 75 % overlap56 let steps = n / step57 var energy = [Double](repeating: 0, count: steps) // summed over channels, per 100 ms step58 var totalEnergy = 0.059 var input = [Double](repeating: 0, count: step)60 var output = [Double](repeating: 0, count: step)6162 for channel in 0..<(isMono ? 1 : 2) {63 let source = channel == 0 ? l : r64 var delay = [Double](repeating: 0, count: 6)65 var position = 066 var index = 067 while position < n {68 if index & 63 == 0 { try check() }69 let length = min(step, n - position)70 vDSP_vspdp(source + position, 1, &input, 1, vDSP_Length(length))71 vDSP_biquadD(setup, &delay, input, 1, &output, 1, vDSP_Length(length))72 var e = 0.073 vDSP_svesqD(output, 1, &e, vDSP_Length(length))74 let weighted = isMono ? 2 * e : e75 totalEnergy += weighted76 if index < steps { energy[index] += weighted }77 position += length78 index += 179 }80 }8182 func lufs(_ meanSquare: Double) -> Double { meanSquare > 0 ? -0.691 + 10 * log10(meanSquare) : -Double.infinity }8384 guard steps >= 4 else {85 // Shorter than one gating block: ungated loudness of what there is.86 let value = lufs(totalEnergy / Double(n))87 return Measurement(integratedLUFS: max(silenceLUFS, value), peakDBFS: peakDB)88 }89 var blocks = [Double](repeating: 0, count: steps - 3)90 for j in 0..<(steps - 3) {91 blocks[j] = (energy[j] + energy[j + 1] + energy[j + 2] + energy[j + 3]) / Double(4 * step)92 }93 let absoluteGate = pow(10, (-70 + 0.691) / 10)94 let aboveAbsolute = blocks.filter { $0 > absoluteGate }95 guard !aboveAbsolute.isEmpty else { return Measurement(integratedLUFS: silenceLUFS, peakDBFS: peakDB) }96 let relativeGate = aboveAbsolute.reduce(0, +) / Double(aboveAbsolute.count) * pow(10, -10.0 / 10)97 let gated = aboveAbsolute.filter { $0 > relativeGate }98 guard !gated.isEmpty else { return Measurement(integratedLUFS: silenceLUFS, peakDBFS: peakDB) }99 let value = lufs(gated.reduce(0, +) / Double(gated.count))100 return Measurement(integratedLUFS: max(silenceLUFS, value), peakDBFS: peakDB)101 }102}103