diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 16fc7ec12..0bbfd90c9 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -51,7 +51,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..ed0a9e6c5 --- /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 but **is not activated**: a controlled migration from the existing joined device and plugin-graph ownership must be implemented and verified before exposure. 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 policy is intentionally not wired to the legacy JUCE joined audio device callback or its GUI yet. The existing app still cannot measure independent capture/render clocks from that callback. The true P0 remaining acceptance scope is: + +1. Implement independent Windows capture and render stream adapters or demonstrate that a supported JUCE API exposes actual independent timelines. Use real endpoint IDs/formats/IAudioClient buffer events, not friendly-name matching. +2. Wire the prepared `AdaptiveClockBridge` only for **proven independent clocks** with render-master timeline, bounded callback scratch buffers and no RT allocations. Maintain direct ASIO/shared-clock fast path. +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** with true callback-source labels; do not claim render driver starvation from inferred callback delays. +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 are required while this engineering work proceeds. The approved GUI v0.8 baseline is locked; existing SIGNAL CHECK diagnostics remain unchanged. 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..a1f3718df 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 @@ -509,6 +510,12 @@ 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", "JUCE_JOINED_CALLBACK"); + o->setProperty ("p0IndependentClockBridgeActive", false); + 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. 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/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; +}