Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/p1-windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ jobs:
-DBUILD_TESTING=ON
-DJUCE_WEBVIEW2_PACKAGE_LOCATION="${{ github.workspace }}/.deps"
- name: Build executable and native RT tests
run: cmake --build build --config Release --target ARMixConsole ARMixFxOrderTests ARMixMixerRoutingTests ARMixChannelRoutingContractTests ARMixChannelSendTests ARMixPreparedMixerBlockTests ARMixLiveRoutingEpochTests ARMixJucePortMaskTests ARMixNativeMixerSessionTests ARMixNativeDrySendTests ARMixLiveChannelFxTests ARMixDedicatedAuxBusTests ARMixTenChannelLiveControlTests ARMixWorkspaceTests ARMixVaultTests ARMixBackupTests ARMixOrbitPhaseTests ARMixOrbitControlTests ARMixOrbitMotionTests ARMixOrbitDistanceTests ARMixFxBypassEnvelopeTests ARMixDearVrPolarPolicyTests ARMixRTTests ARMixPresetTests ARMixShowSchemaTests ARMixShowStoreTests ARMixLiveShowCaptureTests ARMixDiagnosticTests ARMixClockBridgeTests ARMixVirtualClockSoakTests ARMixCadenceTests ARMixCrackleWindowTests ARMixHealthTests ARMixPolicyTests ARMixPeriodEvidenceTests ARMixLifecycleTests ARMixWasapiProbeTests ARMixDualJuceTests ARMixClockSizingTests ARMixIndependentFormatTests ARMixRecoveryTests ARMixStreamWatchdogTests ARMixBridgeContinuityTests ARMixEndpointPolicyTests ARMixEndpointGuardTests ARMixAsioPolicyTests ARMixAsioBackendTests ARMixAsioRegistryIdentityTests ARMixDirectFenceTests --parallel 2
run: cmake --build build --config Release --target ARMixConsole ARMixFxOrderTests ARMixMixerRoutingTests ARMixChannelRoutingContractTests ARMixChannelSendTests ARMixPreparedMixerBlockTests ARMixLiveRoutingEpochTests ARMixJucePortMaskTests ARMixNativeMixerSessionTests ARMixNativeDrySendTests ARMixLiveChannelFxTests ARMixDedicatedAuxBusTests ARMixTenChannelLiveControlTests ARMixWorkspaceTests ARMixVaultTests ARMixBackupTests ARMixOrbitPhaseTests ARMixOrbitControlTests ARMixOrbitMotionTests ARMixOrbitDistanceTests ARMixFxBypassEnvelopeTests ARMixDearVrPolarPolicyTests ARMixRTTests ARMixPresetTests ARMixShowSchemaTests ARMixShowStoreTests ARMixLiveShowCaptureTests ARMixNativeMasterLoudnessTests ARMixDiagnosticTests ARMixClockBridgeTests ARMixVirtualClockSoakTests ARMixCadenceTests ARMixCrackleWindowTests ARMixHealthTests ARMixPolicyTests ARMixPeriodEvidenceTests ARMixLifecycleTests ARMixWasapiProbeTests ARMixDualJuceTests ARMixClockSizingTests ARMixIndependentFormatTests ARMixRecoveryTests ARMixStreamWatchdogTests ARMixBridgeContinuityTests ARMixEndpointPolicyTests ARMixEndpointGuardTests ARMixAsioPolicyTests ARMixAsioBackendTests ARMixAsioRegistryIdentityTests ARMixDirectFenceTests --parallel 2
- name: Test realtime control primitives
run: ctest --test-dir build -C Release --output-on-failure
- name: Package verified JUCE GUI for hardware FAT
Expand Down
4 changes: 4 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -234,4 +234,8 @@ if(BUILD_TESTING)
target_compile_features(ARMixShowStoreTests PRIVATE cxx_std_20)
add_test(NAME P4ImmutableNativeShowsAndVendorStateRoundTrip COMMAND ARMixShowStoreTests)

add_executable(ARMixNativeMasterLoudnessTests tests/native_master_loudness_test.cpp engine/dsp/NativeMasterLoudness.h)
target_compile_features(ARMixNativeMasterLoudnessTests PRIVATE cxx_std_20)
add_test(NAME P1KMeasuredNativeBS1770StereoAnd4xTruePeak COMMAND ARMixNativeMasterLoudnessTests)

