diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 06002b11e..15c312319 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -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 diff --git a/CMakeLists.txt b/CMakeLists.txt index d7b30c85f..42088138f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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() diff --git a/docs/P1K_NATIVE_BS1770_DBTp_20261029.md b/docs/P1K_NATIVE_BS1770_DBTp_20261029.md new file mode 100644 index 000000000..96eb84fe2 --- /dev/null +++ b/docs/P1K_NATIVE_BS1770_DBTp_20261029.md @@ -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). diff --git a/engine/dsp/NativeMasterLoudness.h b/engine/dsp/NativeMasterLoudness.h new file mode 100644 index 000000000..4c6dd0d54 --- /dev/null +++ b/engine/dsp/NativeMasterLoudness.h @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include +#include + +// 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;i0.5)return; // NEVER invent LUFS at other rates + constexpr double pi=3.1415926535897932384626433832795; + for(int phase=0;phase=2?2:1; + float blockPeak=0.f; + for(int i=0;i(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(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(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(pk)); + double absoluteSum=0.0, count=0.0; + for(int i=0;i=1.0) { + out.integratedLufs=-0.691+10.0*std::log10(gatedEnergy/gatedCount); + out.integratedValid=std::isfinite(out.integratedLufs); + out.gatedWindows=static_cast(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; + return y; + } + }; + // Exact 48kHz coefficient sets specified in BS.1770 annex 1. + std::array 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 rlb_{{ + {0,0,1.,-2.,1.,-1.99004745483398,0.99007225036621}, + {0,0,1.,-2.,1.,-1.99004745483398,0.99007225036621} + }}; + std::array,2> history_{}; + std::array,phases> coeff_{}; + std::array binEnergy_{}; + std::array quarterEnergy_{}; + std::array,bins> hist_{}; + std::atomic peak_{0.f}; + std::atomic framesProcessed_{0}; + std::atomic enabled_{false}; + int writeAt_=0,quarterOffset_=0,quarterSlot_=0,completeQuarters_=0; +}; +} // namespace armix::dsp diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index cffdec53d..1fe032ef1 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -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" @@ -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()); @@ -1121,6 +1130,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool attached_ = false; juce::AudioBuffer scratch_; juce::AudioBuffer dryScratch_; + armix::dsp::NativeMasterLoudness masterLoudness_; armix::diagnostics::DiagnosticTone diagnosticTone_; LiveDryRoutingLab dryRoutingLab_; std::atomic diagnosticRoute_ {armix::diagnostics::Route::normal}; @@ -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); @@ -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); @@ -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; @@ -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); diff --git a/tests/main_v08_native_integration_test.mjs b/tests/main_v08_native_integration_test.mjs index 051d4673c..38973b2fc 100644 --- a/tests/main_v08_native_integration_test.mjs +++ b/tests/main_v08_native_integration_test.mjs @@ -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 SIM<\/span>/); }); diff --git a/tests/native_master_loudness_test.cpp b/tests/native_master_loudness_test.cpp new file mode 100644 index 000000000..9ec9a42ad --- /dev/null +++ b/tests/native_master_loudness_test.cpp @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#ifdef NDEBUG + #undef NDEBUG +#endif +#include +#include +#include +#include "../engine/dsp/NativeMasterLoudness.h" + +int main() +{ + using armix::dsp::NativeMasterLoudness; + constexpr double pi=3.14159265358979323846; + NativeMasterLoudness meter; + meter.prepare(44100.0); + assert(!meter.read().supported); // no invented measurements at unqualified rate + meter.prepare(48000.0); + assert(meter.read().supported); + assert(!meter.read().integratedValid); + constexpr int chunk=480; + float L[chunk]{},R[chunk]{}; + const float* output[2]{L,R}; + // ITU-R BS.1770 997 Hz 0 dBFS sine = -3.01 LKFS per channel. + // Stereo -20dBFS => approx -20 LUFS after 2x channel power. + for(int block=0;block<110;++block) { + for(int i=0;i(std::sin(2*pi*997*n/48000.0)); + } + meter.process(output,2,chunk); + } + const auto a=meter.read(); + if(!a.integratedValid||!a.truePeakValid) + std::cerr<<"valid="<=2); + assert(a.integratedLufs > -21.0 && a.integratedLufs < -19.0); + assert(a.dbtp > -20.8 && a.dbtp < -19.2); + + // 4x interpolated reconstruction must detect intersample peaks, not + // merely maximum discrete 12kHz sampled input. + meter.prepare(48000.0); + double sampled=0; + for(int block=0;block<110;++block) { + for(int i=0;i(std::sin(2*pi*12000*n/48000.0+pi/4)); + sampled=std::max(sampled,static_cast(std::abs(L[i]))); + } + meter.process(output,2,chunk); + } + const auto reconstructed=meter.read(); + const double sampleDb=20*std::log10(sampled); + if(!(reconstructed.dbtp>sampleDb+2.0)) + std::cerr<<"sample dBFS="<sampleDb+2.0); + assert(reconstructed.dbtp<0.0); // 0.9 amplitude never exceeds actual 0dBFS + + // Muted/silent signal must never be represented as a fabricated finite LUFS. + meter.prepare(48000.0); + for(int i=0;ilimit); + element.setAttribute("aria-label",measured? + ("Native measured "+unit+" "+label):(unit+" unavailable")); + } + const lcd=document.querySelector("#masterLeft .master-analysis"); + if(lcd){ + const info=measurement? + "Native measured 48k BS.1770 K-weighted gated LUFS and 4x FIR true peak": + "Native measurement unavailable at this rate or independent clock"; + if(lcd.title!==info)lcd.title=info; + } const pk=document.getElementById("masterPeakDb"); if(pk)pk.textContent=Number(d.peak)>0 ?(20*Math.log10(Math.max(1e-8,Number(d.peak)))).toFixed(1)+" dBFS":"−∞";