diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 16fc7ec12..246e0aa42 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -43,6 +43,7 @@ jobs: node --test tests/smart_audio_ard_contract_test.mjs node --test tests/p0_diagnostic_contract_test.mjs node --test tests/smart_audio_diagnostic_contract_test.mjs + node --test tests/p0_live_split_contract_test.mjs - name: Configure Windows x64 shell: pwsh run: > @@ -51,7 +52,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 ARMixRTTests ARMixPresetTests ARMixDiagnosticTests ARMixClockBridgeTests ARMixHealthTests ARMixPolicyTests --parallel 2 + run: cmake --build build --config Release --target ARMixConsole ARMixRTTests ARMixPresetTests ARMixDiagnosticTests ARMixClockBridgeTests ARMixHealthTests ARMixPolicyTests ARMixRecoveryTests ARMixSplitTelemetryTests ARMixIndependentPipelineTests --parallel 2 - name: Test realtime control primitives run: ctest --test-dir build -C Release --output-on-failure - name: Package native executable diff --git a/CMakeLists.txt b/CMakeLists.txt index ef3a1c7f5..869cbbdb1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,7 +19,7 @@ juce_add_gui_app(ARMixConsole juce_add_binary_data(ARMixAssets SOURCES web/index.html web/styles.css web/app.js web/bridge.js web/monitor.js) -target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/PluginCatalog.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h) +target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/PluginCatalog.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h engine/device/DeviceRecoveryPolicy.h engine/device/SplitStreamTelemetry.h engine/device/IndependentClockPipeline.h engine/device/JuceIndependentDeviceAdapter.h) target_compile_definitions(ARMixConsole PRIVATE JUCE_WEB_BROWSER=1 JUCE_USE_WIN_WEBVIEW2=1 @@ -40,6 +40,15 @@ target_link_libraries(ARMixConsole PRIVATE include(CTest) if(BUILD_TESTING) + add_executable(ARMixIndependentPipelineTests tests/independent_clock_pipeline_test.cpp) + target_compile_features(ARMixIndependentPipelineTests PRIVATE cxx_std_20) + add_test(NAME IndependentClockPipeline COMMAND ARMixIndependentPipelineTests) + add_executable(ARMixSplitTelemetryTests tests/split_stream_telemetry_test.cpp) + target_compile_features(ARMixSplitTelemetryTests PRIVATE cxx_std_20) + add_test(NAME SplitStreamTelemetry COMMAND ARMixSplitTelemetryTests) + add_executable(ARMixRecoveryTests tests/device_recovery_policy_test.cpp) + target_compile_features(ARMixRecoveryTests PRIVATE cxx_std_20) + add_test(NAME DeviceRecoveryPolicy COMMAND ARMixRecoveryTests) add_executable(ARMixPolicyTests tests/audio_profile_policy_test.cpp) target_compile_features(ARMixPolicyTests PRIVATE cxx_std_20) add_test(NAME CapabilityAudioProfilePolicy COMMAND ARMixPolicyTests) diff --git a/docs/P0_DEVICE_RECOVERY_INTEGRATION_HANDOFF.md b/docs/P0_DEVICE_RECOVERY_INTEGRATION_HANDOFF.md new file mode 100644 index 000000000..11d2bd762 --- /dev/null +++ b/docs/P0_DEVICE_RECOVERY_INTEGRATION_HANDOFF.md @@ -0,0 +1,27 @@ +# P0 backend recovery handoff — generation-safe control plane + +**Updated:** 2026-10-25 +**Reference:** [P0 issue #15](https://github.com/masarray/arsonmix/issues/15), [ARD v1](ARD_SMART_AUDIO_ENGINE_V1_2026-10-25.md), [Smart Audio implementation blueprint](SMART_AUDIO_ENGINE_IMPLEMENTATION_BLUEPRINT.md) + +## Implemented in this engineering tranche + +- Pure `DeviceRecoveryPolicy` state machine for the message/control thread. States: stopped, discovering, preparing, running, degraded, recovering, failed. Every prepare/discovery completion must include the generation issued by its start. A late completion for a retired device is rejected rather than re-arming invalid PCM pointers. +- On endpoint loss: require render silence and device retirement **before** acquiring replacement. Retry uses bounded backoff 100 ms–10 seconds, maximum eight consecutive failures, and explicit terminal failure. +- A configuration is **eligible** for stable persistence only after 30 seconds of healthy callbacks. This is a policy primitive, not a claim that audible playback is clean. +- Pure `SplitStreamTelemetry`: lock-free independent capture/render frames, dropped input frames, bridge starvation frames and invalid-buffer counters, with separate generation numbers. These are not equivalent to Windows driver output xruns; report source provenance. +- `IndependentClockPipeline` now connects two **independently invoked callback interfaces** to the prepared FIR/ASRC and telemetry. It is JUCE-independent and tested against separate synthetic source/render callback frame counts. +- `JuceIndependentDeviceAdapter` now implements two actually separate JUCE AudioDeviceManager callback hosts: one input-only clock, one output-only clock, capture FIFO producer, render-master FIR consumer and bounded render blocks. Its source compiles into the Windows app and an explicitly opt-in **EXPERIMENTAL 0-FX** route activates separate one-sided JUCE device managers using controlled joined-device shutdown, bridge preparation and rollback. It is NOT a general plugin-host backend, nor hardware-certified. Independent capture rate is negotiated separately; output uses selected render period. +- Release-active CTests for generation cancellation, state transitions, bounded delays, stable eligibility, recording different capture/render frame rates, and FIFO overflow/starvation/re-prime. + +## Production integration is **not yet complete** + +The `DeviceRecoveryPolicy` planner is not yet wired to runtime AUTO/STABLE control. The default JUCE joined route still cannot expose independent clocks; the optional Smart I/O 0-FX path uses separately opened capture/render device managers and reports real bridge frame starvation. The true P0 remaining acceptance scope is: + +1. Replace the current manual Smart I/O 0-FX opt-in with capability-driven AUTO/STABLE selection and a device-identity/period evidence provider. The first adapter has independent callbacks but no Windows IAudioClient3 period/clock service verification or event-driven render-padding instrumentation. +2. Extend the split route beyond zero FX through a safe, independently prepared VST3 graph handoff and ensure direct ASIO/shared-clock fast path remains free of extra SRC. The 25 ms bridge target is experimental, NOT a universal low-latency claim. +3. Attach this `DeviceRecoveryPolicy` to a real control executor that serializes COM/device change transitions, invalidates and drains old callbacks, safely owns graph/plugin lifetimes, and makes stable profile persistence transactional. +4. Integrate `SplitStreamTelemetry` into native **COPY FULL REPORT**: actual split route now exports FIFO occupancy, source frame drop, bridge underflow/priming frames, and ppm; real driver render underruns remain unavailable. Host callback timing is not an xrun. +5. Add deterministic rate-mismatch jitter and device restart failure tests plus resampling fidelity/latency/CPU acceptance gates; run automated Windows/MSVC and GUI checks. +6. Perform one consolidated hardware acceptance campaign after P0 stages are integrated. Until then mark P0 #15 OPEN and physical crackling **unresolved**. + +**User workflow:** no recurring manual tests while the engineering work proceeds. An experimental **ENABLE SMART I/O · 0 FX** control is in the native SIGNAL CHECK overlay only, and COPY FULL REPORT includes its actual activation state. This control is *not* the final AUTO/STABLE selector. The approved mixer GUI v0.8 remains locked. diff --git a/engine/device/DeviceRecoveryPolicy.h b/engine/device/DeviceRecoveryPolicy.h new file mode 100644 index 000000000..00f08f89d --- /dev/null +++ b/engine/device/DeviceRecoveryPolicy.h @@ -0,0 +1,150 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include + +namespace armix::device +{ +// Pure control-thread state machine. All callbacks pass generation tokens; +// delayed asynchronous completions from retired devices cannot revive a stale +// session. This module NEVER opens devices or touches the audio callback. +enum class SessionState : std::uint8_t +{ + stopped, discovering, preparing, running, degraded, recovering, failed +}; +enum class DeviceEvent : std::uint8_t +{ + start, discoveryOk, discoveryFailed, preparationOk, preparationFailed, + callbackHealthy, instability, endpointLost, recover, stop +}; +enum class RecoveryAction : std::uint8_t +{ + none, enumerateDevices, prepareCandidate, publishCandidate, + silenceAndRetire, scheduleRetry, persistStable, reportFailure +}; +struct RecoveryDecision +{ + SessionState state = SessionState::stopped; + RecoveryAction action = RecoveryAction::none; + std::uint64_t generation = 0; + std::uint64_t retryAfterMs = 0; + bool accepted = false; +}; +class DeviceRecoveryPolicy final +{ +public: + // One controller, one control-thread owner. nowMs must be monotonic. + RecoveryDecision apply (DeviceEvent event, std::uint64_t token, std::uint64_t nowMs) noexcept + { + if (event == DeviceEvent::stop) + { + ++generation_; state_ = SessionState::stopped; consecutiveFailures_ = 0; + stabilityArmed_ = false; stableSince_ = 0; nextRetry_ = 0; + return result (RecoveryAction::silenceAndRetire, 0, true); + } + if (event == DeviceEvent::start) + { + if (state_ != SessionState::stopped && state_ != SessionState::failed) + return result (RecoveryAction::none, 0, false); + ++generation_; state_ = SessionState::discovering; + consecutiveFailures_ = 0; stabilityArmed_ = false; stableSince_ = 0; nextRetry_ = 0; + return result (RecoveryAction::enumerateDevices, 0, true); + } + if (token != generation_) return result (RecoveryAction::none, 0, false); + + switch (event) + { + case DeviceEvent::discoveryOk: + if (state_ != SessionState::discovering) break; + state_ = SessionState::preparing; + return result (RecoveryAction::prepareCandidate, 0, true); + case DeviceEvent::preparationOk: + if (state_ != SessionState::preparing) break; + state_ = SessionState::running; + stableSince_ = nowMs; stabilityArmed_ = true; + return result (RecoveryAction::publishCandidate, 0, true); + case DeviceEvent::callbackHealthy: + if (state_ == SessionState::running && stabilityArmed_ + && nowMs >= stableSince_ && nowMs - stableSince_ >= 30000) + { + stabilityArmed_ = false; + consecutiveFailures_ = 0; // reset only after sustained health + return result (RecoveryAction::persistStable, 0, true); + } + if (state_ == SessionState::degraded) + { + state_ = SessionState::running; + stableSince_ = nowMs; stabilityArmed_ = true; + return result (RecoveryAction::none, 0, true); + } + break; + case DeviceEvent::instability: + if (state_ == SessionState::running) + { + state_ = SessionState::degraded; stabilityArmed_ = false; stableSince_ = 0; + return result (RecoveryAction::none, 0, true); + } + break; + case DeviceEvent::endpointLost: + if (state_ == SessionState::running || state_ == SessionState::degraded + || state_ == SessionState::preparing || state_ == SessionState::discovering) + { + ++consecutiveFailures_; ++generation_; + stabilityArmed_ = false; stableSince_ = 0; + if (consecutiveFailures_ >= 8) + { + state_ = SessionState::failed; nextRetry_ = 0; + return result (RecoveryAction::silenceAndRetire, 0, true); + } + state_ = SessionState::recovering; + const auto delay = backoffFor (consecutiveFailures_); + nextRetry_ = nowMs + delay; + return result (RecoveryAction::silenceAndRetire, delay, true); + } + break; + case DeviceEvent::discoveryFailed: + case DeviceEvent::preparationFailed: + if (state_ == SessionState::discovering || state_ == SessionState::preparing) + { + ++consecutiveFailures_; + if (consecutiveFailures_ >= 8) + { + ++generation_; state_ = SessionState::failed; nextRetry_ = 0; + return result (RecoveryAction::reportFailure, 0, true); + } + ++generation_; state_ = SessionState::recovering; + // Bounded backoff, 100ms to 10s; no uncontrolled spin. + const auto delay = backoffFor (consecutiveFailures_); + nextRetry_ = nowMs + delay; + return result (RecoveryAction::scheduleRetry, delay, true); + } + break; + case DeviceEvent::recover: + if (state_ == SessionState::recovering && nowMs >= nextRetry_) + { + state_ = SessionState::discovering; + return result (RecoveryAction::enumerateDevices, 0, true); + } + break; + default: break; + } + return result (RecoveryAction::none, 0, false); + } + std::uint64_t generation() const noexcept { return generation_; } + SessionState state() const noexcept { return state_; } + std::uint64_t nextRetryMs() const noexcept { return nextRetry_; } +private: + static std::uint64_t backoffFor (unsigned consecutive) noexcept + { + const auto shift = std::min (consecutive - 1, 7u); + return std::min (10000, 100ull << shift); + } + RecoveryDecision result (RecoveryAction action, std::uint64_t delay, bool accepted) const noexcept + { return {state_,action,generation_,delay,accepted}; } + SessionState state_ = SessionState::stopped; + std::uint64_t generation_ = 0, stableSince_ = 0, nextRetry_ = 0; + unsigned consecutiveFailures_ = 0; + bool stabilityArmed_ = false; +}; +} // namespace armix::device diff --git a/engine/device/IndependentClockPipeline.h b/engine/device/IndependentClockPipeline.h new file mode 100644 index 000000000..e9b498271 --- /dev/null +++ b/engine/device/IndependentClockPipeline.h @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "AdaptiveClockBridge.h" +#include "SplitStreamTelemetry.h" + +namespace armix::device +{ +// Concrete producer/consumer audio pipeline for *two independently clocked* +// callbacks. Ownership, device lifecycle and stream-format adaptation belong +// to a Windows backend adapter. This is intentionally JUCE-independent. +// prepare() only with both callbacks stopped; capture()/render() RT-safe. +class IndependentClockPipeline final +{ +public: + bool prepare (double captureHz, double renderHz, int channels, + int fifoFrames, double targetLatencyMs) + { + if (!bridge_.prepare(captureHz,renderHz,channels,fifoFrames,targetLatencyMs)) + return false; + telemetry_.sourceStarted(); + telemetry_.renderStarted(); + return true; + } + int capture (const float* const* input,int channels,int frames) noexcept + { + const int written=bridge_.push(input,channels,frames); + telemetry_.captured(frames,written); + return written; + } + void render (float* const* output,int channels,int frames) noexcept + { + const auto before=bridge_.status().underflowFrames; + bridge_.pull(output,channels,frames); + const auto after=bridge_.status().underflowFrames; + const auto delta=after>=before?after-before:0; + telemetry_.rendered(frames,static_cast( + std::min(delta,frames>0?static_cast(frames):0))); + } + AdaptiveClockBridge::Status bridgeStatus() const noexcept + { + return bridge_.status(); + } + SplitStreamSnapshot streamStatus() const noexcept + { + return telemetry_.snapshot(); + } +private: + AdaptiveClockBridge bridge_; + SplitStreamTelemetry telemetry_; +}; +} // namespace armix::device diff --git a/engine/device/JuceIndependentDeviceAdapter.h b/engine/device/JuceIndependentDeviceAdapter.h new file mode 100644 index 000000000..d6d5388f6 --- /dev/null +++ b/engine/device/JuceIndependentDeviceAdapter.h @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include "IndependentClockPipeline.h" +#include +#include +#include + +namespace armix::device +{ +// Real JUCE two-manager transport feasibility adapter: independently opened +// capture and render devices feed the same preallocated render-master bridge. +// Deliberately NOT activated by the production LiveAudioEngine until control- +// plane setup migration, VST3 ownership and physical rollback are validated. +// No backend/device calls, dynamic allocation, COM, or GUI access in callbacks. +// A single control thread owns prepare/start/stop; callbacks are drained by +// AudioDeviceManager::removeAudioCallback before any resource is reset. +class JuceIndependentDeviceAdapter final +{ +public: + JuceIndependentDeviceAdapter() : captureCallback_(*this), renderCallback_(*this) {} + ~JuceIndependentDeviceAdapter() { stop(); } + JuceIndependentDeviceAdapter(const JuceIndependentDeviceAdapter&) = delete; + JuceIndependentDeviceAdapter& operator=(const JuceIndependentDeviceAdapter&) = delete; + + // The original application must already have stopped its joined device + // BEFORE entering this method. Never open two exclusive instances of a + // capture/render device without a controlled migration transaction. + juce::String prepare (const juce::String& deviceType, + const juce::AudioDeviceManager::AudioDeviceSetup& selection, + double fifoTargetMs = 25.0) + { + stop(); + if (selection.inputDeviceName.isEmpty() || selection.outputDeviceName.isEmpty()) + return "Select both input and output endpoints before split-mode setup"; + auto err = captureManager_.initialise (1, 0, nullptr, false); + if (err.isNotEmpty()) return fail (err); + err = renderManager_.initialise (0, 2, nullptr, false); + if (err.isNotEmpty()) return fail (err); + captureManager_.setCurrentAudioDeviceType (deviceType, false); + renderManager_.setCurrentAudioDeviceType (deviceType, false); + if (captureManager_.getCurrentAudioDeviceType() != deviceType || + renderManager_.getCurrentAudioDeviceType() != deviceType) + return fail ("Requested backend type is unavailable for one-sided I/O"); + + auto captureConfig = captureManager_.getAudioDeviceSetup(); + captureConfig.inputDeviceName = selection.inputDeviceName; + captureConfig.outputDeviceName.clear(); + captureConfig.outputChannels.clear(); + captureConfig.useDefaultOutputChannels = false; + // Independent capture clock: use an actual driver-supported mode; + // forcing the render device rate here defeats separate-clock probing. + captureConfig.sampleRate = 0; + captureConfig.bufferSize = 0; + err = captureManager_.setAudioDeviceSetup (captureConfig, false); + if (err.isNotEmpty()) return fail ("Capture: " + err); + + auto renderConfig = renderManager_.getAudioDeviceSetup(); + renderConfig.inputDeviceName.clear(); + renderConfig.inputChannels.clear(); + renderConfig.useDefaultInputChannels = false; + renderConfig.outputDeviceName = selection.outputDeviceName; + renderConfig.sampleRate = selection.sampleRate; + renderConfig.bufferSize = selection.bufferSize; + err = renderManager_.setAudioDeviceSetup (renderConfig, false); + if (err.isNotEmpty()) return fail ("Render: " + err); + + auto* in = captureManager_.getCurrentAudioDevice(); + auto* out = renderManager_.getCurrentAudioDevice(); + if (in == nullptr || out == nullptr || + in->getActiveOutputChannels().countNumberOfSetBits() != 0 || + out->getActiveInputChannels().countNumberOfSetBits() != 0 || + in->getActiveInputChannels().countNumberOfSetBits() < 1 || + out->getActiveOutputChannels().countNumberOfSetBits() < 1) + return fail ("Driver failed to expose independent capture/render endpoint channels"); + + if (!pipeline_.prepare (in->getCurrentSampleRate(), out->getCurrentSampleRate(), + 2, 8192, fifoTargetMs)) + return fail ("Separate-stream rates or FIFO capacity are unsupported"); + prepared_ = true; + return {}; + } + + juce::String start (juce::AudioIODeviceCallback& processor) + { + if (!prepared_ || running_) return "Split adapter is not prepared or already running"; + processor_ = &processor; + // Attach capture producer first, then render consumer, ensuring source + // clock starts filling FIFO before output becomes audible. + captureManager_.addAudioCallback (&captureCallback_); + captureAttached_ = true; + renderManager_.addAudioCallback (&renderCallback_); + renderAttached_ = true; + running_ = true; + return {}; + } + void stop() + { + // Removal synchronously drains callbacks. Render stops before producer. + if (renderAttached_) + { + renderManager_.removeAudioCallback (&renderCallback_); + renderAttached_ = false; + } + if (captureAttached_) + { + captureManager_.removeAudioCallback (&captureCallback_); + captureAttached_ = false; + } + processor_ = nullptr; + running_ = false; + renderManager_.closeAudioDevice(); + captureManager_.closeAudioDevice(); + prepared_ = false; + } + bool running() const noexcept { return running_; } // control-thread only + juce::AudioIODevice* outputDevice() const noexcept + { return renderManager_.getCurrentAudioDevice(); } + juce::AudioIODevice* inputDevice() const noexcept + { return captureManager_.getCurrentAudioDevice(); } + IndependentClockPipeline& pipeline() noexcept { return pipeline_; } + bool callbackErrorObserved() const noexcept + { return driverError_.load(std::memory_order_relaxed); } + +private: + class Capture final : public juce::AudioIODeviceCallback + { + public: + explicit Capture(JuceIndependentDeviceAdapter& owner):owner_(owner){} + void audioDeviceAboutToStart(juce::AudioIODevice*) override {} + void audioDeviceStopped() override {} + void audioDeviceError(const juce::String&) override + { owner_.driverError_.store(true,std::memory_order_relaxed); } + void audioDeviceIOCallbackWithContext(const float* const* input,int numInput, + float* const* output,int numOutput,int frames, + const juce::AudioIODeviceCallbackContext&) override + { + // A capture-only device should not have output channels; zero any + // incorrectly exposed buffer to fail closed on buggy backends. + for(int c=0;caudioDeviceAboutToStart(device); + } + void audioDeviceStopped() override + { + if(owner_.processor_) owner_.processor_->audioDeviceStopped(); + } + void audioDeviceError(const juce::String&) override + { owner_.driverError_.store(true,std::memory_order_relaxed); } + void audioDeviceIOCallbackWithContext(const float* const*,int, + float* const* outputs,int numOutputs,int numSamples, + const juce::AudioIODeviceCallbackContext& context) override + { + // Process arbitrary backend block lengths in fixed bounded chunks. + // No overflow of preallocated PCM buffers or stack pointer table. + constexpr int maxFrames=8192, maxOutputPointers=32; + for(int offset=0;offsetaudioDeviceIOCallbackWithContext( + input,2,deviceOutput,count,frames,context); + } + else for(int c=0;c,2> scratch_ {}; + juce::AudioIODeviceCallback* processor_ = nullptr; + std::atomic driverError_ {false}; + bool prepared_ = false, running_ = false; + bool captureAttached_ = false, renderAttached_ = false; +}; +} // namespace armix::device diff --git a/engine/device/SplitStreamTelemetry.h b/engine/device/SplitStreamTelemetry.h new file mode 100644 index 000000000..e1fd776a0 --- /dev/null +++ b/engine/device/SplitStreamTelemetry.h @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include + +namespace armix::device +{ +// Bounded event counters for independent source/render streams, independent +// of backend-specific driver xrun semantics. These are bridge frame counts, +// NEVER a substitute for hardware-render underrun evidence. +struct SplitStreamCounters final +{ + std::atomic captureCallbacks {0}, renderCallbacks {0}; + std::atomic captureFrames {0}, renderFrames {0}; + std::atomic captureDropFrames {0}, renderMissingFrames {0}; + std::atomic invalidBufferCallbacks {0}; + std::atomic sourceGeneration {0}, renderGeneration {0}; +}; +struct SplitStreamSnapshot +{ + std::uint64_t captureCallbacks = 0, renderCallbacks = 0; + std::uint64_t captureFrames = 0, renderFrames = 0; + std::uint64_t captureDropFrames = 0, renderMissingFrames = 0; + std::uint64_t invalidBufferCallbacks = 0; + std::uint64_t sourceGeneration = 0, renderGeneration = 0; +}; +// Control-plane observer for split device adapters. The realtime threads only +// perform bounded atomic increments; snapshots are gathered on UI thread. +class SplitStreamTelemetry final +{ +public: + void sourceStarted() noexcept { counters_.sourceGeneration.fetch_add(1,std::memory_order_relaxed); } + void renderStarted() noexcept { counters_.renderGeneration.fetch_add(1,std::memory_order_relaxed); } + void captured (int asked,int accepted) noexcept + { + counters_.captureCallbacks.fetch_add(1,std::memory_order_relaxed); + if(asked<0 || accepted<0 || accepted>asked) + { + counters_.invalidBufferCallbacks.fetch_add(1,std::memory_order_relaxed); + return; + } + counters_.captureFrames.fetch_add(static_cast(accepted),std::memory_order_relaxed); + counters_.captureDropFrames.fetch_add(static_cast(asked-accepted),std::memory_order_relaxed); + } + void rendered(int asked,int missing) noexcept + { + counters_.renderCallbacks.fetch_add(1,std::memory_order_relaxed); + if(asked<0 || missing<0 || missing>asked) + { + counters_.invalidBufferCallbacks.fetch_add(1,std::memory_order_relaxed); + return; + } + counters_.renderFrames.fetch_add(static_cast(asked),std::memory_order_relaxed); + counters_.renderMissingFrames.fetch_add(static_cast(missing),std::memory_order_relaxed); + } + SplitStreamSnapshot snapshot() const noexcept + { + return {counters_.captureCallbacks.load(std::memory_order_relaxed), + counters_.renderCallbacks.load(std::memory_order_relaxed), + counters_.captureFrames.load(std::memory_order_relaxed), + counters_.renderFrames.load(std::memory_order_relaxed), + counters_.captureDropFrames.load(std::memory_order_relaxed), + counters_.renderMissingFrames.load(std::memory_order_relaxed), + counters_.invalidBufferCallbacks.load(std::memory_order_relaxed), + counters_.sourceGeneration.load(std::memory_order_relaxed), + counters_.renderGeneration.load(std::memory_order_relaxed)}; + } +private: + SplitStreamCounters counters_; +}; +} // namespace armix::device diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index db3c0c850..867bfe28a 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -8,6 +8,7 @@ #include "LiveGraphHandoff.h" #include "DiagnosticTone.h" #include "../engine/core/RealtimeHealthHistogram.h" +#include "../engine/device/JuceIndependentDeviceAdapter.h" #include #include #include @@ -57,6 +58,69 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback ~LiveAudioEngine() override { stop(); } juce::AudioDeviceManager& devices() noexcept { return deviceManager_; } + bool isIndependentAudioActive() const noexcept { return splitAudioActive_; } + bool isIndependentAudioDriverError() const noexcept + { return splitAudioActive_ && splitAdapter_.callbackErrorObserved(); } + juce::AudioIODevice* activeOutputDevice() const noexcept + { return splitAudioActive_ ? splitAdapter_.outputDevice() : deviceManager_.getCurrentAudioDevice(); } + juce::AudioIODevice* activeInputDevice() const noexcept + { return splitAudioActive_ ? splitAdapter_.inputDevice() : deviceManager_.getCurrentAudioDevice(); } + + // CONTROL THREAD ONLY: stop/drain old callbacks before reconfiguring. + // This opt-in phase is deliberately restricted to 0 VST3, so it diagnoses + // and carries clean PCM before FX graph concurrency is introduced. + juce::String setIndependentAudioActive (bool desired) + { + if (splitAudioActive_ == desired) return {}; + if (handoff_.busy()) return "Wait for the live FX transition to finish"; + if (desired && graphOwned_->count != 0) + return "Independent-clock diagnostic currently requires an empty 0-VST3 rack"; + if (desired && (savedLiveSetup_ || diagnosticRoute() != armix::diagnostics::Route::normal)) + return "Return audio isolation mode to NORMAL before enabling Smart I/O"; + + struct SafeSwitch + { + std::atomic& flag; + explicit SafeSwitch (std::atomic& f):flag(f) + { flag.store(true,std::memory_order_release); } + ~SafeSwitch(){ flag.store(false,std::memory_order_release); } + } switching(routeReconfiguring_); + + if (desired) + { + const auto type=deviceManager_.getCurrentAudioDeviceType(); + deviceManager_.getAudioDeviceSetup(joinedBeforeSplit_); + if (joinedBeforeSplit_.inputDeviceName.isEmpty() || + joinedBeforeSplit_.outputDeviceName.isEmpty()) + return "Select both endpoints via AUDIO SETUP before enabling Smart I/O"; + detach(); + deviceManager_.closeAudioDevice(); + auto error=splitAdapter_.prepare(type,joinedBeforeSplit_,25.0); + if(error.isEmpty()) error=splitAdapter_.start(*this); + if(error.isNotEmpty()) + { + splitAdapter_.stop(); + const auto restore=deviceManager_.setAudioDeviceSetup(joinedBeforeSplit_,false); + if(restore.isEmpty()) attach(); + else setOutputMuted(true); + return "Split I/O not available: "+error+ + (restore.isNotEmpty()?" | Original audio restore failed: "+restore:juce::String()); + } + splitAudioActive_=true; + return {}; + } + + splitAdapter_.stop(); // drain both independent device callbacks first + splitAudioActive_=false; + const auto error=deviceManager_.setAudioDeviceSetup(joinedBeforeSplit_,false); + if(error.isNotEmpty()) + { + setOutputMuted(true); // never claim restored while no device is open + return "Could not restore joined audio routing: "+error; + } + attach(); + return {}; + } juce::String start (const juce::XmlElement* savedSettings = nullptr) { @@ -73,6 +137,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void stop() { + if (splitAudioActive_) + { + splitAdapter_.stop(); + splitAudioActive_ = false; + } detach(); handoff_.resetAfterStop (graphOwned_.get()); stagedOwner_.reset(); @@ -97,6 +166,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { using Route = armix::diagnostics::Route; if (handoff_.busy()) return "Finish the pending FX graph transition first"; + if (splitAudioActive_) return "Disable Smart I/O before using isolation modes"; if (wanted == diagnosticRoute_.load (std::memory_order_acquire) && !(wanted == Route::normal && savedLiveSetup_)) return {}; if (wanted < Route::normal || wanted > Route::captureOnly) @@ -252,6 +322,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String addVst3 (const juce::String& filename, int uid, const juce::String& catalogId) { + if (splitAudioActive_) return "Return to joined I/O before loading VST3 effects"; if (handoff_.busy()) return "FX graph transition in progress; retry shortly"; if (graphOwned_->count >= maxFx) return "FX Rack is full (maximum 8 VST3 effects)"; auto* device = deviceManager_.getCurrentAudioDevice(); @@ -302,6 +373,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // exactly once, no plugin state methods ever execute on the audio thread. juce::String captureSnapshot (armix::storage::Snapshot& snapshot) { + if (splitAudioActive_) return "Return to joined I/O before saving effect graphs"; if (!isOutputMuted()) return "Mute hardware output before saving a native preset"; if (handoff_.busy()) return "Finish pending FX graph transition before saving"; snapshot.effects.clear(); @@ -486,8 +558,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::var status() { auto o = std::make_unique(); - auto* d = deviceManager_.getCurrentAudioDevice(); - o->setProperty ("connected", d != nullptr); + auto* d = activeOutputDevice(); + auto* captureDevice = activeInputDevice(); + o->setProperty ("connected", d != nullptr && captureDevice != nullptr); o->setProperty ("driver", deviceManager_.getCurrentAudioDeviceType()); o->setProperty ("device", d ? d->getName() : "No device"); o->setProperty ("rate", d ? d->getCurrentSampleRate() : 0.0); @@ -509,10 +582,32 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("lateCallbackIntervals", static_cast (lateCallbackIntervals_.load())); o->setProperty ("testOutputFrames", static_cast (testOutputFrames_.load())); o->setProperty ("testCaptureFrames", static_cast (testCaptureFrames_.load())); + // Capability truth: building the split pipeline and recovery policy does + // not mean the current JUCE AudioDeviceManager uses either one. + o->setProperty ("p0BackendMode", splitAudioActive_ ? "JUCE_SPLIT_BRIDGED_0FX" : "JUCE_JOINED_CALLBACK"); + o->setProperty ("p0IndependentClockBridgeActive", splitAudioActive_); + o->setProperty ("p0SplitDriverError", isIndependentAudioDriverError()); + if(splitAudioActive_) + { + const auto bridge=splitAdapter_.pipeline().bridgeStatus(); + const auto streams=splitAdapter_.pipeline().streamStatus(); + o->setProperty ("p0FifoFrames",static_cast(bridge.fillFrames)); + o->setProperty ("p0CaptureDropFrames",static_cast(streams.captureDropFrames)); + o->setProperty ("p0BridgeUnderflowFrames",static_cast(streams.renderMissingFrames)); + o->setProperty ("p0SrcCorrectionPpm",bridge.correctionPpm); + o->setProperty ("p0PrimingFrames",static_cast(bridge.primingFrames)); + o->setProperty ("p0CaptureCallbacks",static_cast(streams.captureCallbacks)); + o->setProperty ("p0RenderCallbacks",static_cast(streams.renderCallbacks)); + } + o->setProperty ("p0AutomaticDeviceRecoveryActive", false); + o->setProperty ("p0PhysicalOutputUnderrunsObservable", false); o->setProperty ("renderUnderrunSource", "UNAVAILABLE_THROUGH_CURRENT_JUCE_AUDIODEVICE"); // AudioIODevice::getXRunCount is backend-specific, not comprehensive. // Pinned JUCE WASAPI reports input capture discontinuity flags only. - const int reported = d != nullptr ? d->getXRunCount() : -1; + // In split mode WASAPI capture discontinuities belong to the INPUT + // endpoint, not the render-master output endpoint. + auto* xrunSource = splitAudioActive_ ? captureDevice : d; + const int reported = xrunSource != nullptr ? xrunSource->getXRunCount() : -1; o->setProperty ("backendXrunCount", reported >= 0 ? juce::var (reported) : juce::var()); const auto type = deviceManager_.getCurrentAudioDeviceType(); o->setProperty ("backendXrunMeaning", reported < 0 ? "UNAVAILABLE" @@ -520,9 +615,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback : "DRIVER_DEFINED"); juce::AudioDeviceManager::AudioDeviceSetup setup; deviceManager_.getAudioDeviceSetup (setup); - o->setProperty ("inputDevice", setup.inputDeviceName); - o->setProperty ("outputDevice", setup.outputDeviceName); - o->setProperty ("deviceInputChannels", d ? d->getActiveInputChannels().countNumberOfSetBits() : 0); + o->setProperty ("inputDevice", splitAudioActive_ ? joinedBeforeSplit_.inputDeviceName : setup.inputDeviceName); + o->setProperty ("outputDevice", splitAudioActive_ ? joinedBeforeSplit_.outputDeviceName : setup.outputDeviceName); + o->setProperty ("deviceInputChannels", captureDevice ? captureDevice->getActiveInputChannels().countNumberOfSetBits() : 0); o->setProperty ("deviceOutputChannels", d ? d->getActiveOutputChannels().countNumberOfSetBits() : 0); o->setProperty ("callbackInputChannels", callbackInputs_.load()); o->setProperty ("callbackOutputChannels", callbackOutputs_.load()); @@ -574,6 +669,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback private: static constexpr int maxFrames = 8192; juce::AudioDeviceManager deviceManager_; + armix::device::JuceIndependentDeviceAdapter splitAdapter_; + juce::AudioDeviceManager::AudioDeviceSetup joinedBeforeSplit_; + bool splitAudioActive_ = false; // JUCE message/control thread only juce::AudioPluginFormatManager formats_; std::unique_ptr graphOwned_ {std::make_unique()}; std::unique_ptr stagedOwner_; diff --git a/src/Main.cpp b/src/Main.cpp index 6051c8523..7ecc36b3f 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -293,7 +293,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr juce::String makeAudioReport() { const auto status = engine_.status(); - auto* device = engine_.devices().getCurrentAudioDevice(); + auto* device = engine_.activeOutputDevice(); + auto* captureDevice = engine_.activeInputDevice(); juce::String result; result.preallocateBytes (64 * 1024); result << "ARSONMIX / SMART AUDIO DIAGNOSTIC REPORT v2\n"; @@ -309,7 +310,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr result << "=== DEVICE CAPABILITIES (backend-reported) ===\n"; if (device != nullptr) { - result << "Input latency: " << device->getInputLatencyInSamples() + result << "Input latency: " << (captureDevice ? captureDevice->getInputLatencyInSamples() : -1) << " frames | Output latency: " << device->getOutputLatencyInSamples() << " frames | Native buffer: " << device->getCurrentBufferSizeSamples() << " frames\n"; result << "Reported sample rates: "; @@ -337,7 +338,28 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto value = args.getProperty ("value", {}); const int slot = static_cast (args.getProperty ("slot", -1)); - if (action == "copyDiagnosticReport") + if (engine_.isIndependentAudioActive() && + (action == "addCatalog" || action == "presetSave" || + action == "presetLoad" || action == "fxRemove" || + action == "fxMove" || action == "fxEditor")) + return emitNotice ("Disable experimental Smart I/O before VST3 graph editing.", true); + if (action == "toggleSmartIO") + { + const bool enabled = bool(value); + if (audioSetupWindow_ != nullptr) audioSetupWindow_->setVisible (false); + const auto error = engine_.setIndependentAudioActive (enabled); + if (error.isNotEmpty()) + { + diagnostics_.record ("P0_SPLIT_ROUTE_FAIL", error); + return emitNotice (error, true); + } + deviceSettingsDirty_ = !enabled; + diagnostics_.record ("P0_SPLIT_ROUTE", enabled ? "ON: independent capture+render (0FX)" : "OFF: legacy joined callback"); + emitNotice (enabled + ? "EXPERIMENTAL independent-clock 0-FX route activated; FIFO is priming. COPY FULL REPORT to inspect bridge health." + : "Restored joined JUCE audio routing."); + } + else if (action == "copyDiagnosticReport") { diagnostics_.record ("REPORT_COPY", "User explicitly requested one-click report"); const auto report = makeAudioReport(); @@ -351,6 +373,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } else if (action == "audioSetup") { + if (engine_.isIndependentAudioActive()) + { + const auto error = engine_.setIndependentAudioActive (false); + if (error.isNotEmpty()) return emitNotice (error, true); + deviceSettingsDirty_ = true; + } // One-sided device routes are temporary and must never leak into // normal user configuration or the persisted audio-devices.xml. if (engine_.hasTemporaryDiagnosticDevice()) @@ -577,6 +605,17 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void timerCallback() override { ++timerTicks_; + // Device error is handled from message thread, never audio callback. + if (engine_.isIndependentAudioDriverError()) + { + const auto error = engine_.setIndependentAudioActive (false); + diagnostics_.record ("P0_SPLIT_DEVICE_ERROR", error.isEmpty() + ? "Driver reported error; restored joined JUCE backend" : error); + deviceSettingsDirty_ = error.isEmpty(); + emitNotice (error.isEmpty() + ? "Smart I/O driver failed; automatic fallback to joined I/O." + : "Smart I/O failed and joined backend could not be restored: "+error, true); + } if (engine_.finalizeGraphSwitch()) { diagnostics_.record ("GRAPH_SWAP_ACK", pendingPresetName_); @@ -596,7 +635,8 @@ 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_.hasTemporaryDiagnosticDevice() && + !engine_.isIndependentAudioActive()) if (auto xml = engine_.devices().createStateXml()) { const auto text = xml->toString(); diff --git a/tests/adaptive_clock_bridge_test.cpp b/tests/adaptive_clock_bridge_test.cpp index 1a2f09e5c..ee5c97956 100644 --- a/tests/adaptive_clock_bridge_test.cpp +++ b/tests/adaptive_clock_bridge_test.cpp @@ -81,5 +81,34 @@ int main() empty.pull(outs,2,128); for(int i=0;i<128;++i)check(lo[i]==0.f && ro[i]==0.f); check(empty.status().primingFrames==128); + + // Long-running starvation/overrun recovery. Explicitly test that FIFO + // resumes after the capture clock stalls and drops excess source frames. + armix::device::AdaptiveClockBridge recovering; + check(recovering.prepare(48000,48000,2,1024,12.)); + std::array srcL {},srcR {}; + for(int i=0;i<512;++i)srcL[i]=srcR[i]=0.25f; + const float* src[2]={srcL.data(),srcR.data()}; + for(int i=0;i<4;++i)recovering.push(src,2,512); + check(recovering.status().overflowFrames>0); + for(int i=0;i<64;++i) + { + recovering.pull(outs,2,128); + for(int n=0;n<128;++n) + { + check(std::isfinite(lo[n]) && std::isfinite(ro[n])); + check(std::abs(lo[n])<=0.3f && std::abs(ro[n])<=0.3f); + } + } + check(recovering.status().underflowFrames>0); + // Simulate a fresh producer clock after a full starvation interval. + for(int cycle=0;cycle<100;++cycle) + { + recovering.push(src,2,128); + recovering.pull(outs,2,128); + } + auto after=recovering.status(); + check(after.pushedFrames>0 && after.renderedFrames>0); + check(after.fillFrames<=1024); return 0; } diff --git a/tests/device_recovery_policy_test.cpp b/tests/device_recovery_policy_test.cpp new file mode 100644 index 000000000..7740324c5 --- /dev/null +++ b/tests/device_recovery_policy_test.cpp @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/device/DeviceRecoveryPolicy.h" +#include +static void check(bool x){if(!x)std::abort();} +int main() +{ + using namespace armix::device; + DeviceRecoveryPolicy p; + check(p.state()==SessionState::stopped); + auto a=p.apply(DeviceEvent::start,0,1000); + check(a.accepted && a.action==RecoveryAction::enumerateDevices); + const auto gen=p.generation(); + check(!p.apply(DeviceEvent::start,gen,1001).accepted); + check(p.apply(DeviceEvent::discoveryOk,gen,1100).action==RecoveryAction::prepareCandidate); + check(p.apply(DeviceEvent::preparationOk,gen,1200).action==RecoveryAction::publishCandidate); + check(!p.apply(DeviceEvent::callbackHealthy,gen,25000).accepted); + check(p.apply(DeviceEvent::callbackHealthy,gen,31200).action==RecoveryAction::persistStable); + check(!p.apply(DeviceEvent::callbackHealthy,gen,40000).accepted); + check(p.apply(DeviceEvent::instability,gen,42000).state==SessionState::degraded); + check(p.apply(DeviceEvent::endpointLost,gen,43000).action==RecoveryAction::silenceAndRetire); + check(!p.apply(DeviceEvent::preparationOk,gen,44000).accepted); // stale async reply + auto newer=p.generation(); + check(newer>gen); + check(!p.apply(DeviceEvent::recover,newer,43000).accepted); + check(p.apply(DeviceEvent::recover,newer,43100).action==RecoveryAction::enumerateDevices); + for(unsigned i=0;i<6;++i) + { + auto failed=p.apply(DeviceEvent::discoveryFailed,p.generation(),50000+i*20000); + check(failed.action==RecoveryAction::scheduleRetry); + check(failed.retryAfterMs<=10000 && failed.retryAfterMs>=100); + check(!p.apply(DeviceEvent::recover,p.generation(),50000+i*20000).accepted); + check(p.apply(DeviceEvent::recover,p.generation(),50000+i*20000+failed.retryAfterMs).accepted); + } + check(p.apply(DeviceEvent::discoveryFailed,p.generation(),999999).action==RecoveryAction::reportFailure); + check(p.state()==SessionState::failed); + check(p.apply(DeviceEvent::stop,0,999999).state==SessionState::stopped); + check(p.apply(DeviceEvent::start,0,1000000).accepted); + // Zero is a valid monotonic origin; do not use stableSince==0 as "off". + DeviceRecoveryPolicy zero; + auto initial=zero.apply(DeviceEvent::start,0,0); + check(zero.apply(DeviceEvent::discoveryOk,initial.generation,0).accepted); + check(zero.apply(DeviceEvent::preparationOk,initial.generation,0).accepted); + check(zero.apply(DeviceEvent::callbackHealthy,initial.generation,30000).action== + RecoveryAction::persistStable); + + // Repeated endpoint loss with momentary apparent recovery cannot bypass + // retry limit. An explicit new START or sustained health is required. + DeviceRecoveryPolicy flapping; + auto wave=flapping.apply(DeviceEvent::start,0,100); + std::uint64_t now=100; + for(int i=0;i<8;++i) + { + check(flapping.apply(DeviceEvent::discoveryOk,wave.generation,now).accepted); + check(flapping.apply(DeviceEvent::preparationOk,wave.generation,now).accepted); + auto down=flapping.apply(DeviceEvent::endpointLost,wave.generation,now+1); + check(down.action==RecoveryAction::silenceAndRetire); + if(i==7) + { + check(down.state==SessionState::failed); + check(!flapping.apply(DeviceEvent::recover,down.generation,now+100000).accepted); + } + else + { + check(down.retryAfterMs>=100 && down.retryAfterMs<=10000); + check(!flapping.apply(DeviceEvent::recover,down.generation,now+1).accepted); + now+=1+down.retryAfterMs; + wave=flapping.apply(DeviceEvent::recover,down.generation,now); + check(wave.action==RecoveryAction::enumerateDevices); + } + } + return 0; +} diff --git a/tests/independent_clock_pipeline_test.cpp b/tests/independent_clock_pipeline_test.cpp new file mode 100644 index 000000000..ef2aa701b --- /dev/null +++ b/tests/independent_clock_pipeline_test.cpp @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/device/IndependentClockPipeline.h" +#include +#include +#include +static void check(bool x){if(!x)std::abort();} +int main() +{ + using armix::device::IndependentClockPipeline; + IndependentClockPipeline p; + check(p.prepare(44100.,48000.,2,8192,30.)); + std::array a{},b{},c{},d{}; + const float* in[2]={a.data(),b.data()}; + float* out[2]={c.data(),d.data()}; + for(int i=0;i<512;++i)a[i]=b[i]=0.15f; + for(int n=0;n<1200;++n) + { + const int captureFrames=(n%10==0)?45:44; // independent source tick + p.capture(in,2,captureFrames); + p.render(out,2,48); + for(int i=0;i<48;++i) + { + check(std::isfinite(c[i]) && std::isfinite(d[i])); + check(std::abs(c[i])<0.25f && std::abs(d[i])<0.25f); + } + } + const auto status=p.streamStatus(); + const auto bridge=p.bridgeStatus(); + check(status.captureCallbacks==1200 && status.renderCallbacks==1200); + check(status.captureFrames>50000 && status.renderFrames==57600); + check(status.captureDropFrames==bridge.overflowFrames); + check(status.renderMissingFrames==bridge.underflowFrames); + check(bridge.primingFrames>0); + check(bridge.fillFrames<=8192); + return 0; +} diff --git a/tests/p0_live_split_contract_test.mjs b/tests/p0_live_split_contract_test.mjs new file mode 100644 index 000000000..38f9c552a --- /dev/null +++ b/tests/p0_live_split_contract_test.mjs @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +const read=p=>readFileSync(p,'utf8'); +const engine=read('src/LiveAudioEngine.h'); +const main=read('src/Main.cpp'); +const native=read('web/monitor.js'); +const adapter=read('engine/device/JuceIndependentDeviceAdapter.h'); + +test('separate real JUCE input-only and output-only managers, callback ownership',()=>{ + assert.match(adapter,/captureManager_\.initialise \(1, 0, nullptr, false\)/); + assert.match(adapter,/renderManager_\.initialise \(0, 2, nullptr, false\)/); + assert.match(adapter,/pipeline_\.capture\(input,numInput,frames\)/); + assert.match(adapter,/pipeline_\.render\(captureData,2,frames\)/); + assert.match(adapter,/renderManager_\.removeAudioCallback \(&renderCallback_\)/); + assert.match(adapter,/captureManager_\.removeAudioCallback \(&captureCallback_\)/); + assert.match(adapter,/setCurrentAudioDeviceType/); + assert.match(adapter,/captureConfig\.sampleRate = 0/); +}); +test('host opt-in is reversible, mode truthful, exact capture endpoint xrun',()=>{ + assert.match(engine,/setIndependentAudioActive \(bool desired\)/); + assert.match(engine,/graphOwned_->count != 0/); + assert.match(engine,/deviceManager_\.closeAudioDevice\(\)/); + assert.match(engine,/splitAdapter_\.prepare\(type,joinedBeforeSplit_,25\.0\)/); + assert.match(engine,/splitAdapter_\.start\(\*this\)/); + assert.match(engine,/splitAdapter_\.stop\(\)/); + assert.match(engine,/deviceManager_\.setAudioDeviceSetup\(joinedBeforeSplit_,false\)/); + assert.match(engine,/splitAudioActive_ \? captureDevice : d/); + assert.match(engine,/JUCE_SPLIT_BRIDGED_0FX/); + assert.match(engine,/p0BridgeUnderflowFrames/); + assert.match(engine,/p0CaptureDropFrames/); +}); +test('one-click GUI opt-in and automatic driver-error rollback; FX unchanged',()=>{ + assert.match(main,/action == "toggleSmartIO"/); + assert.match(main,/P0_SPLIT_DEVICE_ERROR/); + assert.match(main,/isIndependentAudioDriverError/); + assert.match(main,/isIndependentAudioActive/); + assert.match(main,/engine_\.activeOutputDevice\(\)/); + assert.match(native,/arSmartToggle/); + assert.match(native,/0 FX \(EXPERIMENTAL\)/); + assert.match(native,/toggleSmartIO/); + assert.match(native,/p0BridgeUnderflowFrames/); +}); diff --git a/tests/split_stream_telemetry_test.cpp b/tests/split_stream_telemetry_test.cpp new file mode 100644 index 000000000..421bf9748 --- /dev/null +++ b/tests/split_stream_telemetry_test.cpp @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/device/SplitStreamTelemetry.h" +#include +static void check(bool ok){if(!ok)std::abort();} +int main() +{ + armix::device::SplitStreamTelemetry d; + d.sourceStarted(); + d.renderStarted(); + d.captured(256,250); + d.captured(256,256); + d.rendered(128,4); + d.rendered(128,0); + d.rendered(-1,0); + d.captured(10,11); + const auto s=d.snapshot(); + check(s.sourceGeneration==1 && s.renderGeneration==1); + check(s.captureCallbacks==3 && s.renderCallbacks==3); + check(s.captureFrames==506 && s.captureDropFrames==6); + check(s.renderFrames==256 && s.renderMissingFrames==4); + check(s.invalidBufferCallbacks==2); + return 0; +} diff --git a/web/monitor.js b/web/monitor.js index 1d56167f7..2520786d1 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}" + + "#arSmartRoute{display:flex;flex-wrap:wrap;gap:9px;align-items:center;margin-top:9px;font-size:11px;color:#91b6c8}" + + "#arSmartToggle{padding:7px 12px;border-radius:4px;cursor:pointer;color:#d5f5ff;background:linear-gradient(#255469,#123544);border:1px solid #56a5bc}"; document.head.appendChild(css); // Signal Check is declared in the permanent toolbar; footer holds status only. const overlay = document.createElement("div"); @@ -42,6 +44,8 @@ '' + '' + 'One click → paste to ChatGPT' + + '
' + + 'Requires two endpoints, empty FX rack and NORMAL isolation mode. No live certification.
' + '
' + '
The legacy Main L/R, Record and Streaming buttons are UI previews, not hardware routing. Select output using AUDIO SETUP. Use headphones at low volume.
' + ''; @@ -90,6 +94,10 @@ el("arOutputBar").style.width=percent(d.peak)+"%"; el("arSignalReason").textContent=diagnosis(d); el("arDiagnosticMode").value=d.diagnosticRoute||"NORMAL"; + el("arSmartToggle").textContent=d.p0IndependentClockBridgeActive?"DISABLE SMART I/O":"ENABLE SMART I/O · 0 FX (EXPERIMENTAL)"; + el("arSmartStatus").textContent=d.p0IndependentClockBridgeActive + ?"SPLIT ACTIVE · FIFO "+(d.p0FifoFrames??0)+" fr · SRC "+Number(d.p0SrcCorrectionPpm??0).toFixed(1)+" ppm · bridge starvation "+(d.p0BridgeUnderflowFrames??0)+" fr" + :"Legacy JUCE joined callback active. Enable only for 0-VST3 diagnostic; revert before inserting plugins."; el("arSignalMonitor").textContent=d.monitor?"MUTE OUTPUT":"UNMUTE OUTPUT"; el("arSignalDry").textContent=d.dryTest?"DRY TEST ON":"DRY TEST OFF"; el("arHealthPanel").textContent="CALLBACK "+(d.callbackDurationUs||0)+" µs / period "+ @@ -115,6 +123,8 @@ el("arSignalClose").addEventListener("click",()=>overlay.classList.remove("open")); el("arSignalMonitor").addEventListener("click",()=>api.emitEvent("arMixAction",{action:"monitor",value:!state.monitor})); el("arSignalDry").addEventListener("click",()=>api.emitEvent("arMixAction",{action:"dryTest",value:!state.dryTest})); + el("arSmartToggle").addEventListener("click",()=> + api.emitEvent("arMixAction",{action:"toggleSmartIO",value:!state.p0IndependentClockBridgeActive})); el("arDiagnosticMode").addEventListener("change",e=> api.emitEvent("arMixAction",{action:"diagnosticRoute",value:e.target.value})); el("arDiagnosticMark").addEventListener("click",()=>