Files
Lyrebird/Sources/Lyrebird/Generators/Analysis/LoudnessBandCore.swift
T
2026-06-21 11:45:58 -07:00

316 lines
14 KiB
Swift

// LoudnessBandCore.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Shared loudness back-end for ``Loudness``: bins a `SpectralBuffer` into
/// third-octave band levels (dB SPL via the calibration offset), then computes
/// total loudness in sones under one of the three ``LoudnessModel`` algorithms.
///
/// All buffers are allocated once at `init`; the per-block methods perform no
/// allocation (RT-safe). The ISO 532 B path is an independent implementation of
/// the published DIN 45631 / Zwicker stationary algorithm.
final class LoudnessBandCore {
// MARK: - Fixed at init
private let calibrationDB: Double
/// `binBand[k]` = third-octave band index for FFT bin `k`, or `-1` if the
/// bin falls outside the 25 Hz … 12.5 kHz grid.
private let binBand: [Int]
private let binCount: Int
// MARK: - Scratch (allocated once)
private var bandPower: [Double] // 28 third-octave band powers (linear)
private var bandLevel: [Double] // 28 third-octave band levels (dB SPL)
private var coreLoudness: [Double] // 21 critical-band core loudnesses
private var critLevel: [Double] // 20 critical-band levels (dB, ear-corrected)
private var ti: [Double] // low-band intensities (ISO core path)
private var logic: [Bool] // RAP-range comparison flags (ISO core path)
// MARK: - Temporal-mask state (realtimeZwicker only)
private var tmaskState: Double = 0.0
// MARK: - Init
/// - Parameters:
/// - fftSize: FFT size of the paired analysis chain.
/// - sampleRate: Engine sample rate (Hz), for bin→Hz mapping.
/// - calibrationDB: dBFS→SPL offset added to each band power level.
/// - binCount: Number of spectral bins (`fftSize/2 + 1`).
init(fftSize: Int, sampleRate: Double, calibrationDB: Double, binCount: Int) {
self.calibrationDB = calibrationDB
self.binCount = max(0, binCount)
let safeSampleRate: Double = max(1.0, sampleRate)
let binHz: Double = safeSampleRate / Double(max(1, fftSize))
let ratio: Double = Foundation.pow(2.0, loudnessThirdOctaveHalfBandwidthExponent)
var map: [Int] = [Int](repeating: -1, count: self.binCount)
for k: Int in 0..<self.binCount {
let freq: Double = Double(k) * binHz
var band: Int = -1
for j: Int in 0..<loudnessISOThirdOctaveCount {
let centre: Double = loudnessISOCenterFreqsHz[j]
let lo: Double = centre / ratio
let hi: Double = centre * ratio
if freq >= lo && freq < hi {
band = j
break
}
}
map[k] = band
}
self.binBand = map
self.bandPower = [Double](repeating: 0.0, count: loudnessISOThirdOctaveCount)
self.bandLevel = [Double](repeating: 0.0, count: loudnessISOThirdOctaveCount)
self.coreLoudness = [Double](repeating: 0.0, count: loudnessCriticalBandCount + 1)
self.critLevel = [Double](repeating: 0.0, count: loudnessCriticalBandCount)
self.ti = [Double](repeating: 0.0, count: loudnessISOLowBandCount)
self.logic = [Bool](repeating: false, count: loudnessISORAP.count)
}
// MARK: - Critical-band levels (shared by the Zwicker models)
/// Fill `critLevel[0..19]` with ear-corrected critical-band levels. The first
/// three bands are the combined low third-octave bands (`computeLCB`); the
/// rest map one-to-one onto third-octave bands 315 Hz … 12.5 kHz.
///
/// - Parameters:
/// - lowFreqCorrected: apply the `RAP`/`DLL` equal-loudness correction to
/// the low bands (ISO 532 B) vs a plain power sum (real-time).
/// - field: free/diffuse field selector.
private func fillCriticalLevels(lowFreqCorrected: Bool, field: LoudnessField) {
let lcb: (Double, Double, Double) = computeLCB(corrected: lowFreqCorrected)
let offset: Int = loudnessISOThirdOctaveCount - loudnessCriticalBandCount
for z: Int in 0..<loudnessCriticalBandCount {
var le: Double
if z == 0 { le = lcb.0 } else if z == 1 { le = lcb.1 } else if z == 2 { le = lcb.2 }
else { le = bandLevel[z + offset] }
le -= loudnessISOA0[z]
if field == .diffuse { le += loudnessISODDF[z] }
critLevel[z] = le
}
}
/// Combine the lowest third-octave bands into the first three critical-band
/// levels (dB). With `corrected`, the `RAP`/`DLL` equal-loudness correction is
/// applied first (ISO 532 B); otherwise a plain power sum (real-time).
private func computeLCB(corrected: Bool) -> (Double, Double, Double) {
for i: Int in 0..<loudnessISOLowBandCount {
let level: Double = bandLevel[i]
var corr: Double = 0.0
if corrected {
for j: Int in 0..<loudnessISORAP.count {
logic[j] = level > (loudnessISORAP[j] - loudnessISODLL[j][i])
}
corr = loudnessISODLL[0][i]
if logic[0] { corr = 0.0 }
for j: Int in 1..<(loudnessISORAP.count - 1) {
if logic[j - 1] != logic[j] { corr = loudnessISODLL[j][i] }
}
}
let xp: Double = level + corr
ti[i] = Foundation.pow(loudnessDBDecadeFactor, xp / loudnessDBDecadeFactor)
}
let gi0: Double = ti[0] + ti[1] + ti[2] + ti[3] + ti[4] + ti[5]
let gi1: Double = ti[6] + ti[7] + ti[8]
let gi2: Double = ti[9] + ti[10]
let lcb0: Double = gi0 > 0.0 ? loudnessDBDecadeFactor * Foundation.log10(gi0) : 0.0
let lcb1: Double = gi1 > 0.0 ? loudnessDBDecadeFactor * Foundation.log10(gi1) : 0.0
let lcb2: Double = gi2 > 0.0 ? loudnessDBDecadeFactor * Foundation.log10(gi2) : 0.0
return (lcb0, lcb1, lcb2)
}
// MARK: - Band binning
/// Fill `bandLevel` (dB SPL) from the spectral buffer's bin magnitudes.
private func updateBandLevels(_ spectral: SpectralBuffer) {
for j: Int in 0..<loudnessISOThirdOctaveCount {
bandPower[j] = 0.0
}
let n: Int = min(binCount, spectral.binCount)
for k: Int in 0..<n {
let band: Int = binBand[k]
if band < 0 { continue }
let mag: Double = Double(spectral.magnitude(at: k))
bandPower[band] += mag * mag
}
for j: Int in 0..<loudnessISOThirdOctaveCount {
bandLevel[j] = loudnessDBDecadeFactor
* Foundation.log10(bandPower[j] + loudnessTinyPower) + calibrationDB
if bandLevel[j] > loudnessMaxBandLevelDB { bandLevel[j] = loudnessMaxBandLevelDB }
}
}
// MARK: - Model dispatch
/// Total loudness in sones for `model` from the current spectral frame.
/// `blockSeconds` is the audio-block duration (for the temporal mask).
func loudness(
spectral: SpectralBuffer,
model: LoudnessModel,
blockSeconds: Double
) -> Double {
updateBandLevels(spectral)
switch model {
case .barkEstimate:
return barkEstimateLoudness()
case .realtimeZwicker(let smask, let tmask):
return realtimeZwickerLoudness(smask: smask, tmask: tmask, blockSeconds: blockSeconds)
case .iso532b(let field):
return iso532bLoudness(field: field)
}
}
// MARK: - Model 1: Bark/third-octave Stevens estimate
private func barkEstimateLoudness() -> Double {
var total: Double = 0.0
let calibrationFactor: Double = Foundation.pow(
loudnessDBDecadeFactor, calibrationDB / loudnessDBDecadeFactor)
for j: Int in 0..<loudnessISOThirdOctaveCount {
let intensity: Double = bandPower[j]
if intensity <= 0.0 { continue }
// Calibrated intensity ratio → Stevens power law.
let ratio: Double = intensity * calibrationFactor
total += Foundation.pow(ratio, loudnessStevensExponent)
}
let result: Double = total * loudnessBarkEstimateScale
return result.isFinite ? max(0.0, result) : 0.0
}
// MARK: - Model 2: real-time Zwicker (critical-band specific loudness + temporal mask)
private func realtimeZwickerLoudness(
smask: Double,
tmask: Double,
blockSeconds: Double
) -> Double {
// Simplified core loudness: the same critical-band levels as ISO 532 B
// (low bands combined into LCB, but without the RAP/DLL/DCB/korry
// refinement), with the spectral-masking constant exposed as `smask`.
// Then the shared upper-slope integration, followed by the temporal mask.
let s: Double = min(1.0, max(0.0, smask))
fillCriticalLevels(lowFreqCorrected: false, field: .free)
for z: Int in 0..<loudnessCriticalBandCount {
let le: Double = critLevel[z]
let ltq: Double = loudnessISOLTQ[z]
if le > ltq {
let mp1: Double = loudnessZwickerConst
* Foundation.pow(loudnessDBDecadeFactor, loudnessZwickerThresholdCoeff * ltq)
let inner: Double = 1.0 - s
+ s * Foundation.pow(loudnessDBDecadeFactor, loudnessLevelToPowerCoeff * (le - ltq))
let mp2: Double = Foundation.pow(inner, loudnessZwickerExponent) - 1.0
coreLoudness[z] = max(0.0, mp1 * mp2)
} else {
coreLoudness[z] = 0.0
}
}
coreLoudness[loudnessCriticalBandCount] = 0.0
let base: Double = integrateUpperSlopes()
// Temporal mask: instant attack, exponential release toward 0.
let safeTMask: Double = max(loudnessTinyPower, tmask)
let coeff: Double = Foundation.exp(-max(0.0, blockSeconds) / safeTMask)
let released: Double = tmaskState * coeff
let out: Double = max(base, released)
tmaskState = denormalsToZero(out)
return out.isFinite ? max(0.0, out) : 0.0
}
// MARK: - Model 3: ISO 532 B / DIN 45631 stationary Zwicker
private func iso532bLoudness(field: LoudnessField) -> Double {
computeCoreLoudness(field: field)
return integrateUpperSlopes()
}
/// Fill `coreLoudness[0..20]` (main loudness per critical band) per DIN 45631.
private func computeCoreLoudness(field: LoudnessField) {
// Ear-corrected critical-band levels with the RAP/DLL low-frequency
// correction (the full standard).
fillCriticalLevels(lowFreqCorrected: true, field: field)
for z: Int in 0..<loudnessCriticalBandCount {
var le: Double = critLevel[z]
let ltq: Double = loudnessISOLTQ[z]
if le > ltq { le -= loudnessISODCB[z] }
if le > ltq {
let mp1: Double = loudnessZwickerConst
* Foundation.pow(loudnessDBDecadeFactor, loudnessZwickerThresholdCoeff * ltq)
let inner: Double = 1.0 - loudnessISOCoreS
+ loudnessISOCoreS * Foundation.pow(
loudnessDBDecadeFactor, loudnessLevelToPowerCoeff * (le - ltq))
let mp2: Double = Foundation.pow(inner, loudnessZwickerExponent) - 1.0
coreLoudness[z] = max(0.0, mp1 * mp2)
} else {
coreLoudness[z] = 0.0
}
}
coreLoudness[loudnessCriticalBandCount] = 0.0 // appended sentinel band
// Lowest-band threshold-dependence correction.
let korry: Double = loudnessKorryBase
+ loudnessKorryScale * Foundation.pow(coreLoudness[0], loudnessKorryExponent)
if korry <= 1.0 { coreLoudness[0] *= korry }
}
/// Integrate the specific-loudness function with the Zwicker upper slopes →
/// total loudness (sones). Walks each critical band's flat top plus the
/// upper-slope tail spilling into higher bands.
private func integrateUpperSlopes() -> Double {
var total: Double = 0.0
var z1: Double = 0.0
var n1: Double = 0.0
let maxColumn: Int = loudnessISOUSL[0].count - 1 // USL has 8 critical-band columns
for i: Int in 0..<(loudnessCriticalBandCount + 1) {
let zupI: Double = loudnessISOZUP[i]
var ig: Int = i - 1
if ig > maxColumn { ig = maxColumn }
if ig < 0 { ig = 0 }
let nmI: Double = coreLoudness[i]
while true {
if n1 <= nmI {
// Rising / flat: plateau at nmI across the band.
total += nmI * (zupI - z1)
z1 = zupI
n1 = nmI
break
}
// Decreasing: upper slope from (z1, n1) down through rns ranges.
var j: Int = 0
while j < (loudnessISORNS.count - 1) && loudnessISORNS[j] >= n1 { j += 1 }
let n2: Double = max(loudnessISORNS[j], nmI)
let slope: Double = loudnessISOUSL[j][ig]
let dz: Double = slope > 0.0 ? (n1 - n2) / slope : (zupI - z1)
var z2: Double = z1 + dz
if z2 >= zupI {
z2 = zupI
let nEdge: Double = n1 - slope * (z2 - z1)
total += loudnessTrapezoidalFactor * (n1 + nEdge) * (z2 - z1)
z1 = zupI
n1 = nEdge
break
}
total += loudnessTrapezoidalFactor * (n1 + n2) * (z2 - z1)
z1 = z2
n1 = n2
// Loop continues for the next rns range within the same band.
}
}
return total.isFinite ? max(0.0, total) : 0.0
}
}