From 69fedf8777e9d8514c3e82e78c924baedcacc29f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 19:50:18 +0700 Subject: [PATCH 01/25] feat(P0): real separate WASAPI capture and render devices with bounded SPSC polyphase bridge --- src/SplitDuplexAdapter.h | 168 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 src/SplitDuplexAdapter.h diff --git a/src/SplitDuplexAdapter.h b/src/SplitDuplexAdapter.h new file mode 100644 index 000000000..9ad44f0b5 --- /dev/null +++ b/src/SplitDuplexAdapter.h @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "../engine/device/AdaptiveClockBridge.h" +#include +#include +#include +#include + +// P0: real independent JUCE Windows Audio capture and render streams. +// This is deliberately NOT a second callback registered on the same manager: +// each AudioDeviceManager owns its own one-sided WASAPI AudioIODevice/clock. +// All lifecycle methods execute on the JUCE control/message thread. Both +// callbacks are removed and endpoints stopped before reconfiguring the bridge. +// No I/O, lock, malloc, COM query, or UI work in the producer callback. +namespace armix::device +{ +class SplitDuplexAdapter final +{ + struct CaptureTap final : juce::AudioIODeviceCallback + { + explicit CaptureTap (AdaptiveClockBridge& bridge) : bridge_ (bridge) {} + + void audioDeviceIOCallbackWithContext ( + const float* const* input, int inputs, + float* const*, int, int frames, + const juce::AudioIODeviceCallbackContext&) override + { + const auto now = micros(); + lastCallbackUs.store (now, std::memory_order_relaxed); + callbackCount.fetch_add (1, std::memory_order_relaxed); + if (frames > 0 && inputs > 0 && input != nullptr) + bridge_.push (input, inputs, frames); + } + void audioDeviceAboutToStart (juce::AudioIODevice* device) override + { + startCount.fetch_add (1, std::memory_order_relaxed); + rateHz.store (device->getCurrentSampleRate(), std::memory_order_relaxed); + lastCallbackUs.store (micros(), std::memory_order_relaxed); + } + void audioDeviceStopped() override + { + stopCount.fetch_add (1, std::memory_order_relaxed); + lastCallbackUs.store (0, std::memory_order_relaxed); + } + static std::uint64_t micros() noexcept + { + return static_cast ( + std::chrono::duration_cast ( + std::chrono::steady_clock::now().time_since_epoch()).count()); + } + AdaptiveClockBridge& bridge_; + std::atomic lastCallbackUs {0}, callbackCount {0}; + std::atomic startCount {0}, stopCount {0}; + std::atomic rateHz {0.}; + }; + +public: + struct Readout + { + AdaptiveClockBridge::Status fifo; + std::uint64_t captureCallbacks = 0; + std::uint64_t captureAgeUs = 0; + std::uint64_t captureStarts = 0, captureStops = 0; + double captureRate = 0., outputRate = 0.; + int captureChannels = 0, renderChannels = 0; + int capturePeriodFrames = 0, renderPeriodFrames = 0; + int captureDriverXRuns = -1; // JUCE-backend-specific, not render underruns + }; + + SplitDuplexAdapter() : tap_ (bridge_) {} + ~SplitDuplexAdapter() { stop(); } + + // First caller MUST stop the existing full-duplex device, preserving the + // user's combined AudioDeviceSetup on the message thread for rollback. + juce::String prepare (const juce::String& deviceType, + const juce::AudioDeviceManager::AudioDeviceSetup& original, + juce::AudioDeviceManager& renderManager, + double fifoTargetMs = 20.) + { + if (running_) return "Split stream already active"; + if (!deviceType.startsWithIgnoreCase ("Windows Audio") + || deviceType.containsIgnoreCase ("Exclusive")) + return "Separate-clock bridge is supported only on Windows Audio shared backends"; + if (original.inputDeviceName.isEmpty() || original.outputDeviceName.isEmpty()) + return "Both capture and render endpoints must be configured"; + + juce::AudioDeviceManager::AudioDeviceSetup capture = original; + capture.outputDeviceName.clear(); + capture.outputChannels.clear(); + capture.useDefaultOutputChannels = false; + capture.useDefaultInputChannels = false; + capture.inputChannels.clear(); + capture.inputChannels.setRange (0, 2, true); // target max two physical channels + // Initialise with zero channels to avoid briefly opening a wrong default + // endpoint. Then select the original backend and explicit capture name. + auto error = captureManager_.initialise (0, 0, nullptr, false); + if (error.isNotEmpty()) return "Capture manager initialise: " + error; + captureManager_.setCurrentAudioDeviceType (deviceType, false); + error = captureManager_.setAudioDeviceSetup (capture, false); + if (error.isNotEmpty()) return "Independent capture open: " + error; + + auto* const cap = captureManager_.getCurrentAudioDevice(); + auto* const out = renderManager.getCurrentAudioDevice(); + if (cap == nullptr || out == nullptr) + return "Two independent audio endpoints were not opened"; + const auto inputs = cap->getActiveInputChannels().countNumberOfSetBits(); + const auto outputs = out->getActiveOutputChannels().countNumberOfSetBits(); + if (inputs < 1 || outputs < 1 + || cap->getActiveOutputChannels().countNumberOfSetBits() != 0 + || out->getActiveInputChannels().countNumberOfSetBits() != 0) + return "Backend refused independent capture/render isolation"; + + const double captureRate = cap->getCurrentSampleRate(); + const double outputRate = out->getCurrentSampleRate(); + if (!bridge_.prepare (captureRate, outputRate, 2, 16384, fifoTargetMs)) + return "Cannot prepare a bounded drift-correction bridge at negotiated device rates"; + // Strictly no callback can observe an unprepared or reset bridge. + captureManager_.addAudioCallback (&tap_); + captureAttached_ = true; + running_ = true; + return {}; + } + + void stop() noexcept + { + if (captureAttached_) + { + captureManager_.removeAudioCallback (&tap_); + captureAttached_ = false; + } + captureManager_.closeAudioDevice(); + running_ = false; + } + + bool running() const noexcept { return running_; } + void pull (float* const* outputs, int channels, int frames) noexcept + { + bridge_.pull (outputs, channels, frames); + } + + Readout snapshot (const juce::AudioIODevice* renderDevice) const + { + Readout r; + r.fifo = bridge_.status(); + r.captureCallbacks = tap_.callbackCount.load (std::memory_order_relaxed); + r.captureStarts = tap_.startCount.load (std::memory_order_relaxed); + r.captureStops = tap_.stopCount.load (std::memory_order_relaxed); + const auto last = tap_.lastCallbackUs.load (std::memory_order_relaxed); + const auto now = CaptureTap::micros(); + r.captureAgeUs = last > 0 && now >= last ? now - last : 0; + const auto* cap = captureManager_.getCurrentAudioDevice(); + r.captureRate = cap ? cap->getCurrentSampleRate() : 0.; + r.outputRate = renderDevice ? renderDevice->getCurrentSampleRate() : 0.; + r.captureChannels = cap ? cap->getActiveInputChannels().countNumberOfSetBits() : 0; + r.renderChannels = renderDevice ? renderDevice->getActiveOutputChannels().countNumberOfSetBits() : 0; + r.capturePeriodFrames = cap ? cap->getCurrentBufferSizeSamples() : 0; + r.renderPeriodFrames = renderDevice ? renderDevice->getCurrentBufferSizeSamples() : 0; + r.captureDriverXRuns = cap ? cap->getXRunCount() : -1; + return r; + } + +private: + AdaptiveClockBridge bridge_; + juce::AudioDeviceManager captureManager_; + CaptureTap tap_; + bool captureAttached_ = false, running_ = false; // message-thread only +}; +} // namespace armix::device From a57df1be7238a6d6fb8a04ebffdec995ed336b70 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 19:51:58 +0700 Subject: [PATCH 02/25] feat(P0): run true independent capture/render managers and live adaptive clock bridge with rollback --- src/LiveAudioEngine.h | 162 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 158 insertions(+), 4 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index db3c0c850..510bb371f 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -7,6 +7,7 @@ #include "VstBusLayout.h" #include "LiveGraphHandoff.h" #include "DiagnosticTone.h" +#include "SplitDuplexAdapter.h" #include "../engine/core/RealtimeHealthHistogram.h" #include #include @@ -73,6 +74,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void stop() { + // Capture callback stops before releasing its FIFO or the render graph. + if (smartBridgeConfigured_) splitAdapter_.stop(); + smartBridgeEnabled_.store (false, std::memory_order_release); detach(); handoff_.resetAfterStop (graphOwned_.get()); stagedOwner_.reset(); @@ -85,6 +89,117 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback deviceManager_.closeAudioDevice(); } + // True separate stream mode: input and output are opened as two WASAPI + // AudioIODevices, NOT two callbacks multiplexed on one JUCE manager. + // Message-thread-only operations. On any error restore original full + // duplex, and fail muted when hardware restoration cannot succeed. + juce::String enableSmartBridge (double targetLatencyMs = 20.) + { + using Setup = juce::AudioDeviceManager::AudioDeviceSetup; + if (isGraphSwitchPending()) return "FX graph transition pending"; + if (savedLiveSetup_) return "Leave the endpoint isolation test first"; + if (smartBridgeConfigured_) + { + const auto stopError = disableSmartBridge(); + if (stopError.isNotEmpty()) return stopError; + } + const auto type = deviceManager_.getCurrentAudioDeviceType(); + if (!type.startsWithIgnoreCase ("Windows Audio") || type.containsIgnoreCase ("Exclusive")) + return "Smart clock bridge currently requires Windows Audio shared backend"; + const Setup original = deviceManager_.getAudioDeviceSetup(); + if (original.inputDeviceName.isEmpty() || original.outputDeviceName.isEmpty()) + return "Input and output must both be configured before Smart Audio can start"; + routeReconfiguring_.store (true, std::memory_order_release); + detach(); + Setup outputOnly = original; + outputOnly.inputDeviceName.clear(); + outputOnly.inputChannels.clear(); + outputOnly.useDefaultInputChannels = false; + auto error = deviceManager_.setAudioDeviceSetup (outputOnly, false); + if (error.isEmpty()) + { + auto* output = deviceManager_.getCurrentAudioDevice(); + if (output == nullptr || output->getActiveInputChannels().countNumberOfSetBits() != 0 + || output->getActiveOutputChannels().countNumberOfSetBits() == 0) + error = "Output endpoint refused render-only mode"; + } + if (error.isEmpty()) + error = splitAdapter_.prepare (type, original, deviceManager_, targetLatencyMs); + if (error.isNotEmpty()) + { + splitAdapter_.stop(); + smartBridgeEnabled_.store (false, std::memory_order_release); + const auto rollback = deviceManager_.setAudioDeviceSetup (original, false); + if (rollback.isNotEmpty()) + { + setOutputMuted (true); + error += " | FATAL fallback failed: " + rollback; + } + attach(); + routeReconfiguring_.store (false, std::memory_order_release); + return "Smart Audio could not start: " + error; + } + smartBridgeConfigured_ = original; + smartBridgeEnabled_.store (true, std::memory_order_release); + smartTargetMs_.store (targetLatencyMs, std::memory_order_relaxed); + attach(); // render clock enters DSP after bridge is ready + routeReconfiguring_.store (false, std::memory_order_release); + return {}; + } + + juce::String disableSmartBridge() + { + if (!smartBridgeConfigured_) return {}; + routeReconfiguring_.store (true, std::memory_order_release); + detach(); // block render consumer before tearing down capture producer + splitAdapter_.stop(); // drain producer before any FIFO reconfiguration + smartBridgeEnabled_.store (false, std::memory_order_release); + const auto previous = *smartBridgeConfigured_; + const auto error = deviceManager_.setAudioDeviceSetup (previous, false); + if (error.isEmpty()) + smartBridgeConfigured_.reset(); + else + setOutputMuted (true); // preserve original config for retry + attach(); + routeReconfiguring_.store (false, std::memory_order_release); + return error.isEmpty() ? juce::String() + : "Original full-duplex device restore failed: " + error; + } + + // At startup AUTO only attempts independently opened Windows Audio streams + // for distinct selected endpoint names; ASIO always keeps the direct path. + juce::String configureStartupAuto() + { + const auto setup = deviceManager_.getAudioDeviceSetup(); + const auto type = deviceManager_.getCurrentAudioDeviceType(); + if (type.startsWithIgnoreCase ("Windows Audio") + && !type.containsIgnoreCase ("Exclusive") + && setup.inputDeviceName.isNotEmpty() + && setup.outputDeviceName.isNotEmpty() + && setup.inputDeviceName != setup.outputDeviceName) + return enableSmartBridge(); + return {}; + } + + bool isSmartBridgeActive() const noexcept + { return smartBridgeEnabled_.load (std::memory_order_acquire); } + bool hasSmartBridgeSetup() const noexcept { return smartBridgeConfigured_.has_value(); } + bool hasTemporaryAudioRouting() const noexcept + { return savedLiveSetup_.has_value() || smartBridgeConfigured_.has_value(); } + + // If capture stops scheduling, the existing joined JUCE route is restored + // ON THE MESSAGE THREAD, never inside an audio callback. Report fallback. + juce::String pollSmartHealth() + { + if (!isSmartBridgeActive()) return {}; + const auto health = splitAdapter_.snapshot (deviceManager_.getCurrentAudioDevice()); + if (health.captureCallbacks < 2 || health.captureAgeUs < 3000000u) + return {}; + const auto fallbackError = disableSmartBridge(); + return "Smart bridge capture silent for >3 seconds: automatic direct fallback" + + (fallbackError.isNotEmpty() ? " | " + fallbackError : juce::String()); + } + void setMonitorEnabled (bool value) noexcept { monitor_.store (value); } bool isMonitorEnabled() const noexcept { return monitor_.load(); } // Emergency output mute, not a prerequisite for receiving audio. @@ -97,6 +212,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { using Route = armix::diagnostics::Route; if (handoff_.busy()) return "Finish the pending FX graph transition first"; + if (isSmartBridgeActive() || smartBridgeConfigured_) + return "Return to DIRECT mode before changing diagnostic route"; if (wanted == diagnosticRoute_.load (std::memory_order_acquire) && !(wanted == Route::normal && savedLiveSetup_)) return {}; if (wanted < Route::normal || wanted > Route::captureOnly) @@ -504,6 +621,27 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("dryTest", dryTest_.load()); const auto route = diagnosticRoute(); o->setProperty ("diagnosticRoute", armix::diagnostics::routeName (route)); + const bool split = isSmartBridgeActive(); + o->setProperty ("smartMode", split ? "DUAL_CLOCK_BRIDGED" : "DIRECT_JUCE"); + o->setProperty ("smartTargetLatencyMs", smartTargetMs_.load()); + if (split) + { + const auto b = splitAdapter_.snapshot (d); + o->setProperty ("inputDevice", smartBridgeConfigured_->inputDeviceName); + o->setProperty ("bridgeCaptureRate", b.captureRate); + o->setProperty ("bridgeRenderRate", b.outputRate); + o->setProperty ("bridgeCapturePeriod", b.capturePeriodFrames); + o->setProperty ("bridgeRenderPeriod", b.renderPeriodFrames); + o->setProperty ("bridgeFillFrames", static_cast (b.fifo.fillFrames)); + o->setProperty ("bridgeCorrectionPpm", b.fifo.correctionPpm); + o->setProperty ("bridgeCaptureCallbacks", static_cast (b.captureCallbacks)); + o->setProperty ("bridgeCaptureAgeMs", static_cast (b.captureAgeUs) / 1000.); + o->setProperty ("bridgeProducerOverflowFrames", static_cast (b.fifo.overflowFrames)); + o->setProperty ("bridgeConsumerUnderflowFrames", static_cast (b.fifo.underflowFrames)); + o->setProperty ("bridgeStartupPrimingFrames", static_cast (b.fifo.primingFrames)); + o->setProperty ("bridgeCaptureBackendXRuns", b.captureDriverXRuns < 0 + ? juce::var() : juce::var (b.captureDriverXRuns)); + } o->setProperty ("diagnosticTemporary", savedLiveSetup_.has_value()); o->setProperty ("deviceGeneration", static_cast (deviceStartCount_.load())); o->setProperty ("lateCallbackIntervals", static_cast (lateCallbackIntervals_.load())); @@ -513,16 +651,21 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // AudioIODevice::getXRunCount is backend-specific, not comprehensive. // Pinned JUCE WASAPI reports input capture discontinuity flags only. const int reported = d != nullptr ? d->getXRunCount() : -1; - o->setProperty ("backendXrunCount", reported >= 0 ? juce::var (reported) : juce::var()); + o->setProperty ("backendXrunCount", reported >= 0 && !split ? juce::var (reported) : juce::var()); + if (split) + o->setProperty ("backendXrunCount", splitAdapter_.snapshot (d).captureDriverXRuns >= 0 + ? juce::var (splitAdapter_.snapshot (d).captureDriverXRuns) : juce::var()); const auto type = deviceManager_.getCurrentAudioDeviceType(); o->setProperty ("backendXrunMeaning", reported < 0 ? "UNAVAILABLE" : type.startsWith ("Windows Audio") ? "WASAPI_CAPTURE_DISCONTINUITIES_ONLY" : "DRIVER_DEFINED"); juce::AudioDeviceManager::AudioDeviceSetup setup; deviceManager_.getAudioDeviceSetup (setup); - o->setProperty ("inputDevice", setup.inputDeviceName); + if (!split) o->setProperty ("inputDevice", setup.inputDeviceName); o->setProperty ("outputDevice", setup.outputDeviceName); - o->setProperty ("deviceInputChannels", d ? d->getActiveInputChannels().countNumberOfSetBits() : 0); + o->setProperty ("deviceInputChannels", split + ? splitAdapter_.snapshot (d).captureChannels + : d ? d->getActiveInputChannels().countNumberOfSetBits() : 0); o->setProperty ("deviceOutputChannels", d ? d->getActiveOutputChannels().countNumberOfSetBits() : 0); o->setProperty ("callbackInputChannels", callbackInputs_.load()); o->setProperty ("callbackOutputChannels", callbackOutputs_.load()); @@ -574,6 +717,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback private: static constexpr int maxFrames = 8192; juce::AudioDeviceManager deviceManager_; + armix::device::SplitDuplexAdapter splitAdapter_; + std::atomic smartBridgeEnabled_ {false}; + std::optional smartBridgeConfigured_; // message thread + std::atomic smartTargetMs_ {0.}; juce::AudioPluginFormatManager formats_; std::unique_ptr graphOwned_ {std::make_unique()}; std::unique_ptr stagedOwner_; @@ -724,6 +871,13 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { const int frames = juce::jmin (maxFrames, samples - offset); scratch_.setSize (2, frames, false, false, true); + if (smartBridgeEnabled_.load (std::memory_order_acquire) && !toneTest) + { + auto* left = scratch_.getWritePointer (0); + auto* right = scratch_.getWritePointer (1); + float* target[2] {left, right}; + splitAdapter_.pull (target, 2, frames); + } if (toneTest) { auto* left = scratch_.getWritePointer (0); @@ -737,7 +891,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback float* dst = scratch_.getWritePointer (c); const float* src = inputChannels > c ? inputs[c] : inputChannels > 0 ? inputs[0] : nullptr; - if (!toneTest) + if (!toneTest && !smartBridgeEnabled_.load (std::memory_order_relaxed)) { if (src) juce::FloatVectorOperations::copy (dst, src + offset, frames); From e14c3b3ceff6e45ffff3005f3cac008d1a213280 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 19:53:10 +0700 Subject: [PATCH 03/25] fix(P0): honor mono capture selection and observe stopped endpoint for deterministic fallback --- src/SplitDuplexAdapter.h | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/SplitDuplexAdapter.h b/src/SplitDuplexAdapter.h index 9ad44f0b5..8c31bc1da 100644 --- a/src/SplitDuplexAdapter.h +++ b/src/SplitDuplexAdapter.h @@ -33,6 +33,7 @@ class SplitDuplexAdapter final } void audioDeviceAboutToStart (juce::AudioIODevice* device) override { + stopped_.store (false, std::memory_order_release); startCount.fetch_add (1, std::memory_order_relaxed); rateHz.store (device->getCurrentSampleRate(), std::memory_order_relaxed); lastCallbackUs.store (micros(), std::memory_order_relaxed); @@ -40,6 +41,9 @@ class SplitDuplexAdapter final void audioDeviceStopped() override { stopCount.fetch_add (1, std::memory_order_relaxed); + // Publish stopped state for supervisory fallback even if no more + // capture callbacks will ever arrive. + stopped_.store (true, std::memory_order_release); lastCallbackUs.store (0, std::memory_order_relaxed); } static std::uint64_t micros() noexcept @@ -52,6 +56,7 @@ class SplitDuplexAdapter final std::atomic lastCallbackUs {0}, callbackCount {0}; std::atomic startCount {0}, stopCount {0}; std::atomic rateHz {0.}; + std::atomic stopped_ {true}; }; public: @@ -61,6 +66,7 @@ class SplitDuplexAdapter final std::uint64_t captureCallbacks = 0; std::uint64_t captureAgeUs = 0; std::uint64_t captureStarts = 0, captureStops = 0; + bool captureStopped = false; double captureRate = 0., outputRate = 0.; int captureChannels = 0, renderChannels = 0; int capturePeriodFrames = 0, renderPeriodFrames = 0; @@ -90,7 +96,10 @@ class SplitDuplexAdapter final capture.useDefaultOutputChannels = false; capture.useDefaultInputChannels = false; capture.inputChannels.clear(); - capture.inputChannels.setRange (0, 2, true); // target max two physical channels + // Keep the working user's input mask: a mono device may reject asking + // for a second physical channel that it does not expose. + capture.inputChannels = original.inputChannels; + if (capture.inputChannels.isZero()) capture.inputChannels.setBit (0); // Initialise with zero channels to avoid briefly opening a wrong default // endpoint. Then select the original backend and explicit capture name. auto error = captureManager_.initialise (0, 0, nullptr, false); @@ -145,6 +154,7 @@ class SplitDuplexAdapter final r.captureCallbacks = tap_.callbackCount.load (std::memory_order_relaxed); r.captureStarts = tap_.startCount.load (std::memory_order_relaxed); r.captureStops = tap_.stopCount.load (std::memory_order_relaxed); + r.captureStopped = tap_.stopped_.load (std::memory_order_acquire); const auto last = tap_.lastCallbackUs.load (std::memory_order_relaxed); const auto now = CaptureTap::micros(); r.captureAgeUs = last > 0 && now >= last ? now - last : 0; From 3b30921033da473229cce0e3d4fc843e07af1853 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 19:53:48 +0700 Subject: [PATCH 04/25] feat(P0): telemetry for actual split-stream clock state and capture watchdog failback --- src/LiveAudioEngine.h | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 510bb371f..ddc0c0899 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -74,10 +74,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void stop() { - // Capture callback stops before releasing its FIFO or the render graph. + // Close BOTH callbacks before releasing the FIFO, processor or graph. + // Renderer is stopped first to guarantee no concurrent FIFO readers. + detach(); if (smartBridgeConfigured_) splitAdapter_.stop(); smartBridgeEnabled_.store (false, std::memory_order_release); - detach(); handoff_.resetAfterStop (graphOwned_.get()); stagedOwner_.reset(); for (int i = 0; i < graphOwned_->count; ++i) @@ -193,7 +194,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { if (!isSmartBridgeActive()) return {}; const auto health = splitAdapter_.snapshot (deviceManager_.getCurrentAudioDevice()); - if (health.captureCallbacks < 2 || health.captureAgeUs < 3000000u) + if (!health.captureStopped && health.captureAgeUs < 3000000u) return {}; const auto fallbackError = disableSmartBridge(); return "Smart bridge capture silent for >3 seconds: automatic direct fallback" @@ -624,6 +625,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const bool split = isSmartBridgeActive(); o->setProperty ("smartMode", split ? "DUAL_CLOCK_BRIDGED" : "DIRECT_JUCE"); o->setProperty ("smartTargetLatencyMs", smartTargetMs_.load()); + o->setProperty ("smartClockStatus", split + ? "TWO_REAL_JUCE_STREAMS_RENDER_MASTER_FIR_ASRC" + : "LEGACY_SINGLE_JUCE_DEVICE_NO_ADDITIONAL_SRC"); + o->setProperty ("smartFallbackIsAutomatic", true); if (split) { const auto b = splitAdapter_.snapshot (d); @@ -635,6 +640,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("bridgeFillFrames", static_cast (b.fifo.fillFrames)); o->setProperty ("bridgeCorrectionPpm", b.fifo.correctionPpm); o->setProperty ("bridgeCaptureCallbacks", static_cast (b.captureCallbacks)); + o->setProperty ("bridgeCaptureStopped", b.captureStopped); + o->setProperty ("bridgeCaptureStartCount", static_cast (b.captureStarts)); + o->setProperty ("bridgeCaptureStopCount", static_cast (b.captureStops)); o->setProperty ("bridgeCaptureAgeMs", static_cast (b.captureAgeUs) / 1000.); o->setProperty ("bridgeProducerOverflowFrames", static_cast (b.fifo.overflowFrames)); o->setProperty ("bridgeConsumerUnderflowFrames", static_cast (b.fifo.underflowFrames)); @@ -678,6 +686,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("worstCallbackGapUs", static_cast (worstCallbackGapUs_.load())); o->setProperty ("worstPluginUs", static_cast (worstPluginUs_.load())); o->setProperty ("deviceStartCount", static_cast (deviceStartCount_.load())); + o->setProperty ("renderDeviceSource", split ? "SPLIT_WASAPI_RENDER" : "JUCE_SINGLE_DEVICE"); + o->setProperty ("bridgeUnderflowMeaning", "HOST_CAPTURE_FIFO_READ_STARVATION_NOT_HARDWARE_RENDER_XRUN"); + o->setProperty ("bridgeOverflowMeaning", "HOST_CAPTURE_FIFO_DROP_NEWEST_NOT_DRIVER_XRUN"); o->setProperty ("deviceStopCount", static_cast (deviceStopCount_.load())); juce::Array pluginTimings; for (int i = 0; i < graphOwned_->count; ++i) From ecc60e4df13f573a11801df79fb53f53283757a9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 19:54:37 +0700 Subject: [PATCH 05/25] feat(P0): AUTO startup, stable/low/direct profiles, watchdog rollback, diagnostic and persistent setup integrity --- src/Main.cpp | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 82 insertions(+), 2 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 6051c8523..b360fa153 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -118,6 +118,20 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr auto saved = juce::XmlDocument::parse (settingsDirectory().getChildFile ("audio-devices.xml")); startupError_ = engine_.start (saved.get()); engine_.devices().addChangeListener (this); + // AUTO is default. Explicit DIRECT persists across reboots, without + // affecting the old ASIO direct path or the approved mixer GUI. + const auto choice = settingsDirectory().getChildFile ("smart-audio-profile.txt") + .loadFileAsString().trim().toUpperCase(); + if (choice == "DIRECT" || choice == "STABLE" || choice == "LOW_LATENCY") + audioProfileChoice_ = choice; + if (startupError_.isEmpty() && audioProfileChoice_ != "DIRECT") + { + const auto smartError = audioProfileChoice_ == "AUTO" + ? engine_.configureStartupAuto() + : engine_.enableSmartBridge (audioProfileChoice_ == "STABLE" ? 40. : 12.); + diagnostics_.record (smartError.isEmpty() ? "SMART_AUTO_START" : "SMART_AUTO_FALLBACK", + smartError.isEmpty() ? audioProfileChoice_ : smartError); + } diagnostics_.record ("STARTUP", startupError_.isEmpty() ? "Audio device initialized" : startupError_); browser_.goToURL (juce::WebBrowserComponent::getResourceProviderRoot()); startTimerHz (12); @@ -152,6 +166,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr bool setupLaunching_ = false; unsigned int timerTicks_ = 0; bool deviceSettingsDirty_ = false; + juce::String audioProfileChoice_ {"AUTO"}; juce::var pendingPresetUI_; juce::String pendingPresetName_; @@ -298,7 +313,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr result.preallocateBytes (64 * 1024); result << "ARSONMIX / SMART AUDIO DIAGNOSTIC REPORT v2\n"; result << "Timestamp: " << juce::Time::getCurrentTime().toISO8601 (true) << "\n"; - result << "Build: experimental-P0 clock-instrumentation / native JUCE 8.0.15\n"; + result << "Build: ArSonMix P0 independent capture/render JUCE 8.0.15\n"; + result << "User profile: " << audioProfileChoice_ << "\n"; result << "Platform: " << juce::SystemStats::getOperatingSystemName() << "\n"; result << "CPU: " << juce::SystemStats::getCpuModel() << "\n"; result << "Logical cores: " << juce::SystemStats::getNumCpus() @@ -349,8 +365,47 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr browser_.emitEventIfBrowserIsVisible ("arMixDiagnosticReportCopied", juce::var (response.release())); emitNotice ("Audio report copied! Paste it directly into the engineering chat."); } + else if (action == "smartAudioProfile") + { + const auto request = value.toString().toUpperCase(); + if (request != "AUTO" && request != "STABLE" + && request != "LOW_LATENCY" && request != "DIRECT") + return emitNotice ("Unknown Smart Audio profile", true); + if (engine_.hasTemporaryDiagnosticDevice()) + { + const auto error = engine_.setDiagnosticRoute (armix::diagnostics::Route::normal); + if (error.isNotEmpty()) return emitNotice (error, true); + } + if (engine_.hasSmartBridgeSetup()) + { + const auto error = engine_.disableSmartBridge(); + if (error.isNotEmpty()) return emitNotice (error, true); + } + juce::String error; + if (request == "AUTO") error = engine_.configureStartupAuto(); + else if (request == "STABLE") error = engine_.enableSmartBridge (40.); + else if (request == "LOW_LATENCY") error = engine_.enableSmartBridge (12.); + if (error.isNotEmpty()) + { + diagnostics_.record ("SMART_PROFILE_FAIL", request + " | " + error); + return emitNotice (error + " | running safe JUCE direct fallback", true); + } + audioProfileChoice_ = request; + if (!settingsDirectory().getChildFile ("smart-audio-profile.txt") + .replaceWithText (audioProfileChoice_)) + diagnostics_.record ("SMART_PROFILE_SAVE_FAIL", audioProfileChoice_); + diagnostics_.record ("SMART_PROFILE_SELECTED", request + " | " + + juce::JSON::toString (engine_.status(), false)); + deviceSettingsDirty_ = true; + emitNotice ("Smart Audio profile: " + request); + } else if (action == "audioSetup") { + if (engine_.hasSmartBridgeSetup()) + { + const auto error = engine_.disableSmartBridge(); + if (error.isNotEmpty()) return emitNotice (error, true); + } // One-sided device routes are temporary and must never leak into // normal user configuration or the persisted audio-devices.xml. if (engine_.hasTemporaryDiagnosticDevice()) @@ -371,6 +426,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr else if (selected == "DRY_THROUGH") route = Route::dryThrough; else if (selected != "NORMAL") return emitNotice ("Unsupported diagnostic mode", true); if (audioSetupWindow_ != nullptr) audioSetupWindow_->setVisible (false); + if (engine_.hasSmartBridgeSetup()) + { + const auto restoreError = engine_.disableSmartBridge(); + if (restoreError.isNotEmpty()) return emitNotice (restoreError, true); + } const auto error = engine_.setDiagnosticRoute (route); if (error.isNotEmpty()) { @@ -381,6 +441,16 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (route == Route::normal) deviceSettingsDirty_ = true; diagnostics_.record ("AUDIO_TEST_MODE", selected + " | " + juce::JSON::toString (engine_.status(), false)); + if (route == Route::normal && audioProfileChoice_ != "DIRECT") + { + // A diagnostics run is a deliberate interruption. Re-arm only + // after the original combined endpoint has been restored. + const auto smartError = audioProfileChoice_ == "AUTO" + ? engine_.configureStartupAuto() + : engine_.enableSmartBridge (audioProfileChoice_ == "STABLE" ? 40. : 12.); + if (smartError.isNotEmpty()) + diagnostics_.record ("SMART_POST_TEST_FALLBACK", smartError); + } emitNotice ("Audio diagnostic: " + selected + ". Use low headphone volume and MARK CRACKLE on audible faults."); } @@ -577,6 +647,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void timerCallback() override { ++timerTicks_; + if (timerTicks_ % 12 == 0) + { + const auto health = engine_.pollSmartHealth(); + if (health.isNotEmpty()) + { + diagnostics_.record ("SMART_WATCHDOG_FALLBACK", health); + emitNotice (health, true); + } + } if (engine_.finalizeGraphSwitch()) { diagnostics_.record ("GRAPH_SWAP_ACK", pendingPresetName_); @@ -596,7 +675,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr deviceSettingsDirty_ = false; // DeviceManager signals even when a temporary capture-only / // output-only route is selected. Never persist that test route. - if (!engine_.hasTemporaryDiagnosticDevice()) + if (!engine_.hasTemporaryAudioRouting()) if (auto xml = engine_.devices().createStateXml()) { const auto text = xml->toString(); @@ -620,6 +699,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (catalog_.busy() && timerTicks_ % 3 == 0) emitScanProgress(); auto state = engine_.status(); + state.getDynamicObject()->setProperty ("smartUserProfile", audioProfileChoice_); state.getDynamicObject()->setProperty ("diagnosticsDropped", static_cast (diagnostics_.lostRecords())); state.getDynamicObject()->setProperty ("diagnosticsTruncated", From a12ee79c24aef21d6d8206497cc4bafb06803657 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 19:55:08 +0700 Subject: [PATCH 06/25] feat(P0): user-visible AUTO/STABLE/LOW LATENCY/DIRECT profiles and real FIFO/drift telemetry --- web/monitor.js | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/web/monitor.js b/web/monitor.js index 1d56167f7..bb680ed68 100644 --- a/web/monitor.js +++ b/web/monitor.js @@ -19,7 +19,9 @@ "#arDiagnosticMode{color:#d9eaf3;background:#142a36;border:1px solid #57849a;border-radius:4px;padding:6px;font-size:11px}" + "#arDiagnosticMark{color:#f9e5ca;background:#503926;border:1px solid #b9854a;border-radius:4px;padding:7px 10px;cursor:pointer}" + "#arDiagnosticCopy{color:#e1f7f4;background:#166052;border:1px solid #34c8ac;border-radius:4px;padding:7px 12px;cursor:pointer}" + - "#arDiagnosticCopyStatus{color:#8cdec9;font-size:10px}"; + "#arDiagnosticCopyStatus{color:#8cdec9;font-size:10px}" + + "#arSmartProfile{background:#142a36;color:#c5eaf6;border:1px solid #598496;border-radius:4px;padding:6px;font-size:11px}" + + "#arSmartStats{margin:7px 0 2px;color:#9de4cd;font:11px monospace;overflow-wrap:anywhere}"; document.head.appendChild(css); // Signal Check is declared in the permanent toolbar; footer holds status only. const overlay = document.createElement("div"); @@ -34,6 +36,11 @@ '
' + '' + '
' + + '
' + + '
' + + '
' + '
' + '