endif()
20 changes: 20 additions & 0 deletions docs/P1K_NATIVE_BS1770_DBTp_20261029.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# P1K — Native measured 48 kHz MASTER LUFS-I and dBTP (2026-10-29)

**Scope:** Native JUCE DIRECT output, 48 kHz and first two physical output channels only. This PR does not certify all device/rate modes or crackle-free physical audio.

## Native signal authority
- Analysis reads **real hardware-bound MASTER PCM after fader, MUTE, routing, FX and ramp**, both from the existing CH1 path and the approved 10CH DRY Routing LAB. It never reads the browser preview meter or substitutes sample-peak telemetry for true peak.
- `engine/dsp/NativeMasterLoudness.h`: two reference 48-kHz ITU-R BS.1770 K-weight biquads, 400ms/75%-overlap blocks, -70 LUFS absolute gate and -10 LU relative gate; fixed 0.1 LU histogram quantization (maximum nominal 0.05 LU quantization).
- Native dBTP is measured from 4x interpolated audio via 32-tap Blackman-windowed sinc polyphase FIR, with DC normalization and an absolute maximum since device epoch. Intersample peaks are detected separately from the existing sample peak display.
- Always initialized **before** audio callbacks. `process()` has fixed-capacity buffers, no locks/allocations/VST/window/file/OS operations. Callback storage is O(samples) with bounded FIR work. Message-thread `read()` publishes provenance-tagged fields at the existing 12Hz status cadence; 10CH + AUX DSP topology and FX/Orbit callbacks remain unchanged.
- LUFS-I starts only after at least 400ms of valid above-gate signal; offline, silence, disconnected, and unqualified sample rate display **—**, not made-up numbers. dBTP holds maximum observed since current device start.
- Real JS WebView2 receives `masterAnalysisProvenance="MEASURED_48K_BS1770_K_4X_FIR"` and finite `masterLufs`/`masterDbtp`; the compact two-row black LCD displays numbers in bright green, changing to red only for LUFS-I above −12 or dBTP above −1. Browser standalone keeps its clearly simulated demo.

## Limitations/gates
- INTENTIONALLY unsupported: 44.1/88.2/96/192k until recalibrated K weighting and oversample spectral acceptance; independent WASAPI dual-clock output not yet instrumented (cannot silently reuse the DIRECT capture callback); output multichannel >2 not qualified. When unsupported, native LCD remains unavailable.
- Loudness histogram is fixed-memory and approximates exact floating-point gated block list by 0.1 LU. Compare against known ITU vectors, silence, stereo vs mono and live pro tooling before asserting broadcast certification.
- 32-tap 4x Blackman sinc should be compared against a verified Annex 2 / EBU Tech 3341 true-peak reference with intersample worst cases and high-frequency attenuation. The implementation is *measured* and useful, but no claim of formal IEC/ITU certification or guaranteed 0.0 dB numerical agreement.
- Windows CTest covers 997 Hz −20 dBFS stereo reference, 12 kHz phase-shifted intersample overshoot, unsupported rate, silence, reset. Need CPU callback p95, 44.1/48/96 sample-rate hardware FAT and profile on an onboard GPU Windows PC before expanded production support.
- Master UI does **not** change meter LEDs, fader, Plugin Catalog, VST3 lifecycle, routing, Orbit, CI matrix, or #15 crackle closure.

