diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 16fc7ec12..db7b6a4ad 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/live_split_audio_contract_test.mjs - name: Configure Windows x64 shell: pwsh run: > @@ -64,7 +65,7 @@ jobs: if (-not $exe) { throw "ARMixConsole EXE not found" } Copy-Item $exe.FullName "dist/ArSonMix-P2.5-GUI-v0.8-Native-Windows.exe" Copy-Item README.md "dist/README.md" - "P0 native engineering build: SIGNAL CHECK has COPY FULL REPORT, hardware capability and DSP distributions, and isolated output/capture/dry modes. An offline adaptive dual-clock FIR bridge is tested in CI but NOT connected to the existing JUCE joined callback until P0-01 separate-stream adapter is validated. No hardware audio acceptance yet. Use headphones at low level. Only Channel 1 is native." | + "P0 live dual-stream integration build: AUTO attempts independent Windows Audio capture/render with bounded polyphase ASRC for distinct endpoints, DIRECT keeps ASIO without added SRC; profiles and one-click report are available in SIGNAL CHECK. AUTO falls back to legacy JUCE on failed setup or missing capture callbacks. No physical hardware acceptance yet. Use headphones at low level. Only Channel 1 is native." | Out-File -FilePath dist/FIRST_SOUND_README.txt -Encoding utf8 - uses: actions/upload-artifact@v4 with: diff --git a/AGENTS.md b/AGENTS.md index 3cd0b1e41..6b3bfbf51 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,7 +25,7 @@ - Locked GUI v0.8 source untouched without explicit new visual approval. Engine status goes through native adapter. No stale branch bulk merges. - Use `docs/SMART_AUDIO_ENGINE_IMPLEMENTATION_BLUEPRINT.md` PR ladder and definition of done, and update it only with evidence/ADR when changing design decisions. - Consolidate P0 infrastructure development and automated CI before requesting another physical hardware test; no user-assisted test after every tiny code edit. Native SIGNAL CHECK should expose **COPY FULL REPORT** to capture hardware capabilities, source-labeled xruns, budget histograms, and latest MARK CRACKLE events in the OS clipboard. -- Read [P0 Smart Audio diagnostics & prepared bridge](docs/P0_SMART_AUDIO_DIAGNOSTIC_AND_BRIDGE.md) before wiring an SRC. The `AdaptiveClockBridge` is **experimental standalone**, and MUST NOT be wired to the joined JUCE callback or claimed to fix physical crackling until separate-clock adapter feasibility, back-end xrun semantics, automated quality benchmarks and hardware FAT are demonstrated. +- Read [P0 live dual-stream engine](docs/P0_LIVE_SPLIT_AUDIO_ENGINE.md): the Smart path uses TWO independent JUCE Windows Audio devices and capture/render callbacks with FIFO+ASRC; the ASIO/direct path remains unchanged. No GUI mixer redesign. The previous P0 prepared-core handoff is historical. This real adapter is still hardware-UNQUALIFIED: device-dependent buffering and Bluetooth transport cannot be promised glitch-free or sub-10ms until physical FAT. Preserve one-click COPY FULL REPORT. ## If you are a future ChatGPT thread 1. Fetch live repository `main`, this file and the lock document. Cite approved commit and deployment metadata accurately. diff --git a/CMakeLists.txt b/CMakeLists.txt index ef3a1c7f5..e9f701634 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 src/SplitDuplexAdapter.h engine/core/RealtimeHealthHistogram.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h) target_compile_definitions(ARMixConsole PRIVATE JUCE_WEB_BROWSER=1 JUCE_USE_WIN_WEBVIEW2=1 diff --git a/README.md b/README.md index b2a99d8e5..b938a687a 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ The Chromium smoke test needs Playwright Chromium installed. `.github/workflows/ `main` contains experimental JUCE C++20 ASIO/WASAPI **Channel 1** realtime audio, VST3 scanning/import/catalog, editor, FX bypass, FabFilter/RX-compatible layout, diagnostics, native `.armix` preset saving and P2.5 prepared-graph recall. It preserves GUI v0.8, while Channels 2–12 and Master FX/PAN remain non-native previews. The display does **not** claim measured BS.1770 LUFS-I or dBTP. Live recall uses a de-click fade (not seamless DSP crossfade), and ADD/REMOVE/REORDER still detach callback. FabFilter, iZotope RX, and other third-party plugins require Windows hardware FAT before a stable release. [Experimental Windows CI builds](https://github.com/masarray/arsonmix/actions/workflows/p1-windows.yml) provide artifacts from passing runs. -**P0 field support:** SIGNAL CHECK → **COPY FULL REPORT** copies the current native device, sample-rate/buffer, performance, source-labeled discontinuities and recent MARK CRACKLE events into the Windows clipboard for direct paste into the engineering thread. Experimental FIR/dual-clock code is a CI-tested core, not yet wired to physical WASAPI. [Detailed status and remaining gates](docs/P0_SMART_AUDIO_DIAGNOSTIC_AND_BRIDGE.md). +**P0 live routing candidate:** SIGNAL CHECK → SMART AUDIO offers AUTO / STABLE / LOW LATENCY / DIRECT and **COPY FULL REPORT**. AUTO now attempts two real, independently-clocked Windows Audio capture/render devices for distinct endpoint names; a bounded FIR ASRC consumes capture from render clock, with watchdog and rollback to legacy JUCE on failure. Wired ASIO stays direct without extra SRC. **This code is still hardware-unqualified, not guaranteed to eliminate crackling on every device; Bluetooth and hardware latency remain device-dependent.** [Live split engine and acceptance plan](docs/P0_LIVE_SPLIT_AUDIO_ENGINE.md). **Current native architecture (read first):** [Smart Audio Engine ARD v1.0](docs/ARD_SMART_AUDIO_ENGINE_V1_2026-10-25.md) · [implementation blueprint](docs/SMART_AUDIO_ENGINE_IMPLEMENTATION_BLUEPRINT.md) · [zero-FX crackling P0 issue #15](https://github.com/masarray/arsonmix/issues/15). The [older architecture v0.3](docs/ARD_AR_MIX_LIVE_FX_HOST_v0.3.md) is historical and superseded where inconsistent. [GUI v0.8](docs/GUI_BASELINE_LOCK_2026-10-25.md) remains locked. No P2.6 expansion until 44.1/48 kHz dry audio FAT is clean; no public-live claims from green CI alone. Native code follows GUI v0.8, not the opposite. diff --git a/docs/P0_LIVE_SPLIT_AUDIO_ENGINE.md b/docs/P0_LIVE_SPLIT_AUDIO_ENGINE.md new file mode 100644 index 000000000..9c7753aef --- /dev/null +++ b/docs/P0_LIVE_SPLIT_AUDIO_ENGINE.md @@ -0,0 +1,33 @@ +# P0 Live Smart Audio — independent Windows capture/render integration + +**2026-10-25 · implementation review status:** Windows CI pending on PR branch; physical 44.1/48 kHz crackling FAT not run. Never mark P0 hardware acceptance GREEN from simulated test. + +## What is actually different from PR #21 + +- **Two independently started JUCE Windows Audio devices** (separate capture `AudioDeviceManager` and render manager) replace the earlier single joined I/O callback in Smart mode. The producer capture callback deposits raw audio in preallocated SPSC FIFO; the render callback clocks the VST3 mixer through bounded polyphase FIR ASRC. There is **no extra user thread per channel**. +- Only the Windows Audio shared backend is eligible for the dual-stream route; **ASIO and exclusive** retain their existing direct fast path (no added FIFO, no additional SRC). +- **AUTO** is the default: tries split capture/render for two different selected Windows Audio endpoint names. Failure to open either endpoint is caught; stops capture, restores the original full-duplex JUCE setup, and records a diagnostic. Distinct names are only a conservative *candidate signal*, **not proof that two hardware clocks differ**. +- Profile menu in the native-only SIGNAL CHECK: AUTO (20 ms FIFO fill), STABLE (40 ms), LOW LATENCY (12 ms), DIRECT (no bridge). These are provisional **additional FIFO targets**, not total end-to-end latency; output device and wireless transport add their own latency. The selected profile persists locally. +- One-sided OUTPUT ONLY/CAPTURE ONLY tests remain accessible: Smart stream stops before diagnostic routing changes; after NORMAL the selected Smart profile is attempted again. Editing audio device configuration reverts to the existing supported device selector; temporary split or diagnostic setups **never overwrite the saved device XML**. +- A control-thread watchdog detects capture callback stoppage or >3 seconds with no capture callback; this fails over once to direct mode. It does not attempt repeated restart storms, does not restart on the audio thread, and preserves the old route on failed restoration. +- Existing native **COPY FULL REPORT** includes routing mode, capture and render rates, periods, FIFO fill, ratio correction ppm, host FIFO overrun/underflow/priming counts, capture backend xrun provenance, callback timing and timestamped markers. This does **not** imply render hardware underrun telemetry is available through generic JUCE. + +## Realtime invariants + +Audio callback is **always** either the old direct callback, or a render callback pulling from a prepared SPSC FIFO. Independent capture callback only does bounded copying + relaxed atomic telemetry. Device teardown/initialization, plugin preparation, diagnostics writer, Clipboard and WebView are control-thread operations. FIFO preparation happens after endpoints have been negotiated and before the callbacks are attached. A route transition mutes the output while detaching callbacks and restoring the device. + +Cross-clock drift is corrected by the precomputed 48-tap/1024-phase FIR and bounded PI loop; 44.1→48, 48→44.1, +100/+300/−300 ppm deterministic CTests remain required. An additional 30 virtual-minute 8kHz test includes −300 ppm drift and short capture scheduling stalls. Do not infer CPU headroom for all processors/sample rates from this short test alone. + +## Remaining non-negotiable P0 acceptance + +1. Windows MSVC x64 Release compile, whole CTest suite, native/JS contract and Chromium smoke green on **exact commit**. +2. Realtime capture/render drop/race stability under real WASAPI. Neither JUCE backend output-underrun nor device hardware timestamps are currently exposed; **hardware render starvation remains unavailable**, not zero. +3. Device stop/unplug/replug, output sample-rate renegotiation, shared-period contention, 44.1 and 48 kHz + virtual cable / Bluetooth / wired interface all need physical FAT. Unknown clocks can still be unsupported; never claim zero glitches on every driver. +4. Proof-quality SRC tests (multi-tone/sweep, stop-band alias, impulse delay, CPU, 30-minute soak) and end-to-end sub-10ms targets remain **device-dependent**. 12/20/40 ms target FIFO profiles cannot honestly be described as universal ultra-low latency. +5. Third-party VST3 callback safety remains a separate P2.5.2 scope. This P0 update changes I/O, not add/remove graph APIs. + +## User acceptance workflow (ONE campaign) + +The user should not be forced to manually test after every code step. When actual Windows CI is green and a complete P0 candidate is packaged, test both 44.1 and 48 kHz across wired and reported virtual/BT endpoints. Listen at low volume for 0-VST3 dry / split / output-only, mark crackle, and click **COPY FULL REPORT** once to paste in the engineering conversation. Report backend names/modes, selected profiles, FIFO counters and any captured onset times. Only after measured real-device results should P0 hardware issue #15 be closed. + +Primary references: Microsoft WASAPI IAudioClient3, IAudioCaptureClient GetBuffer flags (DATA_DISCONTINUITY), JUCE 8.0.15 AudioDeviceManager / AudioIODeviceCallback. P0 issue: https://github.com/masarray/arsonmix/issues/15 diff --git a/docs/P0_SMART_AUDIO_DIAGNOSTIC_AND_BRIDGE.md b/docs/P0_SMART_AUDIO_DIAGNOSTIC_AND_BRIDGE.md index 406b91bfe..a5b230352 100644 --- a/docs/P0_SMART_AUDIO_DIAGNOSTIC_AND_BRIDGE.md +++ b/docs/P0_SMART_AUDIO_DIAGNOSTIC_AND_BRIDGE.md @@ -1,5 +1,7 @@ # P0 Smart Audio — native diagnostic + prepared clock bridge milestone +> **Historical P0 core milestone (PR #21).** Live dual-stream integration is now documented in [P0_LIVE_SPLIT_AUDIO_ENGINE.md](P0_LIVE_SPLIT_AUDIO_ENGINE.md). Statements below that the bridge is not connected describe the historical PR #21 state, not the current branch. + **Date:** 2026-10-25 **Scope:** P0-00 one-click field support, P0-01 clock-domain core/feasibility, P0-02 standalone polyphase SRC simulation **Status:** experimental infrastructure; **the JUCE audio capture/render adapter is still a joined callback. Clock bridge is not connected to live physical audio.** diff --git a/engine/device/AdaptiveClockBridge.h b/engine/device/AdaptiveClockBridge.h index 9a58c5b8f..6b956b854 100644 --- a/engine/device/AdaptiveClockBridge.h +++ b/engine/device/AdaptiveClockBridge.h @@ -14,8 +14,8 @@ namespace armix::device // The render clock owns the output timeline; source clock can be independent. // Prepare/reset are CONTROL-THREAD operations with both streams STOPPED. // push()/pull() never allocate, lock, log, wait or call JUCE. -// Not yet wired to JUCE joined WASAPI callback: true independent device -// adapter is required to make this useful on unrelated physical clocks. +// Wired only through SplitDuplexAdapter: a separate capture manager runs its +// own callback. Direct JUCE full-duplex/ASIO never calls this SRC. class AdaptiveClockBridge final { public: diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index db3c0c850..58e5c6887 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,7 +74,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void stop() { + // 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); handoff_.resetAfterStop (graphOwned_.get()); stagedOwner_.reset(); for (int i = 0; i < graphOwned_->count; ++i) @@ -85,6 +90,149 @@ 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"; + Setup original = deviceManager_.getAudioDeviceSetup(); + // JUCE remembers channel requirements while a one-sided device is + // active. Explicit masks prevent restoring 0 inputs from remembered + // numInputChansNeeded=0 after we deliberately disable capture. + if (auto* full = deviceManager_.getCurrentAudioDevice()) + { + if (original.useDefaultInputChannels) + { + original.inputChannels = full->getActiveInputChannels(); + original.useDefaultInputChannels = false; + } + if (original.useDefaultOutputChannels) + { + original.outputChannels = full->getActiveOutputChannels(); + original.useDefaultOutputChannels = false; + } + } + if (original.inputChannels.isZero() || original.outputChannels.isZero()) + return "Original full-duplex channel masks are unavailable"; + 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 + smartRenderStartEpoch_ = deviceStartCount_.load (std::memory_order_acquire); + smartCaptureStartEpoch_ = splitAdapter_.snapshot ( + deviceManager_.getCurrentAudioDevice()).captureStarts; + 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()); + const bool captureRestarted = health.captureStarts != smartCaptureStartEpoch_; + const bool renderRestarted = + deviceStartCount_.load (std::memory_order_acquire) != smartRenderStartEpoch_; + const bool rateChanged = std::abs (health.captureRate - health.preparedCaptureRate) > 0.25 + || std::abs (health.outputRate - health.preparedRenderRate) > 0.25; + const bool silent = health.captureStopped || health.captureAgeUs >= 3000000u + || health.captureChannels == 0 || health.renderChannels == 0; + if (!captureRestarted && !renderRestarted && !rateChanged && !silent) + return {}; + const auto reason = rateChanged ? "capture/render rate renegotiated" + : captureRestarted || renderRestarted ? "device stream restarted" + : "capture/render callback stalled or endpoint vanished"; + const auto fallbackError = disableSmartBridge(); + return "Smart clock bridge generation invalidated (" + juce::String (reason) + + "); switched to safe JUCE 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 +245,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 +654,34 @@ 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()); + 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); + 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 ("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)); + 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 +691,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()); @@ -535,6 +718,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) @@ -574,6 +760,11 @@ 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.}; + std::uint64_t smartRenderStartEpoch_ = 0, smartCaptureStartEpoch_ = 0; // message thread juce::AudioPluginFormatManager formats_; std::unique_ptr graphOwned_ {std::make_unique()}; std::unique_ptr stagedOwner_; @@ -724,6 +915,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 +935,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); diff --git a/src/Main.cpp b/src/Main.cpp index 6051c8523..f24b7c599 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."); } @@ -473,8 +543,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } else if (action == "addCatalog") { - if (engine_.hasTemporaryDiagnosticDevice()) - return emitNotice ("Return to NORMAL before adding VST3 effects.", true); + if (engine_.hasTemporaryAudioRouting()) + return emitNotice ("Switch to DIRECT before adding VST3 effects; callback-detaching edits are not live-safe yet.", true); const auto requestId = static_cast (args.getProperty ("requestId", 0)); const auto requestedId = args.getProperty ("id", {}).toString(); const auto* plugin = catalog_.find (requestedId); @@ -518,15 +588,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } else if (action == "fxRemove") { - if (engine_.hasTemporaryDiagnosticDevice()) - return emitNotice ("Return to NORMAL before editing VST3.", true); + if (engine_.hasTemporaryAudioRouting()) + return emitNotice ("Switch to DIRECT before removing VST3 effects; callback-detaching edits are not live-safe yet.", true); editorWindow_.reset(); if (engine_.removeAt (slot)) { diagnostics_.record ("FX_REMOVE", juce::String (slot)); emitChain(); } } else if (action == "fxMove") { - if (engine_.hasTemporaryDiagnosticDevice()) - return emitNotice ("Return to NORMAL before rearranging VST3 effects.", true); + if (engine_.hasTemporaryAudioRouting()) + return emitNotice ("Switch to DIRECT before rearranging VST3 effects; callback-detaching edits are not live-safe yet.", true); editorWindow_.reset(); if (engine_.moveSlot (slot, slot + static_cast (value))) { diagnostics_.record ("FX_MOVE", juce::String (slot)); emitChain(); } } @@ -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", diff --git a/src/SplitDuplexAdapter.h b/src/SplitDuplexAdapter.h new file mode 100644 index 000000000..8f39d3f45 --- /dev/null +++ b/src/SplitDuplexAdapter.h @@ -0,0 +1,186 @@ +// 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 + { + 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); + } + 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 + { + 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.}; + std::atomic stopped_ {true}; + }; + +public: + struct Readout + { + AdaptiveClockBridge::Status fifo; + 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.; + double preparedCaptureRate = 0., preparedRenderRate = 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(); + // 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); + 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"; + preparedCaptureRate_ = captureRate; + preparedRenderRate_ = outputRate; + // 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 (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); + 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; + auto* cap = captureManager_.getCurrentAudioDevice(); + r.captureRate = cap ? cap->getCurrentSampleRate() : 0.; + r.outputRate = renderDevice ? renderDevice->getCurrentSampleRate() : 0.; + r.preparedCaptureRate = preparedCaptureRate_; + r.preparedRenderRate = preparedRenderRate_; + const auto actualCallbackRate = tap_.rateHz.load (std::memory_order_relaxed); + if (actualCallbackRate > 0.) r.captureRate = actualCallbackRate; + 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_; + double preparedCaptureRate_ = 0., preparedRenderRate_ = 0.; // message-thread-owned + bool captureAttached_ = false, running_ = false; // message-thread only +}; +} // namespace armix::device diff --git a/tests/adaptive_clock_bridge_test.cpp b/tests/adaptive_clock_bridge_test.cpp index 1a2f09e5c..fea43aa98 100644 --- a/tests/adaptive_clock_bridge_test.cpp +++ b/tests/adaptive_clock_bridge_test.cpp @@ -62,6 +62,49 @@ static void testRate(double captureRate,double renderRate,double driftPpm) check(std::abs(st.correctionPpm)<=2000.0); } +// 30 minutes of virtual capture/render clocks. Pure deterministic automation; +// no hardware dependency, sleeping, COM objects or real-time wall clock. +// Includes -300ppm and brief 10ms capture scheduling gaps with catch-up. +static void testThirtyMinuteDualClock() +{ + armix::device::AdaptiveClockBridge bridge; + check(bridge.prepare(8000.,8000.,2,8192,40.)); // STABLE headroom for periodic 10ms stalls + std::array left{},right{},outL{},outR{}; + left.fill(.125f); right.fill(.125f); + const float* input[2]={left.data(),right.data()}; + float* output[2]={outL.data(),outR.data()}; + std::uint64_t written=0, consumed=0; + const double inputRate=8000.*(1.-300.e-6); + for(int i=1;i<=180000;++i) + { + const auto expected=static_cast( + std::floor(inputRate*i/100.)); // 10ms timestep + if(i%300!=100) // brief capture scheduler stall, next tick catches up + { + int n=static_cast(expected-written); + check(n>=0&&n<=256); + check(bridge.push(input,2,n)==n); + written=expected; + } + const auto outExpected=static_cast(i*80); + const int need=static_cast(outExpected-consumed); + bridge.pull(output,2,need); + consumed=outExpected; + for(int j=0;jreadFileSync(p,'utf8'); +const engine=r('src/LiveAudioEngine.h'), host=r('src/Main.cpp'), + adapter=r('src/SplitDuplexAdapter.h'),ui=r('web/monitor.js'), + cmake=r('CMakeLists.txt'); +test('actual separate device managers and callbacks, not synthetic split of joined callback',()=>{ + assert.match(adapter,/juce::AudioDeviceManager captureManager_/); + assert.match(adapter,/struct CaptureTap final : juce::AudioIODeviceCallback/); + assert.match(adapter,/captureManager_\.addAudioCallback \(&tap_\)/); + assert.match(adapter,/captureManager_\.removeAudioCallback \(&tap_\)/); + assert.match(adapter,/captureManager_\.closeAudioDevice\(\)/); + assert.match(adapter,/capture\.outputDeviceName\.clear\(\)/); + assert.match(engine,/outputOnly\.inputDeviceName\.clear\(\)/); + assert.match(adapter,/bridge_\.prepare \(captureRate, outputRate, 2, 16384, fifoTargetMs\)/); + assert.match(engine,/splitAdapter_\.pull \(target, 2, frames\)/); + assert.match(cmake,/src\/SplitDuplexAdapter\.h/); +}); +test('unknown clocks are never labeled direct without proof or force resampled on ASIO',()=>{ + assert.match(engine,/!type\.startsWithIgnoreCase \("Windows Audio"\)/); + assert.match(engine,/type\.containsIgnoreCase \("Exclusive"\)/); + assert.match(engine,/configureStartupAuto\(\)/); + assert.match(ui,/AUTO · ADAPTIVE/); + assert.match(ui,/DIRECT · NO SRC/); + assert.match(ui,/STABLE · MORE HEADROOM/); + assert.match(ui,/LOW LATENCY/); +}); +test('both callbacks quiesce before buffer destruction or device rerouting',()=>{ + const stop =engine.slice(engine.indexOf('void stop()'),engine.indexOf('void setMonitorEnabled')); + assert.ok(stop.indexOf('detach();')getActiveInputChannels\(\)/); + assert.match(engine,/original\.useDefaultInputChannels = false/); + assert.match(engine,/original\.outputChannels = full->getActiveOutputChannels\(\)/); + assert.match(engine,/original\.useDefaultOutputChannels = false/); + assert.match(engine,/preparedCaptureRate/); + assert.match(engine,/preparedRenderRate/); + assert.match(engine,/captureRestarted/); + assert.match(engine,/renderRestarted/); + assert.match(engine,/rateChanged/); + assert.match(engine,/const auto rollback = deviceManager_\.setAudioDeviceSetup \(original, false\)/); + assert.match(engine,/setOutputMuted \(true\)/); + assert.match(engine,/disableSmartBridge\(\)/); + assert.match(host,/SMART_WATCHDOG_FALLBACK/); + assert.match(host,/smart-audio-profile\.txt/); + assert.match(host,/!engine_\.hasTemporaryAudioRouting\(\)/); +}); +test('clipboard report and UI include observed FIFO faults and independent clock source',()=>{ + assert.match(engine,/bridgeConsumerUnderflowFrames/); + assert.match(engine,/bridgeProducerOverflowFrames/); + assert.match(engine,/bridgeCaptureBackendXRuns/); + assert.match(engine,/HOST_CAPTURE_FIFO_READ_STARVATION_NOT_HARDWARE_RENDER_XRUN/); + assert.match(engine,/UNAVAILABLE_THROUGH_CURRENT_JUCE_AUDIODEVICE/); + assert.match(ui,/bridgeCorrectionPpm/); + assert.match(ui,/bridgeFillFrames/); + assert.match(host,/makeAudioReport\(\)/); +}); diff --git a/tests/p0_diagnostic_contract_test.mjs b/tests/p0_diagnostic_contract_test.mjs index dfff5dbc1..17c37a67c 100644 --- a/tests/p0_diagnostic_contract_test.mjs +++ b/tests/p0_diagnostic_contract_test.mjs @@ -20,7 +20,7 @@ test('true output-only and capture-only device configurations are opened, not si assert.match(engine,/setAudioDeviceSetup \(original, false\)/); assert.match(engine,/savedLiveSetup_ = original/); assert.match(engine,/diagnosticRoute_\.store \(wanted/); - assert.match(host,/!engine_\.hasTemporaryDiagnosticDevice\(\)/); + assert.match(host,/!engine_\.hasTemporaryAudioRouting\(\)/); }); test('audio callback isolates low-amplitude oscillator from input and VST3',()=>{ assert.match(engine,/const bool toneTest = route == armix::diagnostics::Route::outputOnlyTone/); diff --git a/tests/smart_audio_diagnostic_contract_test.mjs b/tests/smart_audio_diagnostic_contract_test.mjs index 625d414fd..19c219fe3 100644 --- a/tests/smart_audio_diagnostic_contract_test.mjs +++ b/tests/smart_audio_diagnostic_contract_test.mjs @@ -48,7 +48,10 @@ test('clock bridge has no callback alloc / blocking and is gated behind independ assert.match(bridge,/anti-windup/); assert.match(bridge,/void pull \(float\* const\* render, int outputChannels, int frames\) noexcept/); assert.match(bridge,/int push \(const float\* const\* capture, int sourceChannels, int frames\) noexcept/); - assert.match(bridge,/Not yet wired to JUCE joined WASAPI callback/); + assert.match(bridge,/Wired only through SplitDuplexAdapter/); + assert.match(engine,/splitAdapter_\.pull \(target, 2, frames\)/); + assert.match(engine,/splitAdapter_\.prepare \(type, original, deviceManager_, targetLatencyMs\)/); + assert.match(engine,/smartBridgeEnabled_/); assert.doesNotMatch(engine,/AdaptiveClockBridge\s+clockBridge_/); assert.match(cmake,/AdaptiveDualClockBridge/); assert.match(cmake,/RealtimeHealthHistogram/); 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 @@ '
' + '' + '
' + + '
' + + '
' + + '
' + '
' + '