Repository Public License
1//2// ORIX Audio3// File: Core/Sources/ORIXAudioCore/Analysis/TimeDomainMetrics.swift4// Description: Streaming time-domain statistics: peak, RMS, crest factor, zero crossings, DC offset, clipping, dynamics.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import Accelerate10import Foundation1112public struct TimeInterval2: Codable, Sendable, Hashable {13 public var start: Double14 public var end: Double15 public var duration: Double { end - start }16 public init(start: Double, end: Double) { self.start = start; self.end = end }17}1819public struct TimeDomainMetrics: Codable, Sendable, Equatable {20 public var sampleCount: Int = 021 public var duration: Double = 022 /// Largest absolute sample value (linear, full scale = 1) and the same in dBFS.23 public var peak: Float = 024 public var peakDBFS: Float = Decibels.floor25 public var minimum: Float = 026 public var maximum: Float = 027 /// Root-mean-square level (linear) and in dBFS (a full-scale sine reads −3.01 dBFS RMS).28 public var rms: Float = 029 public var rmsDBFS: Float = Decibels.floor30 /// Peak-to-RMS ratio in dB.31 public var crestFactorDB: Float = 032 public var dcOffset: Float = 033 /// Zero crossings per second.34 public var zeroCrossingRate: Double = 035 /// Samples at or above the clipping threshold that belong to a run of at least `clipRunLength` consecutive samples.36 public var clippedSamples: Int = 037 public var clippingEvents: Int = 038 /// Spread between the 95th and 10th percentile of 400 ms RMS levels, in dB. An indicator, not a standard measure.39 public var dynamicSpreadDB: Float = 040 /// 10th percentile of 400 ms RMS levels in dBFS: an estimate of the background level.41 public var noiseFloorDBFS: Float = Decibels.floor42 public var silences: [TimeInterval2] = []43 public var silentDuration: Double { silences.reduce(0) { $0 + $1.duration } }44 public init() {}45}4647/// Accumulates metrics over a stream of mono chunks. Double-precision sums keep hours of audio numerically stable.48public struct TimeDomainAccumulator {49 public static let clipThreshold: Float = 0.99950 public static let clipRunLength = 351 public var silenceThresholdDBFS: Float = -5052 public var minimumSilence: Double = 0.55354 public let sampleRate: Double55 private var count = 056 private var sum = 0.0, sumSquares = 0.057 private var mn: Float = .greatestFiniteMagnitude, mx: Float = -.greatestFiniteMagnitude58 private var crossings = 059 private var lastSign = 060 private var clipRun = 0, clipped = 0, clipEvents = 061 private var blockAcc = 0.0, blockCount = 062 private let blockSize: Int63 private var blockLevels: [Float] = []64 private var silenceStart: Double?65 private var silences: [TimeInterval2] = []6667 public init(sampleRate: Double) {68 self.sampleRate = sampleRate69 self.blockSize = max(1, Int(sampleRate * 0.4))70 }7172 public mutating func push(_ s: UnsafeBufferPointer<Float>) {73 guard !s.isEmpty else { return }74 var lo: Float = 0, hi: Float = 075 vDSP_minv(s.baseAddress!, 1, &lo, vDSP_Length(s.count))76 vDSP_maxv(s.baseAddress!, 1, &hi, vDSP_Length(s.count))77 mn = min(mn, lo); mx = max(mx, hi)78 for v in s {79 let sq = Double(v) * Double(v)80 sumSquares += sq; sum += Double(v)81 let sign = v > 0 ? 1 : (v < 0 ? -1 : 0)82 if sign != 0 { if lastSign != 0 && sign != lastSign { crossings += 1 }; lastSign = sign }83 if abs(v) >= Self.clipThreshold {84 clipRun += 185 if clipRun == Self.clipRunLength { clipped += Self.clipRunLength; clipEvents += 1 } else if clipRun > Self.clipRunLength { clipped += 1 }86 } else { clipRun = 0 }87 blockAcc += sq; blockCount += 188 if blockCount == blockSize { closeBlock() }89 }90 count += s.count91 }9293 public mutating func push(_ s: [Float]) { s.withUnsafeBufferPointer { push($0) } }9495 private mutating func closeBlock() {96 let level = Decibels.fromPower(Float(blockAcc / Double(max(1, blockCount))))97 let index = blockLevels.count98 blockLevels.append(level)99 let t = Double(index * blockSize) / sampleRate100 if level < silenceThresholdDBFS {101 if silenceStart == nil { silenceStart = t }102 } else if let start = silenceStart {103 if t - start >= minimumSilence { silences.append(.init(start: start, end: t)) }104 silenceStart = nil105 }106 blockAcc = 0; blockCount = 0107 }108109 public mutating func finish() -> TimeDomainMetrics {110 if blockCount > blockSize / 4 { closeBlock() }111 let duration = Double(count) / sampleRate112 if let start = silenceStart, duration - start >= minimumSilence { silences.append(.init(start: start, end: duration)); silenceStart = nil }113 var m = TimeDomainMetrics()114 guard count > 0 else { return m }115 m.sampleCount = count116 m.duration = duration117 m.minimum = mn; m.maximum = mx118 m.peak = max(abs(mn), abs(mx)); m.peakDBFS = Decibels.fromAmplitude(m.peak)119 m.rms = Float((sumSquares / Double(count)).squareRoot()); m.rmsDBFS = Decibels.fromAmplitude(m.rms)120 m.crestFactorDB = m.rms > 0 ? m.peakDBFS - m.rmsDBFS : 0121 m.dcOffset = Float(sum / Double(count))122 m.zeroCrossingRate = Double(crossings) / duration123 m.clippedSamples = clipped; m.clippingEvents = clipEvents124 if !blockLevels.isEmpty {125 let sorted = blockLevels.sorted()126 func pct(_ p: Double) -> Float { sorted[min(sorted.count - 1, Int(p * Double(sorted.count - 1) + 0.5))] }127 m.noiseFloorDBFS = pct(0.10)128 m.dynamicSpreadDB = max(0, pct(0.95) - max(pct(0.10), -120))129 }130 m.silences = silences131 return m132 }133}134