References: [ITU-R BS.1770-5](https://www.itu.int/rec/R-REC-BS.1770-5-202311-I).
178 changes: 178 additions & 0 deletions engine/dsp/NativeMasterLoudness.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
// SPDX-License-Identifier: AGPL-3.0-only
#pragma once
#include <array>
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstdint>
#include <limits>

// P1K v1: 48kHz DIRECT output ONLY, 1/2 PCM output channels.
// 48k coefficients below are from ITU-R BS.1770's exact reference tables.
// 400ms overlapping gated windows (100ms hop). Histogram quantization <=0.05 LU.
// 4x windowed-sinc oversampling for intersample peak (not linear sample peak).
//
// No locks, allocations, device/OS/UI calls in process(). All expensive
// preparation occurs before audioDeviceAboutToStart() returns.
// A second renderer/clock is intentionally NOT supported until bound to its
// own output stream and verified device epoch.
namespace armix::dsp {
class NativeMasterLoudness final {
public:
NativeMasterLoudness() noexcept
{
for(int i=0;i<bins;++i)
binEnergy_[i]=std::pow(10.0,(-70.0+(i+0.5)*0.1+0.691)/10.0);
}
struct Reading {
bool supported=false, integratedValid=false, truePeakValid=false;
double integratedLufs=0.0, dbtp=0.0;
std::uint64_t gatedWindows=0;
};
static constexpr int taps=32;
static constexpr int phases=4;
static constexpr int bins=801;
static constexpr int quarterFrames=4800; // exact 100ms at 48k

void prepare (double rate) noexcept
{
enabled_.store (false,std::memory_order_release);
for(auto& band:hist_)band.store(0,std::memory_order_relaxed);
peak_.store(0.f,std::memory_order_relaxed);
framesProcessed_.store(0,std::memory_order_relaxed);
quarterEnergy_.fill(0.0);
for(auto& ch:history_)ch.fill(0.0f);
for(auto& f:pre_)f.z1=f.z2=0.0;
for(auto& f:rlb_)f.z1=f.z2=0.0;
quarterOffset_=quarterSlot_=completeQuarters_=writeAt_=0;
if(std::abs(rate-48000.0)>0.5)return; // NEVER invent LUFS at other rates
constexpr double pi=3.1415926535897932384626433832795;
for(int phase=0;phase<phases;++phase) {
double norm=0.0;
for(int k=0;k<taps;++k) {
const double t=k-15.0-phase/4.0;
const double s=std::abs(t)<1e-12?1.0:std::sin(pi*t)/(pi*t);
const double w=0.42-0.5*std::cos(2*pi*k/(taps-1))
+0.08*std::cos(4*pi*k/(taps-1));
coeff_[phase][k]=s*w;
norm+=coeff_[phase][k];
}
for(auto& x:coeff_[phase])x/=norm; // unit DC gain
}
enabled_.store(true,std::memory_order_release);
}

void process(const float* const* output,int numChannels,int frames) noexcept
{
if(!enabled_.load(std::memory_order_relaxed)||!output||numChannels<1||frames<=0)
return;
const int count=numChannels>=2?2:1;
float blockPeak=0.f;
for(int i=0;i<frames;++i) {
double energy=0.0;
for(int c=0;c<count;++c) {
const float* src=output[c];
const float x=src&&std::isfinite(src[i])?src[i]:0.f;
double y=pre_[c].step(x);
y=rlb_[c].step(y);
energy+=y*y;
history_[c][writeAt_]=x;
for(int p=0;p<phases;++p) {
double v=0.0;
for(int k=0;k<taps;++k)
v+=coeff_[p][k]*history_[c][(writeAt_+1+k)&(taps-1)];
blockPeak=std::max(blockPeak,static_cast<float>(std::abs(v)));
}
}
writeAt_=(writeAt_+1)&(taps-1);
quarterEnergy_[quarterSlot_]+=energy;
if(++quarterOffset_==quarterFrames) {
quarterOffset_=0;
++completeQuarters_;
quarterSlot_=(quarterSlot_+1)&3;
if(completeQuarters_>=4) {
double window=0.0;
for(const double sum:quarterEnergy_) window+=sum;
window/=4.0*quarterFrames;
if(window>0.0) {
const double loudness=-0.691+10.0*std::log10(window);
if(loudness>-70.0) {
const int idx=static_cast<int>(std::floor((loudness+70.0)*10.0));
hist_[idx<0?0:idx>=bins?bins-1:idx].fetch_add(
1,std::memory_order_relaxed);
}
}
}
quarterEnergy_[quarterSlot_]=0.0;
}
}
float old=peak_.load(std::memory_order_relaxed);
while(old<blockPeak&&!peak_.compare_exchange_weak(
old,blockPeak,std::memory_order_relaxed)){}
framesProcessed_.fetch_add(static_cast<std::uint64_t>(frames),std::memory_order_relaxed);
}

Reading read() const noexcept
{
Reading out;
out.supported=enabled_.load(std::memory_order_acquire);
if(!out.supported)return out;
const float pk=peak_.load(std::memory_order_relaxed);
out.truePeakValid=framesProcessed_.load(std::memory_order_relaxed)>=quarterFrames && pk>0.f;
if(out.truePeakValid)out.dbtp=20.0*std::log10(static_cast<double>(pk));
double absoluteSum=0.0, count=0.0;
for(int i=0;i<bins;++i) {
const auto n=hist_[i].load(std::memory_order_relaxed);
absoluteSum+=binEnergy_[i]*n;
count+=n;
}
if(count<1.0)return out;
const double relative=-0.691+10.0*std::log10(absoluteSum/count)-10.0;
double gatedEnergy=0.0,gatedCount=0.0;
for(int i=0;i<bins;++i) {
const double loudness=-70.0+(i+0.5)*0.1;
if(loudness<=relative)continue;
const auto n=hist_[i].load(std::memory_order_relaxed);
gatedEnergy+=binEnergy_[i]*n;
gatedCount+=n;
}
if(gatedCount>=1.0) {
out.integratedLufs=-0.691+10.0*std::log10(gatedEnergy/gatedCount);
out.integratedValid=std::isfinite(out.integratedLufs);
out.gatedWindows=static_cast<std::uint64_t>(gatedCount);
}
if(!enabled_.load(std::memory_order_acquire))return {};
return out;
}
private:
struct Biquad {
// Transposed DF-II states, double precision, zero allocation.
double z1=0,z2=0;
double b0=1,b1=0,b2=0,a1=0,a2=0;
double step(double x) noexcept {
const double y=b0*x+z1;
z1=b1*x-a1*y+z2;
z2=b2*x-a2*y;
Comment on lines +153 to +155

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Suppress denormals in the loudness filter

When audio becomes silent after a nonzero signal and the callback thread has flush-to-zero disabled, these recursive filter states decay into subnormal doubles and continue doing expensive subnormal arithmetic throughout silence. Neither process() nor the calling LiveAudioEngine callback establishes a denormal guard. An optimized standalone reproduction using an impulse followed by silence took approximately 40–51 ms per second of processed audio, versus 16 ms with FTZ/DAZ enabled. Because this meter now runs on every supported DIRECT callback, this unnecessarily consumes realtime processing headroom even while output is muted. Add a scoped denormal guard or explicitly flush sufficiently small filter states to zero, and cover signal-to-silence transitions in the tests.

Useful? React with 👍 / 👎.

return y;
}
};
// Exact 48kHz coefficient sets specified in BS.1770 annex 1.
std::array<Biquad,2> pre_{{
{0,0,1.53512485958697,-2.69169618940638,1.19839281085285,-1.69065929318241,0.73248077421585},
{0,0,1.53512485958697,-2.69169618940638,1.19839281085285,-1.69065929318241,0.73248077421585}
}};
std::array<Biquad,2> rlb_{{
{0,0,1.,-2.,1.,-1.99004745483398,0.99007225036621},
{0,0,1.,-2.,1.,-1.99004745483398,0.99007225036621}
}};
std::array<std::array<float,taps>,2> history_{};
std::array<std::array<double,taps>,phases> coeff_{};
std::array<double,bins> binEnergy_{};
std::array<double,4> quarterEnergy_{};
std::array<std::atomic<std::uint32_t>,bins> hist_{};
std::atomic<float> peak_{0.f};
std::atomic<std::uint64_t> framesProcessed_{0};
std::atomic<bool> enabled_{false};
int writeAt_=0,quarterOffset_=0,quarterSlot_=0,completeQuarters_=0;
};
} // namespace armix::dsp
27 changes: 27 additions & 0 deletions src/LiveAudioEngine.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "VstBusLayout.h"
#include "LiveGraphHandoff.h"
#include "LiveDryRoutingLab.h"
#include "../engine/dsp/NativeMasterLoudness.h"
#include "DiagnosticTone.h"
#include "../engine/device/JuceIndependentClockDevice.h"
#include "../engine/device/AsioPriorityDeviceManager.h"
Expand Down Expand Up @@ -985,6 +986,14 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback
o->setProperty ("peak", outputPeak_.load());
o->setProperty ("peakLeft", outputPeakL_.load());
o->setProperty ("peakRight", outputPeakR_.load());
const auto loudness = masterLoudness_.read();
const bool measuredDirect = !dual && loudness.supported;
o->setProperty ("masterAnalysisProvenance",
measuredDirect ? "MEASURED_48K_BS1770_K_4X_FIR" : "UNSUPPORTED");
if (measuredDirect && loudness.integratedValid)
o->setProperty ("masterLufs", loudness.integratedLufs);
if (measuredDirect && loudness.truePeakValid)
o->setProperty ("masterDbtp", loudness.dbtp);
o->setProperty ("latencySamples", totalLatency_.load());
o->setProperty ("chainCount", graphOwned_->count);
o->setProperty ("graphSwitchPending", handoff_.busy());
Expand Down Expand Up @@ -1121,6 +1130,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback
bool attached_ = false;
juce::AudioBuffer<float> scratch_;
juce::AudioBuffer<float> dryScratch_;
armix::dsp::NativeMasterLoudness masterLoudness_;
armix::diagnostics::DiagnosticTone diagnosticTone_;
LiveDryRoutingLab dryRoutingLab_;
std::atomic<armix::diagnostics::Route> diagnosticRoute_ {armix::diagnostics::Route::normal};
Expand Down Expand Up @@ -1219,6 +1229,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback
deviceStartCount_.fetch_add (1, std::memory_order_relaxed);
sampleRateHz_ = juce::jmax (1.0, d->getCurrentSampleRate());
diagnosticTone_.prepare (sampleRateHz_); // device stopped; no RT allocation
masterLoudness_.prepare (sampleRateHz_); // fixed buffers, 48k DIRECT only
for (int i = 0; i < maxFx; ++i)
{
lastPluginUsBySlot_[i].store (0, std::memory_order_relaxed);
Expand Down Expand Up @@ -1249,6 +1260,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback

void audioDeviceStopped() override
{
masterLoudness_.prepare (0.0); // clear validity across device epoch
dryRoutingLab_.deviceStopped();
deviceStopCount_.fetch_add (1, std::memory_order_relaxed);
inputPeak_.store (0.f);
Expand Down Expand Up @@ -1328,6 +1340,13 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback
if(outputs && outputs[c])
juce::FloatVectorOperations::clear(outputs[c],samples);
}
// Read actual hardware-bound MASTER PCM, never browser preview.
// A fixed stack view; no VST/JSON/heap/locks in the audio callback.
const float* measured[2] = {
outputs && outputChannels>0 ? outputs[0] : nullptr,
outputs && outputChannels>1 ? outputs[1] : nullptr
};
masterLoudness_.process(measured,juce::jmin(outputChannels,2),samples);
// Only actually routed audio can produce a live output meter.
const float left=routed?dryRoutingLab_.peakLeft():0.f;
const float right=routed?dryRoutingLab_.peakRight():0.f;
Expand Down Expand Up @@ -1495,6 +1514,14 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback
if (c == 1) outPeakR = juce::jmax (outPeakR, channelPeak);
}
}
if (!independent_.active())
{
const float* measured[2] = {
outputs && outputChannels>0 ? outputs[0] : nullptr,
outputs && outputChannels>1 ? outputs[1] : nullptr
};
masterLoudness_.process(measured,juce::jmin(outputChannels,2),samples);
}
inputPeak_.store (juce::jmin (1.f, inPeak), std::memory_order_relaxed);
postFxPeak_.store (juce::jmin (1.f, postFxPeak), std::memory_order_relaxed);
outputPeak_.store (juce::jmin (1.f, outPeak), std::memory_order_relaxed);
Expand Down
15 changes: 9 additions & 6 deletions tests/main_v08_native_integration_test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,14 @@ test('startup never opens an audio device before the WebView2 GUI handshake',()=
assert.ok(readyGate>=0&&startup>readyGate);
assert.ok(timer.includes('browser_.loaded')&&timer.includes('guiReadyTick_ < 150u'));
});
test('master readout remains native-unavailable until measured BS.1770/true peak exists',()=>{
assert.match(app,/updateMasterAnalysisPreview\(-31\+/);
assert.match(app,/\['masterLufs',lufs,-12\]/);
assert.match(app,/\['masterDbtp',dbtp,-1\]/);
assert.match(bridge,/lufs\.textContent="—"/);
assert.match(bridge,/tp\.textContent="—"/);
test('native LUFS/true peak are shown only with qualified live measurement provenance',()=>{
assert.match(app,/updateMasterAnalysisPreview\(-31\+/); // preview remains demo-only
assert.match(bridge,/MEASURED_48K_BS1770_K_4X_FIR/);
assert.match(bridge,/element\.classList\.toggle\("over-limit",measured&&value>limit\)/);
assert.match(src,/masterLoudness_\.process\(measured,juce::jmin\(outputChannels,2\),samples\)/);
assert.match(src,/masterLoudness_\.prepare \(sampleRateHz_\)/);
assert.match(src,/masterLoudness_\.prepare \(0\.0\)/);
assert.match(src,/masterAnalysisProvenance/);
assert.doesNotMatch(bridge,/lufs\.textContent="—"/);
assert.doesNotMatch(app, /STREAM LEVELS <span>SIM<\/span>/);
});
Loading
Loading