Repository Public License
1//2// ORIX Audio3// File: Core/Sources/ORIXAudioCore/Analysis/Loudness.swift4// Description: Programme loudness per ITU-R BS.1770-4 (K-weighting, gated integration), EBU Tech 3342 loudness range, true peak.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import Foundation1011/// Loudness of a digital audio signal relative to full scale (LUFS / LU / dBTP).12/// These are properties of the *file*. They are not sound pressure levels: an iPhone microphone is not a calibrated instrument.13public struct LoudnessMetrics: Codable, Sendable, Equatable {14 /// Gated programme loudness (BS.1770-4), LUFS. nil when the programme is shorter than one 400 ms block or entirely below −70 LUFS.15 public var integratedLUFS: Double?16 /// Maximum momentary (400 ms) and short-term (3 s) loudness, LUFS.17 public var maxMomentaryLUFS: Double?18 public var maxShortTermLUFS: Double?19 /// Loudness range (EBU Tech 3342), LU. nil when fewer than 3 s of ungated material exist.20 public var loudnessRangeLU: Double?21 /// Maximum inter-sample peak estimated by 4× oversampling, dBTP.22 public var truePeakDBTP: Double?23 /// Short-term loudness once per second (LUFS), for plotting.24 public var shortTermSeries: [Float] = []25 public init() {}26}2728/// K-weighting filter of BS.1770: a high-shelf "head" stage followed by the RLB high-pass. The standard tabulates29/// coefficients at 48 kHz; these closed forms reproduce them and give the equivalent analogue response at other rates.30public enum KWeighting {31 public static func sections(sampleRate fs: Double) -> [BiquadCoefficients] {32 // Stage 1: high shelf33 let f0 = 1681.974450955533, g = 3.999843853973347, q = 0.707175236955419634 let k = tan(Double.pi * f0 / fs), vh = pow(10, g / 20), vb = pow(vh, 0.4996667741545416)35 let a0 = 1 + k / q + k * k36 let shelf = BiquadCoefficients(b0: (vh + vb * k / q + k * k) / a0, b1: 2 * (k * k - vh) / a0, b2: (vh - vb * k / q + k * k) / a0,37 a1: 2 * (k * k - 1) / a0, a2: (1 - k / q + k * k) / a0)38 // Stage 2: RLB high-pass (numerator fixed at 1, −2, 1 as in the standard)39 let f1 = 38.13547087602444, q1 = 0.500327037323877340 let k1 = tan(Double.pi * f1 / fs), a01 = 1 + k1 / q1 + k1 * k141 let hp = BiquadCoefficients(b0: 1, b1: -2, b2: 1, a1: 2 * (k1 * k1 - 1) / a01, a2: (1 - k1 / q1 + k1 * k1) / a01)42 return [shelf, hp]43 }44}4546/// Streaming loudness meter for 1 or 2 channels (channel weights are 1.0 for L, R and mono per BS.1770).47public struct LoudnessMeter {48 public let sampleRate: Double49 public let channels: Int50 private var filters: [BiquadCascade]51 // 100 ms sub-block energies (sum over channels of mean square); 400 ms blocks with 75 % overlap are sums of 4.52 private let subBlock: Int53 private var acc = 0.0, accCount = 054 private var subEnergies: [Double] = []55 private var truePeak = 0.056 private var oversamplers: [TruePeakOversampler]5758 public init(sampleRate: Double, channels: Int) {59 precondition(channels >= 1 && channels <= 2)60 self.sampleRate = sampleRate; self.channels = channels61 filters = (0..<channels).map { _ in BiquadCascade(KWeighting.sections(sampleRate: sampleRate)) }62 subBlock = Int((sampleRate * 0.1).rounded())63 oversamplers = (0..<channels).map { _ in TruePeakOversampler() }64 }6566 /// Pushes one chunk; `channelData[c]` holds `frames` samples for channel c.67 public mutating func push(_ channelData: [UnsafePointer<Float>], frames: Int) {68 for n in 0..<frames {69 var e = 0.070 for c in 0..<channels {71 let x = Double(channelData[c][n])72 let y = filters[c].processSample(x)73 e += y * y74 truePeak = max(truePeak, oversamplers[c].push(x))75 }76 acc += e; accCount += 177 if accCount == subBlock { subEnergies.append(acc / Double(subBlock)); acc = 0; accCount = 0 }78 }79 }8081 public mutating func push(mono: [Float]) {82 mono.withUnsafeBufferPointer { push([$0.baseAddress!], frames: $0.count) }83 }8485 static func lufs(_ meanSquare: Double) -> Double { -0.691 + 10 * log10(max(meanSquare, 1e-30)) }8687 /// Momentary loudness of the most recent 400 ms, for live meters.88 public var momentaryLUFS: Double? {89 guard subEnergies.count >= 4 else { return nil }90 return Self.lufs(subEnergies.suffix(4).reduce(0, +) / 4)91 }9293 /// Short-term loudness of the most recent 3 s.94 public var shortTermLUFS: Double? {95 guard subEnergies.count >= 30 else { return nil }96 return Self.lufs(subEnergies.suffix(30).reduce(0, +) / 30)97 }9899 public func finish() -> LoudnessMetrics {100 var m = LoudnessMetrics()101 m.truePeakDBTP = truePeak > 0 ? 20 * log10(truePeak) : nil102 let s = subEnergies103 guard s.count >= 4 else { return m }104 // 400 ms gating blocks, 100 ms hop (75 % overlap).105 var blocks = [Double](); blocks.reserveCapacity(s.count - 3)106 var window = s[0] + s[1] + s[2] + s[3]107 blocks.append(window / 4)108 if s.count > 4 { for i in 4..<s.count { window += s[i] - s[i - 4]; blocks.append(max(window, 0) / 4) } }109 m.maxMomentaryLUFS = blocks.max().map(Self.lufs)110111 // Integrated: absolute gate −70 LUFS, then relative gate 10 LU below the absolute-gated mean.112 let absolute = blocks.filter { Self.lufs($0) > -70 }113 if !absolute.isEmpty {114 let relativeThreshold = Self.lufs(absolute.reduce(0, +) / Double(absolute.count)) - 10115 let gated = absolute.filter { Self.lufs($0) > relativeThreshold }116 if !gated.isEmpty { m.integratedLUFS = Self.lufs(gated.reduce(0, +) / Double(gated.count)) }117 }118119 // Short-term: 3 s windows. Maximum uses a 100 ms hop; LRA uses a 1 s hop (EBU Tech 3342 requires ≥ 1 Hz... ≤ 1 s hop).120 if s.count >= 30 {121 var shortTerm = [Double](); shortTerm.reserveCapacity(s.count - 29)122 var w = s[0..<30].reduce(0, +)123 shortTerm.append(w / 30)124 if s.count > 30 { for i in 30..<s.count { w += s[i] - s[i - 30]; shortTerm.append(max(w, 0) / 30) } }125 m.maxShortTermLUFS = shortTerm.max().map(Self.lufs)126 m.shortTermSeries = stride(from: 0, to: shortTerm.count, by: 10).map { Float(Self.lufs(shortTerm[$0])) }127 // LRA: absolute gate −70, relative gate −20 LU, then 10th–95th percentile spread.128 let abs3 = shortTerm.filter { Self.lufs($0) > -70 }129 if !abs3.isEmpty {130 let threshold = Self.lufs(abs3.reduce(0, +) / Double(abs3.count)) - 20131 let gated = abs3.map(Self.lufs).filter { $0 > threshold }.sorted()132 if gated.count >= 2 {133 func pct(_ p: Double) -> Double { gated[Int((p * Double(gated.count - 1)).rounded())] }134 m.loudnessRangeLU = pct(0.95) - pct(0.10)135 }136 }137 }138 return m139 }140}141142/// 4× oversampling peak detector (BS.1770-4 Annex 2 approach): a 48-tap Kaiser-windowed sinc run as four polyphase branches.143struct TruePeakOversampler: Sendable {144 static let taps = 12 // per phase145 static let phases: [[Double]] = {146 let factor = 4, length = taps * factor147 let beta = 8.0148 func i0(_ x: Double) -> Double { var s = 1.0, t = 1.0; for k in 1..<30 { t *= (x / (2 * Double(k))) * (x / (2 * Double(k))); s += t }; return s }149 var h = [Double](repeating: 0, count: length)150 let centre = Double(length - 1) / 2151 for n in 0..<length {152 let x = (Double(n) - centre) / Double(factor)153 let sinc = x == 0 ? 1 : sin(Double.pi * x) / (Double.pi * x)154 let r = (Double(n) - centre) / centre155 h[n] = sinc * i0(beta * (1 - r * r).squareRoot()) / i0(beta)156 }157 return (0..<factor).map { p in158 var branch = (0..<taps).map { h[$0 * factor + p] }159 let sum = branch.reduce(0, +)160 branch = branch.map { $0 / sum } // unity DC gain per phase161 return branch162 }163 }()164165 private var history = [Double](repeating: 0, count: TruePeakOversampler.taps)166 private var index = 0167168 /// Pushes one sample; returns the largest absolute value among the four interpolated samples.169 mutating func push(_ x: Double) -> Double {170 history[index] = x171 index = (index + 1) % Self.taps172 var peak = 0.0173 for branch in Self.phases {174 var y = 0.0175 var j = index176 // history[index] is the oldest sample; branch[taps-1] pairs with the oldest.177 for t in stride(from: Self.taps - 1, through: 0, by: -1) {178 y += branch[t] * history[j]179 j += 1; if j == Self.taps { j = 0 }180 }181 peak = max(peak, abs(y))182 }183 return peak184 }185}186