Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Music pour macOS9// File : Core/Audio/LoudnessAnalyzer.swift10// Description : Integrated loudness of a file, measured the ITU-R BS.177011// way (K-weighting, 400 ms blocks, absolute and relative.12// Module : Core13// Repository : https://git.spboucher.ai/sp-music-macos14// Created : 2026-11-1715// Last Modified : 2026-11-1816//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : None specified (no license file in this repository)82// Maintainer : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import Foundation90import AVFoundation91import Accelerate9293/// Integrated loudness of a file, measured the ITU-R BS.1770 way (K-weighting, 400 ms blocks, absolute and relative94/// gates), plus its sample peak. Used only for the optional volume normalisation: the files are never modified.95public enum LoudnessAnalyzer {96 public struct Result: Sendable, Equatable { public var lufs: Double; public var peak: Double }97 public static let targetLUFS = -14.09899 private struct Biquad {100 var b0, b1, b2, a1, a2: Double101 var z1 = 0.0, z2 = 0.0102 mutating func process(_ x: Double) -> Double { let y = b0 * x + z1; z1 = b1 * x - a1 * y + z2; z2 = b2 * x - a2 * y; return y }103 }104 /// The two K-weighting filters of BS.1770, computed for any sample rate.105 private static func filters(rate: Double) -> (Biquad, Biquad) {106 let f0 = 1681.974450955533, g = 3.999843853973347, q = 0.7071752369554196107 let k = tan(.pi * f0 / rate), vh = pow(10, g / 20), vb = pow(vh, 0.4996667741545416)108 let a0 = 1 + k / q + k * k109 let shelf = Biquad(b0: (vh + vb * k / q + k * k) / a0, b1: 2 * (k * k - vh) / a0, b2: (vh - vb * k / q + k * k) / a0, a1: 2 * (k * k - 1) / a0, a2: (1 - k / q + k * k) / a0)110 let f1 = 38.13547087602444, q1 = 0.5003270373238773111 let k1 = tan(.pi * f1 / rate), a01 = 1 + k1 / q1 + k1 * k1112 let highpass = Biquad(b0: 1, b1: -2, b2: 1, a1: 2 * (k1 * k1 - 1) / a01, a2: (1 - k1 / q1 + k1 * k1) / a01)113 return (shelf, highpass)114 }115116 public static func analyze(_ source: ByteSource, typeHint: AudioFileTypeID = 0) throws -> Result {117 let dec = try AudioDecoder(source: source, typeHint: typeHint)118 let rate = dec.info.sampleRate, channels = min(dec.info.channels, 2)119 guard let buffer = AVAudioPCMBuffer(pcmFormat: dec.processingFormat, frameCapacity: 32768) else { throw DecoderError.unsupportedFormat }120 var chain = (0..<channels).map { _ in filters(rate: rate) }121 let block = Int(rate * 0.4), hop = Int(rate * 0.1)122 var ring = [Double](repeating: 0, count: block) // per-frame weighted energy (channels summed)123 var filled = 0, pos = 0, sinceHop = 0, running = 0.0124 var blocks: [Double] = []125 var peak: Float = 0126 while true {127 let n = Int(try dec.read(into: buffer))128 if n == 0 { break }129 guard let data = buffer.floatChannelData else { break }130 for c in 0..<channels { var m: Float = 0; vDSP_maxmgv(data[c], 1, &m, vDSP_Length(n)); peak = max(peak, m) }131 for i in 0..<n {132 var e = 0.0133 for c in 0..<channels { let y = chain[c].1.process(chain[c].0.process(Double(data[c][i]))); e += y * y }134 running += e - ring[pos]; ring[pos] = e; pos = (pos + 1) % block135 if filled < block { filled += 1 }136 sinceHop += 1137 if filled == block, sinceHop >= hop { sinceHop = 0; blocks.append(max(running, 0) / Double(block)) }138 }139 }140 let lk = { (z: Double) in -0.691 + 10 * log10(max(z, 1e-12)) }141 let abs = blocks.filter { lk($0) > -70 }142 guard !abs.isEmpty else { return Result(lufs: -70, peak: Double(peak)) }143 let relGate = lk(abs.reduce(0, +) / Double(abs.count)) - 10144 let gated = abs.filter { lk($0) > relGate }145 let mean = (gated.isEmpty ? abs : gated).reduce(0, +) / Double((gated.isEmpty ? abs : gated).count)146 return Result(lufs: lk(mean), peak: Double(peak))147 }148149 /// Gain (dB) that brings a file to the target loudness without letting its peak clip.150 public static func gainDB(lufs: Double, peak: Double, target: Double = targetLUFS) -> Float {151 var g = max(-15, min(12, target - lufs))152 if peak > 0 { g = min(g, -20 * log10(peak) - 0.3) } // keep 0.3 dB of headroom153 return Float(g)154 }155}156