diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b2d20c..b8c503f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ All notable changes to this package are documented here. The format follows - Mark SFX clips cut short by voice stealing with a red edge in the Mix Monitor ([#133](https://github.com/Ambiguous-Interactive/DxAudio/issues/133)). - Show live stereo sample peaks with peak hold for the listener bus in the Mix Monitor ([#133](https://github.com/Ambiguous-Interactive/DxAudio/issues/133)). - Show estimated master true peaks in dBTP in the Mix Monitor, including peaks between samples ([#133](https://github.com/Ambiguous-Interactive/DxAudio/issues/133)). +- Show short-term and integrated master loudness in LUFS on the Mix Monitor listener bus ([#133](https://github.com/Ambiguous-Interactive/DxAudio/issues/133)). - Add DxAudio Problems with named validation rules, project severities, and shared or personal silences ([#135](https://github.com/Ambiguous-Interactive/DxAudio/issues/135)). - Add a Stereo Width effect for DSP chains and graphs to narrow or widen stereo signals ([#27](https://github.com/Ambiguous-Interactive/DxAudio/issues/27)). - Add a room Reverb effect for DSP chains and graphs with adjustable decay and wet level ([#27](https://github.com/Ambiguous-Interactive/DxAudio/issues/27)). diff --git a/Editor/DxAudioMixMonitorWindow.cs b/Editor/DxAudioMixMonitorWindow.cs index 2fdbbc5..eb00795 100644 --- a/Editor/DxAudioMixMonitorWindow.cs +++ b/Editor/DxAudioMixMonitorWindow.cs @@ -121,6 +121,16 @@ private static void DrawWaveform(in Rect rect, float[] peaks, float start, float } } + private static string FormatLoudness(double? lufs) + { + if (!lufs.HasValue) + { + return "-"; + } + + return double.IsNegativeInfinity(lufs.Value) ? "-\u221e" : lufs.Value.ToString("0.0"); + } + public void CreateGUI() { DxAudioEditorTheme.Apply(rootVisualElement); @@ -434,6 +444,8 @@ private void DrawMaster() reading = (20f * Mathf.Log10(truePeak.Value)).ToString("0.0"); } EditorGUILayout.LabelField("True peak (dBTP)", reading); + EditorGUILayout.LabelField("Short-term (LUFS)", FormatLoudness(_masterMeter.ShortTermLufs)); + EditorGUILayout.LabelField("Integrated (LUFS)", FormatLoudness(_masterMeter.IntegratedLufs)); } private void DrawMasterChannel(string label, MixMonitorMasterMeter.Channel channel) diff --git a/Editor/MixMonitorMasterMeter.cs b/Editor/MixMonitorMasterMeter.cs index 39b804d..9b34d88 100644 --- a/Editor/MixMonitorMasterMeter.cs +++ b/Editor/MixMonitorMasterMeter.cs @@ -9,11 +9,14 @@ internal sealed class MixMonitorMasterMeter internal Channel Left => _left; internal Channel Right => _right; + internal double? ShortTermLufs => HasSignal ? _loudness.ShortTerm : null; + internal double? IntegratedLufs => _loudness.Integrated; internal float? TruePeak { get; private set; } internal bool TruePeakOverrun { get; private set; } internal bool IsAttached => _tap != null; internal bool HasSignal { get; private set; } + private readonly MasterLoudness _loudness = new(); private AudioMixBus _bus; private StereoPeakTap _tap; private Channel _left; @@ -49,17 +52,28 @@ internal void Sample(AudioMixBus bus, double now) _bus = bus; } - bool received = _tap.TryRead(out float left, out float right); + ReadCapturedAudio(_tap, now); + } + + internal void ReadCapturedAudio(StereoPeakTap tap, double now) + { + bool received = tap.TryRead(out float left, out float right); if (received) { _lastSignalTime = now; } - HasSignal = received || (HasSignal && now < _lastSignalTime + SignalTimeoutSeconds); + bool hasSignal = received || (HasSignal && now < _lastSignalTime + SignalTimeoutSeconds); + if (HasSignal && !hasSignal) + { + _loudness.Reset(); + } + + HasSignal = hasSignal; _left.Sample(received ? left : null, HasSignal, now); _right.Sample(received ? right : null, HasSignal, now); - bool receivedTruePeak = _tap.TryReadTruePeak(out float peak, out bool overrun); + bool receivedTruePeak = tap.TryReadTruePeak(out float peak, out bool overrun, _loudness); if (overrun) { TruePeakOverrun = true; @@ -89,6 +103,7 @@ internal void Clear() _left = default; _right = default; _truePeak = default; + _loudness.Reset(); TruePeak = null; TruePeakOverrun = false; } diff --git a/Runtime/Core/TruePeakTap.cs b/Runtime/Core/ListenerMeterTap.cs similarity index 62% rename from Runtime/Core/TruePeakTap.cs rename to Runtime/Core/ListenerMeterTap.cs index 9514ff2..042dce3 100644 --- a/Runtime/Core/TruePeakTap.cs +++ b/Runtime/Core/ListenerMeterTap.cs @@ -3,40 +3,50 @@ namespace WallstopStudios.DxAudio using System; using System.Threading; - /// Moves listener blocks from the audio callback to the editor's true-peak filter. - internal sealed class TruePeakTap + /// Moves listener blocks from the audio callback to the editor meters. + internal sealed class ListenerMeterTap { // Over 300 ms at 48 kHz and eight channels, with a normal read every 50 ms. private const int Capacity = 1 << 17; private const int Mask = Capacity - 1; - private const int HeaderSize = 2; + private const int HeaderSize = 3; private readonly float[] _queue = new float[Capacity]; private readonly TruePeakFilter _filter = new(); + private long _format; private int _writing; private int _written; private int _read; + private int _readRevision; private int _reset; private int _overrun; private bool _gap; - internal void RequestReset() + internal ListenerMeterTap(int sampleRate) { - Volatile.Write(ref _reset, 1); + _format = sampleRate; + } + + internal void SetSampleRate(int sampleRate) + { + // Publish the rate and its revision together, including resets at the same rate. + int revision = unchecked((int)(Volatile.Read(ref _format) >> 32) + 1); + Volatile.Write(ref _format, ((long)revision << 32) | (uint)sampleRate); } internal void Enqueue(float[] samples, int channels) { + int revision = (int)(Volatile.Read(ref _format) >> 32); // ProcessBuffer can also be driven explicitly while Unity is delivering audio. if (Interlocked.CompareExchange(ref _writing, 1, 0) != 0) { - RequestReset(); + Volatile.Write(ref _reset, 1); Volatile.Write(ref _overrun, 1); return; } try { - WriteBlock(samples, channels); + WriteBlock(samples, channels, revision); } finally { @@ -44,11 +54,21 @@ internal void Enqueue(float[] samples, int channels) } } - internal bool TryRead(out float peak, out bool overrun) + internal bool TryRead(out float peak, out bool overrun, MasterLoudness loudness) { int end = Volatile.Read(ref _written); + long format = Volatile.Read(ref _format); + int revision = (int)(format >> 32); + int sampleRate = unchecked((int)format); + if (_readRevision != revision) + { + _filter.Reset(); + loudness?.Reset(); + _readRevision = revision; + } + int read = _read; - bool received = read != end; + bool received = false; float maximum = 0f; while (read != end) { @@ -60,20 +80,28 @@ internal bool TryRead(out float peak, out bool overrun) continue; } - if (channels < 0) + int count = (int)_queue[start + 1]; + if (revision == BitConverter.SingleToInt32Bits(_queue[start + 2])) { - _filter.Reset(); - channels = -channels; + if (channels < 0) + { + _filter.Reset(); + loudness?.Reset(); + channels = -channels; + } + + maximum = Math.Max(maximum, _filter.Observe(_queue, start + HeaderSize, count, channels)); + loudness?.Observe(_queue, start + HeaderSize, count, channels, sampleRate); + received = true; } - int count = (int)_queue[start + 1]; - maximum = Math.Max(maximum, _filter.Observe(_queue, start + HeaderSize, count, channels)); read = unchecked(read + HeaderSize + count); Volatile.Write(ref _read, read); } if (Interlocked.Exchange(ref _overrun, 0) == 1) { + loudness?.Reset(); peak = 0f; overrun = true; return false; @@ -84,11 +112,12 @@ internal bool TryRead(out float peak, out bool overrun) return received; } - private void WriteBlock(float[] samples, int channels) + private void WriteBlock(float[] samples, int channels, int revision) { if (TruePeakFilter.MaxChannels < channels) { _gap = true; + Volatile.Write(ref _overrun, 1); return; } @@ -117,6 +146,7 @@ private void WriteBlock(float[] samples, int channels) _gap = false; _queue[start] = reset ? -channels : channels; _queue[start + 1] = count; + _queue[start + 2] = BitConverter.Int32BitsToSingle(revision); Array.Copy(samples, 0, _queue, start + HeaderSize, count); Volatile.Write(ref _written, unchecked(written + padding + HeaderSize + count)); } diff --git a/Runtime/Core/TruePeakTap.cs.meta b/Runtime/Core/ListenerMeterTap.cs.meta similarity index 100% rename from Runtime/Core/TruePeakTap.cs.meta rename to Runtime/Core/ListenerMeterTap.cs.meta diff --git a/Runtime/Core/LoudnessGate.cs b/Runtime/Core/LoudnessGate.cs new file mode 100644 index 0000000..f41dfdc --- /dev/null +++ b/Runtime/Core/LoudnessGate.cs @@ -0,0 +1,184 @@ +namespace WallstopStudios.DxAudio +{ + using System; + + /// Keeps exact block energies and reads the relative gate in logarithmic time. + internal sealed class LoudnessGate + { + private readonly double _absoluteThreshold; + + // Index zero is the empty subtree. Nodes share storage and grow in batches. + private Node[] _nodes = new Node[256]; + private int _used; + private int _root; + + internal LoudnessGate(double absoluteThreshold) + { + _absoluteThreshold = absoluteThreshold; + } + + internal void Add(double energy) + { + if (!(_absoluteThreshold < energy)) + { + return; + } + + int capacity = _nodes.Length; + if (_used == capacity - 1) + { + Array.Resize(ref _nodes, 2 * capacity); + } + + _root = Insert(_root, energy); + } + + internal double? Mean() + { + if (_root == 0) + { + return null; + } + + ref Node root = ref _nodes[_root]; + double threshold = Math.Max(_absoluteThreshold, 0.1d * (root.Sum / root.Count)); + double sum = 0d; + int count = 0; + int index = _root; + while (index != 0) + { + ref Node node = ref _nodes[index]; + if (threshold < node.Energy) + { + // The whole right subtree passes when this energy passes. + ref Node right = ref _nodes[node.Right]; + sum += node.Energy * node.Occurrences + right.Sum; + count += node.Occurrences + right.Count; + index = node.Left; + } + else + { + index = node.Right; + } + } + + return sum / count; + } + + internal void Clear() + { + _used = 0; + _root = 0; + } + + // An AVL tree puts a bound on both sorted input and sustained playback. + private int Insert(int index, double energy) + { + if (index == 0) + { + ++_used; + _nodes[_used] = new Node(energy); + return _used; + } + + // Add reserves space before recursing, so the node array stays in place. + ref Node node = ref _nodes[index]; + if (energy < node.Energy) + { + node.Left = Insert(node.Left, energy); + } + else if (node.Energy < energy) + { + node.Right = Insert(node.Right, energy); + } + else + { + ++node.Occurrences; + } + + Update(ref node); + int balance = Balance(in node); + if (1 < balance) + { + if (Balance(in _nodes[node.Left]) < 0) + { + node.Left = RotateLeft(node.Left); + } + + return RotateRight(index); + } + + if (balance < -1) + { + if (0 < Balance(in _nodes[node.Right])) + { + node.Right = RotateRight(node.Right); + } + + return RotateLeft(index); + } + + return index; + } + + private int Balance(in Node node) + { + return _nodes[node.Left].Height - _nodes[node.Right].Height; + } + + private int RotateLeft(int index) + { + ref Node node = ref _nodes[index]; + int parent = node.Right; + ref Node right = ref _nodes[parent]; + node.Right = right.Left; + right.Left = index; + Update(ref node); + Update(ref right); + return parent; + } + + private int RotateRight(int index) + { + ref Node node = ref _nodes[index]; + int parent = node.Left; + ref Node left = ref _nodes[parent]; + node.Left = left.Right; + left.Right = index; + Update(ref node); + Update(ref left); + return parent; + } + + private void Update(ref Node node) + { + ref Node left = ref _nodes[node.Left]; + ref Node right = ref _nodes[node.Right]; + node.Count = node.Occurrences + left.Count + right.Count; + node.Sum = node.Energy * node.Occurrences + left.Sum + right.Sum; + node.Height = 1 + Math.Max(left.Height, right.Height); + } + + private struct Node + { + internal readonly double Energy; + internal double Sum; + internal int Left; + internal int Right; + internal int Occurrences; + internal int Count; + internal int Height; + + internal Node(double energy) + { + Energy = energy; + Sum = energy; + Left = 0; + Right = 0; + Occurrences = 1; + Count = 1; + Height = 1; + } + } + } +} diff --git a/Runtime/Core/LoudnessGate.cs.meta b/Runtime/Core/LoudnessGate.cs.meta new file mode 100644 index 0000000..5d516f4 --- /dev/null +++ b/Runtime/Core/LoudnessGate.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 80d889ab160c4b56bc3ff21ae097bc75 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Core/MasterLoudness.cs b/Runtime/Core/MasterLoudness.cs new file mode 100644 index 0000000..997c595 --- /dev/null +++ b/Runtime/Core/MasterLoudness.cs @@ -0,0 +1,232 @@ +namespace WallstopStudios.DxAudio +{ + using System; + + /// Measures BS.1770 integrated and EBU short-term loudness on the editor thread. + internal sealed class MasterLoudness + { + private const double Calibration = -0.691d; + private const int GateHops = 4; + private const int ShortTermHops = 30; + private const double SurroundWeight = 1.41d; + private static readonly double AbsoluteGate = Math.Pow(10d, (-70d - Calibration) / 10d); + + /* + Unity's listener channel order. BS.1770 Annex 1 weights quad and 5.x surrounds. + Annex 3 weights 7.1 sides, with unity weighting for the rear pair. + */ + private static readonly double[] Mono = { 1d }; + private static readonly double[] Stereo = { 1d, 1d }; + private static readonly double[] Quad = { 1d, 1d, SurroundWeight, SurroundWeight }; + private static readonly double[] Surround = { 1d, 1d, 1d, SurroundWeight, SurroundWeight }; + private static readonly double[] Surround51 = { 1d, 1d, 1d, 0d, SurroundWeight, SurroundWeight }; + private static readonly double[] Surround71 = { 1d, 1d, 1d, 0d, SurroundWeight, SurroundWeight, 1d, 1d }; + + internal double? ShortTerm => _filledHops == ShortTermHops ? ToLufs(MeanOfLatest(ShortTermHops)) : null; + + internal double? Integrated + { + get + { + double? energy = _gate.Mean(); + return energy.HasValue ? ToLufs(energy.Value) : null; + } + } + + private readonly FilterState[] _shelfState = new FilterState[TruePeakFilter.MaxChannels]; + private readonly FilterState[] _highPassState = new FilterState[TruePeakFilter.MaxChannels]; + private readonly double[] _hops = new double[ShortTermHops]; + + private readonly LoudnessGate _gate = new(AbsoluteGate); + private double[] _weights; + private Biquad _shelf; + private Biquad _highPass; + private int _sampleRate; + private int _channels; + private int _hopFrames; + private int _frames; + private double _energy; + private int _nextHop; + private int _filledHops; + + private static double ToLufs(double energy) + { + return Calibration + 10d * Math.Log10(energy); + } + + internal void Observe(float[] samples, int offset, int count, int channels, int sampleRate) + { + if (_sampleRate != sampleRate || _channels != channels) + { + Configure(channels, sampleRate); + } + + if (_weights == null) + { + return; + } + + int end = offset + count - count % channels; + for (int start = offset; start < end; ) + { + int frames = Math.Min((end - start) / channels, _hopFrames - _frames); + int stop = start + frames * channels; + _energy += MeasureEnergy(samples, start, stop, channels); + _frames += frames; + if (_frames == _hopFrames) + { + CompleteHop(); + } + + start = stop; + } + } + + internal void Reset() + { + Array.Clear(_shelfState, 0, _shelfState.Length); + Array.Clear(_highPassState, 0, _highPassState.Length); + _frames = 0; + _energy = 0d; + _nextHop = 0; + _filledHops = 0; + _gate.Clear(); + } + + private void Configure(int channels, int sampleRate) + { + Reset(); + _sampleRate = sampleRate; + _channels = channels; + _weights = + 4_000 <= sampleRate + ? channels switch + { + 1 => Mono, + 2 => Stereo, + 4 => Quad, + 5 => Surround, + 6 => Surround51, + 8 => Surround71, + _ => null, + } + : null; + + if (_weights != null) + { + _hopFrames = (int)Math.Round(sampleRate / 10d, MidpointRounding.AwayFromZero); + /* + Bilinear design reproduces the BS.1770 Annex 1 tables at 48 kHz. + See FFmpeg's libavfilter/f_ebur128.c for the filter parameters. + */ + double k = Math.Tan(Math.PI * 1681.974450955533d / sampleRate); + double kOverQ = k / 0.7071752369554196d; + double kSquared = k * k; + double normal = 1d + kOverQ + kSquared; + double high = Math.Pow(10d, 3.999843853973347d / 20d); + double mid = Math.Pow(high, 0.4996667741545416d) * kOverQ; + _shelf = new Biquad( + (high + mid + kSquared) / normal, + 2d * (kSquared - high) / normal, + (high - mid + kSquared) / normal, + 2d * (kSquared - 1d) / normal, + (1d - kOverQ + kSquared) / normal + ); + + k = Math.Tan(Math.PI * 38.13547087602444d / sampleRate); + kOverQ = k / 0.5003270373238773d; + kSquared = k * k; + normal = 1d + kOverQ + kSquared; + _highPass = new Biquad(1d, -2d, 1d, 2d * (kSquared - 1d) / normal, (1d - kOverQ + kSquared) / normal); + } + } + + private double MeasureEnergy(float[] samples, int start, int stop, int channels) + { + double energy = 0d; + for (int channel = 0; channel < channels; ++channel) + { + double weight = _weights[channel]; + if (weight == 0d) + { + continue; + } + + FilterState shelf = _shelfState[channel]; + FilterState highPass = _highPassState[channel]; + double channelEnergy = 0d; + for (int index = start + channel; index < stop; index += channels) + { + float sample = samples[index]; + double weighted = _shelf.Process(Math.Abs(sample) <= float.MaxValue ? sample : 0d, ref shelf); + weighted = _highPass.Process(weighted, ref highPass); + channelEnergy += weighted * weighted; + } + + _shelfState[channel] = shelf; + _highPassState[channel] = highPass; + energy += weight * channelEnergy; + } + + return energy; + } + + private void CompleteHop() + { + _hops[_nextHop] = _energy / _hopFrames; + _nextHop = (_nextHop + 1) % ShortTermHops; + _filledHops = Math.Min(ShortTermHops, _filledHops + 1); + _energy = 0d; + _frames = 0; + if (GateHops <= _filledHops) + { + _gate.Add(MeanOfLatest(GateHops)); + } + } + + private double MeanOfLatest(int count) + { + double energy = 0d; + int index = _nextHop; + for (int hop = 0; hop < count; ++hop) + { + index = index == 0 ? ShortTermHops - 1 : index - 1; + energy += _hops[index]; + } + + return energy / count; + } + + private struct FilterState + { + internal double First; + internal double Second; + } + + private readonly struct Biquad + { + private readonly double _b0; + private readonly double _b1; + private readonly double _b2; + private readonly double _a1; + private readonly double _a2; + + internal Biquad(double b0, double b1, double b2, double a1, double a2) + { + _b0 = b0; + _b1 = b1; + _b2 = b2; + _a1 = a1; + _a2 = a2; + } + + internal double Process(double sample, ref FilterState state) + { + double output = _b0 * sample + state.First; + state.First = _b1 * sample - _a1 * output + state.Second; + state.Second = _b2 * sample - _a2 * output; + return output; + } + } + } +} diff --git a/Runtime/Core/MasterLoudness.cs.meta b/Runtime/Core/MasterLoudness.cs.meta new file mode 100644 index 0000000..4f63d98 --- /dev/null +++ b/Runtime/Core/MasterLoudness.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d3cb93d13e7a439c8f1b567a6faf90d9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Core/StereoPeakTap.cs b/Runtime/Core/StereoPeakTap.cs index 6f5bbf2..bc82f68 100644 --- a/Runtime/Core/StereoPeakTap.cs +++ b/Runtime/Core/StereoPeakTap.cs @@ -3,13 +3,18 @@ namespace WallstopStudios.DxAudio using System; using System.Threading; - /// Transfers the largest front-channel sample peaks since the last editor read. + /// Captures listener samples and front-channel peaks for the editor. internal sealed class StereoPeakTap { private const long UnreadEmpty = long.MinValue; - private readonly TruePeakTap _truePeak = new(); + private readonly ListenerMeterTap _listener; private long _pending = UnreadEmpty; + internal StereoPeakTap(int sampleRate) + { + _listener = new ListenerMeterTap(sampleRate); + } + private static long Pack(float left, float right) { return ((long)BitConverter.SingleToInt32Bits(left) << 32) | (uint)BitConverter.SingleToInt32Bits(right); @@ -25,9 +30,9 @@ private static float Right(long pair) return BitConverter.Int32BitsToSingle(unchecked((int)pair)); } - internal void RequestTruePeakReset() + internal void SetSampleRate(int sampleRate) { - _truePeak.RequestReset(); + _listener.SetSampleRate(sampleRate); } internal void Observe(float[] samples, int channels) @@ -37,7 +42,7 @@ internal void Observe(float[] samples, int channels) return; } - _truePeak.Enqueue(samples, channels); + _listener.Enqueue(samples, channels); float left = 0f; float right = 0f; @@ -80,9 +85,10 @@ internal void Observe(float[] samples, int channels) } } - internal bool TryReadTruePeak(out float peak, out bool overrun) + // The editor reads both meters in one drain of the listener samples. + internal bool TryReadTruePeak(out float peak, out bool overrun, MasterLoudness loudness = null) { - return _truePeak.TryRead(out peak, out overrun); + return _listener.TryRead(out peak, out overrun, loudness); } internal bool TryRead(out float left, out float right) diff --git a/Runtime/Players/AudioMixBus.cs b/Runtime/Players/AudioMixBus.cs index 71f89e9..135b74e 100644 --- a/Runtime/Players/AudioMixBus.cs +++ b/Runtime/Players/AudioMixBus.cs @@ -177,7 +177,12 @@ internal void OnAudioConfigurationChanged(bool deviceChanged) _slots.Clear(); Select(_chain); #if UNITY_EDITOR - _peakTap?.RequestTruePeakReset(); + StereoPeakTap tap = _peakTap; + if (tap != null) + { + _layout.Refresh(); + tap.SetSampleRate(_layout.SampleRate); + } #endif } @@ -191,7 +196,8 @@ internal bool TryAttachPeakTap(out StereoPeakTap tap) return false; } - StereoPeakTap attached = new(); + _layout.Refresh(); + StereoPeakTap attached = new(_layout.SampleRate); _peakTap = attached; tap = attached; return true; diff --git a/Tests/Editor/Core/MasterLoudnessTests.cs b/Tests/Editor/Core/MasterLoudnessTests.cs new file mode 100644 index 0000000..4aee4d7 --- /dev/null +++ b/Tests/Editor/Core/MasterLoudnessTests.cs @@ -0,0 +1,249 @@ +namespace WallstopStudios.DxAudio.Tests.Editor +{ + using System; + using NUnit.Framework; + + public sealed class MasterLoudnessTests + { + private static void FeedTone(MasterLoudness meter, int rate, double seconds, double frequency, params double[] levels) + { + int channels = levels.Length; + float[] buffer = new float[509 * channels]; + double[] amplitudes = new double[channels]; + for (int channel = 0; channel < channels; ++channel) + { + amplitudes[channel] = Math.Pow(10d, levels[channel] / 20d); + } + + int frames = (int)Math.Round(seconds * rate); + for (int first = 0; first < frames; first += 509) + { + int count = Math.Min(509, frames - first); + for (int frame = 0; frame < count; ++frame) + { + double sample = Math.Sin((first + frame) * (2d * Math.PI * frequency / rate)); + for (int channel = 0; channel < channels; ++channel) + { + buffer[frame * channels + channel] = (float)(sample * amplitudes[channel]); + } + } + meter.Observe(buffer, 0, count * channels, channels, rate); + } + } + + [TestCase(44_100, -23d)] + [TestCase(48_000, -33d)] + [TestCase(96_000, -23d)] + public void StereoReferenceTonesMatchTheEbuLevels(int rate, double level) + { + MasterLoudness meter = new(); + FeedTone(meter, rate, 2.9, 1_000d, level, level); + Assert.That(meter.ShortTerm.HasValue, Is.False); + FeedTone(meter, rate, 0.1, 1_000d, level, level); + Assert.That(meter.ShortTerm, Is.EqualTo(level).Within(0.1)); + Assert.That(meter.Integrated, Is.EqualTo(level).Within(0.1)); + } + + [TestCase(100d, -24.8245d)] + [TestCase(8_000d, -19.6516d)] + public void TheKWeightingMatchesTheItuFilterResponse(double frequency, double expected) + { + // The expected levels come from evaluating Annex 1 Tables 1 and 2 at 48 kHz. + MasterLoudness meter = new(); + FeedTone(meter, 48_000, 3d, frequency, -23d, -23d); + Assert.That(meter.ShortTerm, Is.EqualTo(expected).Within(0.1)); + } + + [Test] + public void TheIntegratedReadingAppliesBothGates() + { + const int Rate = 48_000; + MasterLoudness meter = new(); + FeedTone(meter, Rate, 10d, 1_000d, -72d, -72d); + Assert.That(meter.Integrated.HasValue, Is.False); + FeedTone(meter, Rate, 10d, 1_000d, -36d, -36d); + Assert.That(meter.Integrated, Is.EqualTo(-36d).Within(0.1)); + FeedTone(meter, Rate, 60d, 1_000d, -23d, -23d); + FeedTone(meter, Rate, 10d, 1_000d, -36d, -36d); + FeedTone(meter, Rate, 10d, 1_000d, -72d, -72d); + Assert.That(meter.Integrated, Is.EqualTo(-23d).Within(0.1)); + Assert.That(meter.ShortTerm, Is.EqualTo(-72d).Within(0.1)); + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(2)] + public void TheOrderedGateMatchesAFullScanAcrossInsertionOrders(int order) + { + const double AbsoluteGate = 0.25d; + LoudnessGate gate = new(AbsoluteGate); + double[] blocks = new double[1_024]; + for (int index = 0; index < 1_024; ++index) + { + int rank = order switch + { + 0 => index, + 1 => 1_023 - index, + _ => index * 137 % 1_024, + }; + double block = Math.Pow(1.06d, rank / 2) * 0.01d; + blocks[index] = block; + gate.Add(block); + + double absoluteSum = 0d; + int absoluteCount = 0; + for (int prior = 0; prior <= index; ++prior) + { + if (AbsoluteGate < blocks[prior]) + { + absoluteSum += blocks[prior]; + ++absoluteCount; + } + } + + double threshold = Math.Max(AbsoluteGate, 0.1d * (absoluteSum / absoluteCount)); + double relativeSum = 0d; + int relativeCount = 0; + for (int prior = 0; prior <= index; ++prior) + { + if (threshold < blocks[prior]) + { + relativeSum += blocks[prior]; + ++relativeCount; + } + } + + double? reading = gate.Mean(); + if (relativeCount == 0) + { + Assert.That(reading.HasValue, Is.False); + } + else + { + double expected = relativeSum / relativeCount; + Assert.That(reading, Is.EqualTo(expected).Within(1e-12d * expected)); + } + } + + gate.Clear(); + gate.Add(AbsoluteGate); + Assert.That(gate.Mean().HasValue, Is.False); + gate.Add(1d); + gate.Add(2d); + Assert.That(gate.Mean(), Is.EqualTo(1.5d)); + } + + [Test] + public void ShortTermRollsOverTheLastThreeSecondsWithoutGating() + { + const int Rate = 48_000; + MasterLoudness meter = new(); + for (int repeat = 0; repeat < 5; ++repeat) + { + FeedTone(meter, Rate, 1.34, 1_000d, -20d, -20d); + FeedTone(meter, Rate, 1.66, 1_000d, -30d, -30d); + Assert.That(meter.ShortTerm, Is.EqualTo(-23d).Within(0.1)); + } + } + + [TestCase(5)] + [TestCase(6)] + public void SurroundWeightsTheRearPairAndExcludesTheSubwoofer(int channels) + { + MasterLoudness meter = new(); + double[] levels = channels == 5 ? new[] { -28d, -28d, -24d, -30d, -30d } : new[] { -28d, -28d, -24d, 0d, -30d, -30d }; + FeedTone(meter, 48_000, 3d, 1_000d, levels); + Assert.That(meter.ShortTerm, Is.EqualTo(-23d).Within(0.1)); + Assert.That(meter.Integrated, Is.EqualTo(-23d).Within(0.1)); + } + + [TestCase(4, -21.51d)] + [TestCase(6, -23.00d)] + public void SevenPointOneWeightsSideAndRearSpeakersByPosition(int activeChannel, double expected) + { + MasterLoudness meter = new(); + double[] levels = new double[8]; + Array.Fill(levels, double.NegativeInfinity); + levels[activeChannel] = -20d; + FeedTone(meter, 48_000, 0.4, 1_000d, levels); + Assert.That(meter.Integrated, Is.EqualTo(expected).Within(0.1)); + } + + [Test] + public void ANewRateOrChannelLayoutStartsNewWindows() + { + MasterLoudness meter = new(); + FeedTone(meter, 48_000, 3d, 1_000d, -23d, -23d); + FeedTone(meter, 44_100, 0.399, 1_000d, -30d, -30d); + Assert.That(meter.ShortTerm.HasValue, Is.False); + Assert.That(meter.Integrated.HasValue, Is.False); + FeedTone(meter, 44_100, 0.4, 1_000d, -33d); + Assert.That(meter.Integrated, Is.EqualTo(-36d).Within(0.1)); + } + + [TestCase(false)] + [TestCase(true)] + public void AGapClearsLoudnessAndAQueuedDeviceChangeUsesItsOwnRate(bool readBeforeNewAudio) + { + StereoPeakTap tap = new(48_000); + MasterLoudness meter = new(); + float[] oldTone = new float[480 * 2]; + float[] newTone = new float[441 * 2]; + for (int frame = 0; frame < 480; ++frame) + { + float sample = (float)(0.1 * Math.Sin(2d * Math.PI * frame / 48d)); + oldTone[2 * frame] = sample; + oldTone[2 * frame + 1] = sample; + if (frame < 441) + { + sample = (float)(0.1 * Math.Sin(20d * Math.PI * frame / 441d)); + newTone[2 * frame] = sample; + newTone[2 * frame + 1] = sample; + } + } + + for (int tick = 0; tick < 4; ++tick) + { + for (int block = 0; block < 10; ++block) + { + tap.Observe(oldTone, 2); + } + + Assert.That(tap.TryReadTruePeak(out _, out _, meter), Is.True); + } + Assert.That(meter.Integrated, Is.EqualTo(-20d).Within(0.1)); + + tap.Observe(oldTone, 2); + tap.SetSampleRate(44_100); + if (readBeforeNewAudio) + { + Assert.That(tap.TryReadTruePeak(out _, out bool deviceOverrun, meter), Is.False); + Assert.That(deviceOverrun, Is.False); + Assert.That(meter.Integrated.HasValue, Is.False); + } + + for (int block = 0; block < 40; ++block) + { + tap.Observe(newTone, 2); + } + Assert.That(tap.TryReadTruePeak(out _, out _, meter), Is.True); + Assert.That(meter.Integrated, Is.EqualTo(-20d).Within(0.1)); + + for (int block = 0; block < 200; ++block) + { + tap.Observe(newTone, 2); + } + Assert.That(tap.TryReadTruePeak(out _, out bool overrun, meter), Is.False); + Assert.That(overrun, Is.True); + Assert.That(meter.Integrated.HasValue, Is.False); + + for (int block = 0; block < 40; ++block) + { + tap.Observe(newTone, 2); + } + Assert.That(tap.TryReadTruePeak(out _, out overrun, meter), Is.True); + Assert.That(overrun, Is.False); + Assert.That(meter.Integrated, Is.EqualTo(-20d).Within(0.1)); + } + } +} diff --git a/Tests/Editor/Core/MasterLoudnessTests.cs.meta b/Tests/Editor/Core/MasterLoudnessTests.cs.meta new file mode 100644 index 0000000..7c4ce73 --- /dev/null +++ b/Tests/Editor/Core/MasterLoudnessTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3ff1e12903224c6296e8213513532e50 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Tests/Editor/Core/StereoPeakTapTests.cs b/Tests/Editor/Core/StereoPeakTapTests.cs index da6a14e..df54db8 100644 --- a/Tests/Editor/Core/StereoPeakTapTests.cs +++ b/Tests/Editor/Core/StereoPeakTapTests.cs @@ -5,12 +5,14 @@ namespace WallstopStudios.DxAudio.Tests.Editor public sealed class StereoPeakTapTests { + private const int SampleRate = 48_000; + [TestCase(1)] [TestCase(2)] [TestCase(8)] public void TruePeakFindsAnIntersampleCrestAcrossUnevenBlocks(int channels) { - StereoPeakTap tap = new(); + StereoPeakTap tap = new(SampleRate); float[] cycle = { 0.75f, 0.75f, -0.75f, -0.75f }; float[] first = new float[7 * channels]; float[] second = new float[57 * channels]; @@ -34,8 +36,8 @@ public void TruePeakFindsAnIntersampleCrestAcrossUnevenBlocks(int channels) [Test] public void SingleFrameCallbacksGiveTheSameTruePeakAsAContiguousBlock() { - StereoPeakTap whole = new(); - StereoPeakTap split = new(); + StereoPeakTap whole = new(SampleRate); + StereoPeakTap split = new(SampleRate); float[] signal = { 0f, 0f, 0.75f, 0.75f, -0.75f, -0.75f, 0f, 0f, 0f, 0f, 0f, 0f }; whole.Observe(signal, 1); foreach (float sample in signal) @@ -53,13 +55,13 @@ public void SingleFrameCallbacksGiveTheSameTruePeakAsAContiguousBlock() [TestCase(2, true)] public void TruePeakClearsFilterHistoryOnLayoutOrDeviceChanges(int nextChannels, bool configurationChanged) { - StereoPeakTap tap = new(); - StereoPeakTap fresh = new(); + StereoPeakTap tap = new(SampleRate); + StereoPeakTap fresh = new(SampleRate); tap.Observe(new[] { 1f, 1f, -1f, -1f }, 2); Assert.That(tap.TryReadTruePeak(out _, out _), Is.True); if (configurationChanged) { - tap.RequestTruePeakReset(); + tap.SetSampleRate(SampleRate); } float[] silence = new float[24]; @@ -74,7 +76,7 @@ public void TruePeakClearsFilterHistoryOnLayoutOrDeviceChanges(int nextChannels, [Test] public void AFullTruePeakQueueReportsAGapAndRestartsTheFilter() { - StereoPeakTap tap = new(); + StereoPeakTap tap = new(SampleRate); float[] block = new float[4096]; block[block.Length - 1] = 1f; for (int index = 0; index < 33; ++index) @@ -98,7 +100,7 @@ public void AFullTruePeakQueueReportsAGapAndRestartsTheFilter() [Test] public void AReadKeepsEachChannelsLoudestSampleAcrossBlocks() { - StereoPeakTap tap = new(); + StereoPeakTap tap = new(SampleRate); tap.Observe(new[] { 0.05f, -0.2f, -1.25f, 0.3f }, 2); tap.Observe(new[] { 0.3f, -0.8f }, 2); @@ -117,7 +119,7 @@ public void AReadKeepsEachChannelsLoudestSampleAcrossBlocks() [TestCase(4, 0.5f, 0.25f)] public void ReadsMonoOrTheFrontTwoChannels(int channels, float expectedLeft, float expectedRight) { - StereoPeakTap tap = new(); + StereoPeakTap tap = new(SampleRate); float[] block = channels == 1 ? new[] { 0.1f, -0.5f } : new[] { 0.5f, 0f, 10f, 12f, 0.1f, -0.25f, 0f, 0f }; tap.Observe(block, channels); @@ -129,7 +131,7 @@ public void ReadsMonoOrTheFrontTwoChannels(int channels, float expectedLeft, flo [Test] public void IgnoresIncompleteFramesAndNonFiniteSamples() { - StereoPeakTap tap = new(); + StereoPeakTap tap = new(SampleRate); tap.Observe(new[] { 1f }, 2); tap.Observe(new[] { 1f }, 0); Assert.That(tap.TryRead(out _, out _), Is.False); diff --git a/Tests/Editor/Unity/AudioMixBusTests.cs b/Tests/Editor/Unity/AudioMixBusTests.cs index 5210cc6..7c61f04 100644 --- a/Tests/Editor/Unity/AudioMixBusTests.cs +++ b/Tests/Editor/Unity/AudioMixBusTests.cs @@ -164,6 +164,64 @@ public void TheMasterDisplaysPostChainTruePeakAndHoldsItThroughSilence() Assert.That(meter.TruePeak.HasValue, Is.False); } + [Test] + public void TheMasterReadsPostChainLoudnessAndClearsItAfterAStop() + { + using MadeObjects made = new(); + AudioMixBus bus = Bus(made, Chain(made, made.Track(DspLimiterAsset.Create(ceilingDecibels: -12f, lookaheadSeconds: 0f)))); + // Keep the native audio callback out of the synthetic capture. + bus.gameObject.SetActive(false); + _ = bus.gameObject.AddComponent(); + Assert.That(bus.TryAttachPeakTap(out StereoPeakTap tap), Is.True); + MixMonitorMasterMeter meter = new(); + meter.ReadCapturedAudio(tap, 0d); + Assert.That(meter.IntegratedLufs.HasValue, Is.False); + + MasterLoudness reference = new(); + int channels = bus.ChannelCount; + int rate = bus.PreparedSampleRate; + int frames = (int)Math.Round(rate / 10d, MidpointRounding.AwayFromZero) / 5; + int count = frames * channels; + float[] block = new float[count]; + for (int index = 0; index < 155; ++index) + { + Array.Clear(block, 0, count); + for (int frame = 0; frame < frames; ++frame) + { + block[frame * channels] = (float)(0.8d * Math.Sin(2d * Math.PI * 1_000d * (frames * index + frame) / rate)); + } + + bus.ProcessBuffer(block, channels); + reference.Observe(block, 0, count, channels, rate); + meter.ReadCapturedAudio(tap, (index + 1) * 0.02d); + } + + Assert.That(reference.ShortTerm, Is.LessThan(-12d)); + Assert.That(meter.ShortTermLufs, Is.EqualTo(reference.ShortTerm).Within(0.01)); + Assert.That(meter.IntegratedLufs, Is.EqualTo(reference.Integrated).Within(0.01)); + + meter.ReadCapturedAudio(tap, 3.5d); + Assert.That(meter.ShortTermLufs.HasValue, Is.False); + Assert.That(meter.IntegratedLufs.HasValue, Is.False); + + bus.ProcessBuffer(block, channels); + meter.ReadCapturedAudio(tap, 3.52d); + Assert.That(meter.HasSignal, Is.True); + Assert.That(meter.IntegratedLufs.HasValue, Is.False); + + for (int index = 1; index < 25; ++index) + { + bus.ProcessBuffer(block, channels); + meter.ReadCapturedAudio(tap, 3.52d + index * 0.02d); + } + Assert.That(meter.IntegratedLufs.HasValue, Is.True); + Assert.That(meter.ShortTermLufs.HasValue, Is.False); + + bus.DetachPeakTap(tap); + meter.Clear(); + Assert.That(meter.IntegratedLufs.HasValue, Is.False); + } + [Test] public void ATruePeakRemainsVisibleForOneSecondWithoutCallbacks() { @@ -290,7 +348,7 @@ public void AListenerPeakTapUsesLessThanOnePercentOfABlockDeadline(int channels) } } - long Measure(bool enabled) + (long Callback, long Drain) Measure(bool enabled, MasterLoudness loudness = null) { StereoPeakTap tap = null; if (enabled) @@ -298,7 +356,8 @@ long Measure(bool enabled) Assert.That(bus.TryAttachPeakTap(out tap), Is.True); } - long ticks = 0; + long callback = 0; + long drain = 0; for (int group = 0; group < BlocksPerBatch / BlocksPerRead; ++group) { long start = Stopwatch.GetTimestamp(); @@ -307,34 +366,60 @@ long Measure(bool enabled) bus.ProcessBuffer(block, channels); } - ticks += Stopwatch.GetTimestamp() - start; + callback += Stopwatch.GetTimestamp() - start; if (tap != null) { - Assert.That(tap.TryReadTruePeak(out _, out bool overrun), Is.True, "the callback must enqueue every measured block"); - Assert.That(overrun, Is.False); + start = Stopwatch.GetTimestamp(); + bool received = tap.TryReadTruePeak(out _, out bool overrun, loudness); tap.TryRead(out _, out _); + if (loudness != null) + { + _ = loudness.ShortTerm; + _ = loudness.Integrated; + } + drain += Stopwatch.GetTimestamp() - start; + Assert.That(received, Is.True, "the callback must enqueue every measured block"); + Assert.That(overrun, Is.False); } } bus.DetachPeakTap(tap); - return ticks; + return (callback, drain); } _ = Measure(false); _ = Measure(true); + _ = Measure(true, new MasterLoudness()); long[] addedTicks = new long[Batches]; + long[] addedDrain = new long[Batches]; for (int batch = 0; batch < Batches; ++batch) { - addedTicks[batch] = batch % 2 == 0 ? -Measure(false) + Measure(true) : Measure(true) - Measure(false); + bool baselineFirst = batch % 2 == 0; + (long Callback, long Drain) passThrough = baselineFirst ? Measure(false) : default; + (long Callback, long Drain) peaks = baselineFirst ? Measure(true) : default; + (long Callback, long Drain) full = Measure(true, new MasterLoudness()); + if (!baselineFirst) + { + peaks = Measure(true); + passThrough = Measure(false); + } + + addedTicks[batch] = full.Callback - passThrough.Callback; + addedDrain[batch] = full.Drain - peaks.Drain; } Array.Sort(addedTicks); + Array.Sort(addedDrain); double ticksToMicrosecondsPerBlock = 1_000_000d / Stopwatch.Frequency / BlocksPerBatch; double median = addedTicks[Batches / 2] * ticksToMicrosecondsPerBlock; - double p95 = addedTicks[(95 * Batches + 99) / 100 - 1] * ticksToMicrosecondsPerBlock; + int p95Index = (95 * Batches + 99) / 100 - 1; + double p95 = addedTicks[p95Index] * ticksToMicrosecondsPerBlock; + double drainMedian = addedDrain[Batches / 2] * ticksToMicrosecondsPerBlock * BlocksPerRead; + double drainP95 = addedDrain[p95Index] * ticksToMicrosecondsPerBlock * BlocksPerRead; double budget = Frames * 10_000d / SampleRate; - string report = $"Listener peak tap, {channels} channels: added p50 {median:F2} us, p95 {p95:F2} us, budget {budget:F2} us."; + string report = $"Listener meter tap, {channels} channels: added p50 {median:F2} us, p95 {p95:F2} us, budget {budget:F2} us."; TestContext.Out.WriteLine(report); + TestContext.Out.WriteLine($"Added loudness drain per {BlocksPerRead} blocks: p50 {drainMedian:F2} us, p95 {drainP95:F2} us."); Assert.That(median, Is.LessThan(budget), report); }