diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index b7ea6f60b..9f7797bb7 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -129,6 +129,7 @@ jobs: node scripts/check_console_puzzle.mjs node --check web/approved-native-bridge.js node --check web/approved-native-contract.js + node --test --test-name-pattern="ASIO4ALL|ASIO restart" tests/mixer_io_operator_contract_test.mjs node --test tests/workstream_coordination_contract.test.mjs tests/ci_workflow_efficiency_test.mjs tests/chat_ci_dispatch_contract.test.mjs tests/approved_native_m2_contract.test.cjs tests/native_artifact_packaging_contract_test.mjs tests/windows_installer_contract_test.mjs tests/live_graph_contract_test.mjs python -m unittest discover -s tests -p approved_native_gui_bundle_test.py -v python -m unittest discover -s scripts/tests -p test_factoryfx_release_bundle.py -v diff --git a/CMakeLists.txt b/CMakeLists.txt index 622f606aa..defd9a268 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -78,13 +78,22 @@ target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h engine/bu if(MSVC) target_compile_options(ARMixConsole PRIVATE "$<$:/utf-8>") endif() +# Stamp the build source in Copy Audio Report, including Windows field trials. +execute_process(COMMAND git rev-parse --verify HEAD + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + OUTPUT_VARIABLE ARMIX_BUILD_SOURCE_SHA OUTPUT_STRIP_TRAILING_WHITESPACE + RESULT_VARIABLE ARMIX_BUILD_SOURCE_STATUS ERROR_QUIET) +if(NOT ARMIX_BUILD_SOURCE_STATUS EQUAL 0 OR NOT ARMIX_BUILD_SOURCE_SHA MATCHES "^[0-9a-f]+$") + set(ARMIX_BUILD_SOURCE_SHA "unavailable") +endif() # One JUCE mixer/PCM host on all three desktops. Device backends are OS owned. target_compile_definitions(ARMixConsole PRIVATE JUCE_WEB_BROWSER=1 JUCE_USE_CURL=0 JUCE_PLUGINHOST_VST3=1 JUCE_APPLICATION_NAME_STRING="AR MIX Studio" - JUCE_APPLICATION_VERSION_STRING="0.5.0-p2") + JUCE_APPLICATION_VERSION_STRING="0.5.0-p2" + ARMIX_BUILD_SOURCE_SHA="${ARMIX_BUILD_SOURCE_SHA}") if(WIN32) # Windows retains its proven ASIO-first / WASAPI / static WebView2 distribution. # Never link Windows loader or sound APIs into macOS/Linux builds. @@ -263,6 +272,10 @@ if(BUILD_TESTING) add_executable(ARMixStreamWatchdogTests tests/independent_stream_watchdog_test.cpp) target_compile_features(ARMixStreamWatchdogTests PRIVATE cxx_std_20) add_test(NAME IndependentStreamSilenceRecovery COMMAND ARMixStreamWatchdogTests) + add_executable(ARMixAsioRestartGateTests tests/asio_restart_recovery_gate_test.cpp + engine/device/AsioRestartRecoveryGate.h) + target_compile_features(ARMixAsioRestartGateTests PRIVATE cxx_std_20) + add_test(NAME Asio4AllWdmSettleBoundedDriverTransactionsAndDeferredRebind COMMAND ARMixAsioRestartGateTests) add_executable(ARMixRecoveryTests tests/direct_restore_backoff_test.cpp) target_compile_features(ARMixRecoveryTests PRIVATE cxx_std_20) add_test(NAME BoundedDirectDeviceRecovery COMMAND ARMixRecoveryTests) diff --git a/engine/device/AsioRestartRecoveryGate.h b/engine/device/AsioRestartRecoveryGate.h new file mode 100644 index 000000000..6d0fb9685 --- /dev/null +++ b/engine/device/AsioRestartRecoveryGate.h @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include + +namespace armix::device { +// CONTROL-thread scheduler for an ASIO4ALL driver whose WDM pin inventory +// may be transient during a control-panel restart. It never opens a device, +// touches a vendor plugin, or enters the realtime PCM callback. +// Only actual driver reopen/correction calls consume the bounded budget; +// readback and native graph publication remain eligible after it is spent. +class AsioRestartRecoveryGate final { +public: + static constexpr unsigned maxDriverTransactions=3; + static constexpr std::uint64_t settleMs=350; + + void observeEpoch(std::uint64_t epoch,std::uint64_t nowMs) noexcept { + if(epoch==0 || epoch==epoch_)return; + epoch_=epoch; + driverTransactions_=0; + bindFailures_=0; + nextMs_=add(nowMs,settleMs); + } + // A restart caused by *our own* verified reopen/correction is not a new + // opportunity for an unlimited series of expensive vendor calls. + void carryInternalEpoch(std::uint64_t epoch) noexcept { + if(epoch!=0)epoch_=epoch; + } + bool due(std::uint64_t nowMs) const noexcept { + return epoch_!=0 && nowMs>=nextMs_; + } + bool mayChangeDriver() const noexcept { + return driverTransactions_30000?30000:pause); + } + void recovered() noexcept { + driverTransactions_=0; + bindFailures_=0; + nextMs_=0; + } + unsigned driverTransactions() const noexcept {return driverTransactions_;} + std::uint64_t trackedEpoch() const noexcept {return epoch_;} +private: + static std::uint64_t add(std::uint64_t a,std::uint64_t b) noexcept { + return a>std::numeric_limits::max()-b? + std::numeric_limits::max():a+b; + } + void defer(std::uint64_t nowMs,std::uint64_t millis) noexcept { + const auto deadline=add(nowMs,millis); + if(deadline>nextMs_)nextMs_=deadline; + } + std::uint64_t epoch_=0,nextMs_=0; + unsigned driverTransactions_=0,bindFailures_=0; +}; +} // namespace armix::device diff --git a/engine/device/DirectRouteFence.h b/engine/device/DirectRouteFence.h index 8647f3e6d..02fbca3a0 100644 --- a/engine/device/DirectRouteFence.h +++ b/engine/device/DirectRouteFence.h @@ -92,8 +92,10 @@ class DirectRouteFence final std::string_view inputMask, std::string_view outputMask) noexcept { - if (type.empty() || device.empty() || !validMask(inputMask) - || !validMask(outputMask)) return 0; + // Zero capture pins are permitted ONLY for the input side of an + // output-only session. The playback mask must identify real pins. + if (type.empty() || device.empty() || !validMask(inputMask,true) + || !validMask(outputMask,false)) return 0; std::uint64_t hash=14695981039346656037ull; append(hash, type); append(hash, device); @@ -102,9 +104,10 @@ class DirectRouteFence final return hash ? hash : 1; // reserve zero for never-approved } private: - static bool validMask(std::string_view mask) noexcept + static bool validMask(std::string_view mask,bool allowZero) noexcept { - if (mask.empty() || mask.front() == '0') return false; + if (mask.empty() || (mask.front() == '0' && + !(allowZero && mask.size() == 1))) return false; for (const unsigned char c : mask) if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false; diff --git a/engine/device/JuceActivePortSnapshot.h b/engine/device/JuceActivePortSnapshot.h index 359ea9d96..feb8c1745 100644 --- a/engine/device/JuceActivePortSnapshot.h +++ b/engine/device/JuceActivePortSnapshot.h @@ -26,8 +26,8 @@ struct JuceActivePortSnapshot final { std::uint64_t epoch=0; juce::String deviceName, typeName; - // Accept a frozen copy of masks so unit tests can exercise sparse - // numbering without requiring an ASIO device. This executes off RT. + // Accept a frozen copy of masks to exercise sparse numbering and real + // output-only devices with zero capture pins. No fake input is created. static bool fromMasks(std::uint64_t epoch, const juce::BigInteger& inputMask, const juce::BigInteger& outputMask, @@ -46,7 +46,6 @@ struct JuceActivePortSnapshot final { if(p>=limit || out>=limit){error=Fault::tooManyOutputs;return false;} outputIndices[out++]=p; } - if(in==0){error=Fault::emptyInput;return false;} if(out==0){error=Fault::emptyOutput;return false;} JuceActivePortSnapshot candidate; LiveInputPortRegistry::Fault inputFault{}; diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index f5065a557..2b3207ea9 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -71,7 +71,7 @@ inline bool publishVerifiedFirstSoundState(juce::var& snapshot, static_cast(routeEpoch)>0 && static_cast(revision)>0 && juce::String(static_cast(routeEpoch))==epoch.toString() && - inputs.isArray() && !inputs.getArray()->isEmpty() && + inputs.isArray() && outputs.isArray() && outputs.getArray()->size()>=2 && nativeV8Number(device.getProperty("sampleRate",{}),rate) && nativeV8Number(device.getProperty("bufferFrames",{}),frames) && @@ -267,7 +267,7 @@ inline bool projectInstalledNativeChannelIdGraph( const auto frames=device.getProperty("bufferFrames",{}); double actualRate=0.,actualFrames=0.; if (!outputMask.isArray() || !inputMask.isArray() || - outputMask.getArray()->size()<2 || inputMask.getArray()->isEmpty() || + outputMask.getArray()->size()<2 || !nativeV8Number(rate,actualRate) || !nativeV8Number(frames,actualFrames) || actualRate<8000. || actualRate>384000. || diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 0c7d1bcdb..877c27e96 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -58,6 +58,13 @@ def accepted_pages_html() -> str: # HTML at native build time. Every anchor must occur exactly once: no silent # breakage if Pages GUI source evolves. No extra layout or simulated PCM. NATIVE_EVENT_HOOKS = ( + # Do not expose the reference mixer while the native host is still starting. + ("", "\n"), + ("Mixer · Reference Session", "Mixer · Native Session"), + ("Interactive visual reference. Changes are local to this mockup.", "Preparing native mixer…"), + ("SIMULATED METERS · NO REAL AUDIO", "NATIVE AUDIO"), # The published /preview/ HTML and its V28 checkpoint are immutable. # Change ONLY the compiled native WebView's operator fader travel law. # The DSP gain remains exact dB -> 10^(dB/20), and the mapping is @@ -228,10 +235,10 @@ def accepted_pages_html() -> str: " setNativeCatalog(rows){\n" " pluginCatalog=rows.filter(x=>x&&typeof x.id==='string'&&typeof x.name==='string').map(x=>({\n" " id:x.id,name:x.name,vendor:x.vendor||'Unknown',category:x.category||'Utility',\n" - " format:'VST3',status:'ready',latencySamples:null,\n" + " format:x.format==='Native'?'Native':'VST3',status:'ready',latencySamples:null,\n" " favorite:!!x.favorite,hidden:false}));\n" " const label=document.querySelector('.plugin-disclaimer');\n" - " if(label)label.textContent='NATIVE JUCE VST3 · only verified scanned catalog entries are insertable';\n" + " if(label)label.textContent='Native EQ/Compressor/Harmony ready · external VST3 require verified scan';\n" " renderPluginCatalog();renderFastPicker();return pluginCatalog.length;\n" " },\n" " closeNativePicker(){setFastPicker(false);},\n" diff --git a/src/DiagnosticTone.h b/src/DiagnosticTone.h index fbedcc300..b7647649d 100644 --- a/src/DiagnosticTone.h +++ b/src/DiagnosticTone.h @@ -7,7 +7,7 @@ namespace armix::diagnostics { // Diagnostic routes are temporary, never persisted as the chosen user device. -enum class Route : int { normal = 0, dryThrough = 1, outputOnlyTone = 2, captureOnly = 3 }; +enum class Route : int { normal = 0, dryThrough = 1, outputOnlyTone = 2, captureOnly = 3, mainOutputTone = 4 }; inline constexpr const char* routeName (Route route) noexcept { @@ -17,6 +17,7 @@ inline constexpr const char* routeName (Route route) noexcept case Route::dryThrough: return "DRY_THROUGH"; case Route::outputOnlyTone: return "OUTPUT_ONLY_TONE"; case Route::captureOnly: return "CAPTURE_ONLY"; + case Route::mainOutputTone: return "MAIN_OUTPUT_TONE"; } return "INVALID"; } diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 0d35127a4..51dce7730 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -191,6 +191,20 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Prefer both input pins on a verified stereo endpoint; saved explicit // channel masks still take precedence. Outputs remain DISARMED. auto error = deviceManager_.initialise (2, 2, savedSettings, !savedRoute); + if(savedAsioPreflight && (error.isNotEmpty() || !deviceManager_.getCurrentAudioDevice() || + deviceManager_.getCurrentAudioDevice()->getActiveOutputChannels().countNumberOfSetBits()<2)) { + auto fallback=*savedSettings; + auto name=fallback.getStringAttribute("audioDeviceName"); + if(name.isEmpty())name=fallback.getStringAttribute("audioOutputDeviceName"); + if(name.startsWithIgnoreCase("ASIO4ALL")) { + const bool captureDisabled=fallback.getStringAttribute("audioDeviceInChans")=="0"; + if(!captureDisabled)fallback.removeAttribute("audioDeviceInChans"); + fallback.removeAttribute("audioDeviceOutChans"); + deviceManager_.closeAudioDevice(); + error=deviceManager_.initialise(2,2,&fallback,false); + } + } + #if defined(_WIN32) if (error.isNotEmpty() && !savedRoute && deviceManager_.singleAsioPreferred()) { @@ -211,6 +225,19 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback + " | Windows Audio fallback unavailable"; } #endif + // On first installation only, an output-only endpoint is a valid + // playback/Player host. Never replace a saved explicit ASIO route. + // Physical output is still muted and DIRECT-fenced until verified. + if(error.isNotEmpty() && !savedRoute) { + const auto outputError=deviceManager_.initialise(0,2,nullptr,true); + const auto* candidate=deviceManager_.getCurrentAudioDevice(); + if(outputError.isEmpty() && candidate && + candidate->getActiveOutputChannels().countNumberOfSetBits()>=2) { + startupFallbackReason_="AUTO_OUTPUT_ONLY_NO_CAPTURE"; + error.clear(); + } else if(outputError.isNotEmpty()) + error+=" | Output-only startup: "+outputError; + } if (error.isNotEmpty()) return error; const auto* active = deviceManager_.getCurrentAudioDevice(); if (active == nullptr) @@ -382,8 +409,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Native AUDIO SETUP is the explicit user authorization boundary. // Suppress any live output while selecting/changing a device, even if JUCE // starts its new callback before the selector window is closed. - void beginManualAudioSetup() noexcept { + void beginManualAudioSetup(bool preserveMonitorIntent=false) noexcept { offeredWasapiBinding_.reset(); + if(!preserveMonitorIntent)resumeMainAfterAsioReset_.store(false,std::memory_order_release); + else if(isMonitorEnabled())resumeMainAfterAsioReset_.store(true,std::memory_order_release); setOutputMuted(true); secondaryOutput_.disarm(); directFence_.suspend(); @@ -391,7 +420,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // device-binding operation, not an implicit CLEAR MIXER command. // The JUCE selector may change the driver before its window closes. } - bool finishManualAudioSetup() { + bool finishManualAudioSetup(bool reuseAsioBinding=true) { if(!approveDirectRoute())return false; using Decision=armix::device::DeviceSessionDecision; switch(armix::device::decideDeviceSession( @@ -402,7 +431,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback case Decision::createFirstSilentMixer: return startUnpatchedProductionSession().isEmpty(); case Decision::retainUnboundMixer: - return rebindRetainedWasapiSession(); + return (reuseAsioBinding && reattachRetainedAsioMixer()) || rebindRetainedWasapiSession(); case Decision::rejectedDevice: return false; } @@ -432,6 +461,108 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool recoverSameWasapiMixer() { return hasRetainedUnboundMixer() && rebindRetainedWasapiSession(); } + // The JUCE ASIO device may restart itself after a control panel change. + // Reauthorize only the previously approved driver class and session. + bool sameRetainedAsioDriver() { + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device || !acceptedMixerBinding_ || !asioPinnedRegistration_.valid() || + device->getTypeName()!="ASIO" || device->getName()!=acceptedMixerBinding_->playback)return false; + const auto registered=armix::device::AsioRegistryIdentityProbe::resolve( + std::wstring(device->getName().toWideCharPointer())); + return registered.registration.ok() && + asioPinnedRegistration_.sameDriverClass(registered.registration.identity); + } + // A vendor ASIO4ALL restart can leave JUCE with NO current device object. + // Only the previously selected, explicitly approved driver name and its + // FULL registered CLSID may be reopened; never choose a default endpoint. + // CONTROL only: registry lookup and JUCE setup are forbidden in callback. + bool selectedRetainedAsioDriverForReopen() { + using Policy=armix::session::MixerDeviceBindingPolicy; + if(deviceManager_.getCurrentAudioDevice() || !acceptedMixerBinding_ || + !Policy::isAsio4All(*acceptedMixerBinding_) || + !asioPinnedRegistration_.valid() || !attached_ || independent_.active() || + deviceManager_.getCurrentAudioDeviceType()!="ASIO")return false; + juce::AudioDeviceManager::AudioDeviceSetup setup; + deviceManager_.getAudioDeviceSetup(setup); + if(setup.outputDeviceName.isEmpty() || + setup.outputDeviceName!=acceptedMixerBinding_->playback || + (!setup.inputDeviceName.isEmpty() && + setup.inputDeviceName!=acceptedMixerBinding_->capture))return false; + const auto registered=armix::device::AsioRegistryIdentityProbe::resolve( + std::wstring(setup.outputDeviceName.toWideCharPointer())); + return registered.registration.ok() && + asioPinnedRegistration_.sameDriverClass(registered.registration.identity); + } + bool authorizeRetainedAsioRestart() { + using Policy=armix::session::MixerDeviceBindingPolicy; + if(!hasRetainedNativeSession() || !acceptedMixerBinding_ || + !Policy::isAsio4All(*acceptedMixerBinding_) || !asioPinnedRegistration_.valid() || + !allOutputsDisarmed() || independent_.active() || !attached_ || handoff_.busy() || + fxMovePhase_.load(std::memory_order_acquire)!=0 || + routeReconfiguring_.load(std::memory_order_acquire) || + diagnosticRoute()!=armix::diagnostics::Route::normal)return false; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device || !device->isOpen() || device->getTypeName()!="ASIO" || + device->getName()!=acceptedMixerBinding_->playback)return false; + return approveDirectRoute(&asioPinnedRegistration_); + } + std::optional asioRestartPinCorrection() { + using Policy=armix::session::MixerDeviceBindingPolicy; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device || !acceptedMixerBinding_ || !directFence_.permitted())return {}; + const auto& previous=*acceptedMixerBinding_; + const auto live=readMixerBinding(*device); + if(live.backend!=previous.backend || live.capture!=previous.capture || + live.playback!=previous.playback)return {}; + juce::AudioDeviceManager::AudioDeviceSetup setup; + deviceManager_.getAudioDeviceSetup(setup); + const auto correct=[](const juce::String& oldMask,const juce::StringArray& oldNames, + const juce::StringArray& newNames,juce::BigInteger& mask, + bool& useDefault) { + if(oldNames==newNames)return false; + juce::BigInteger before; + before.parseString(oldMask,16); + const auto mapped=Policy::translateNamedPins(before,oldNames,newNames); + if(!mapped || *mapped==mask)return false; + mask=*mapped; + useDefault=false; + return true; + }; + const bool input=correct(previous.inputMask,previous.inputNames,live.inputNames, + setup.inputChannels,setup.useDefaultInputChannels); + const bool returning=Policy::addReturningCapturePins( + dryRoutingLab_.waitingAsioInputs(),live.inputNames,setup.inputChannels); + const bool output=correct(previous.outputMask,previous.outputNames,live.outputNames, + setup.outputChannels,setup.useDefaultOutputChannels); + if(!input && !output && !returning)return {}; + setup.useDefaultInputChannels=false; + setup.useDefaultOutputChannels=false; + return setup; + } + bool reattachRetainedAsioMixer() { + using Policy=armix::session::MixerDeviceBindingPolicy; + if(!acceptedMixerBinding_ || !Policy::isAsio4All(*acceptedMixerBinding_) || + !hasRetainedNativeSession() || !allOutputsDisarmed() || + !directFence_.permitted() || handoff_.busy())return false; + armix::session::MixerSessionDocument document; + if(!dryRoutingLab_.describeRetainedAsioSession(document))return false; + document.binding=*acceptedMixerBinding_; + MixerBindingInspection inspected; + constexpr auto mode=Policy::Mode::verifiedAsioRestart; + if(inspectNativeMixerSessionBinding(document,inspected,mode).isNotEmpty() || + inspected.live.rate!=document.binding.rate || + Policy::apply(document,inspected.live,inspected.outputs,inspected.callbackInputs,mode).isNotEmpty() || + !dryRoutingLab_.rebindRetainedAsioSession(std::move(document),inspected.pins, + inspected.live.frames))return false; + acceptedMixerBinding_=std::move(inspected.live); + return true; + } + bool takeAsioResetMonitorIntent() noexcept { + return resumeMainAfterAsioReset_.exchange(false,std::memory_order_acq_rel); + } + void cancelAsioResetMonitorIntent() noexcept { + resumeMainAfterAsioReset_.store(false,std::memory_order_release); + } bool hasRetainedNativeSession() const noexcept { return dryRoutingLab_.hasRetainedNativeSession(); } @@ -568,9 +699,35 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // user setup is restored on exit; temporary routes must not be persisted. juce::String setDiagnosticRoute (armix::diagnostics::Route wanted) { - if (dryRoutingLab_.hasAuthoredMixerContent()) - return "An authored mixer cannot enter endpoint isolation until a safe session rebind is available"; using Route = armix::diagnostics::Route; + const auto currentRoute=diagnosticRoute_.load(std::memory_order_acquire); + if(wanted==Route::mainOutputTone) { + if(currentRoute==wanted)return {}; + if(currentRoute!=Route::normal || independent_.active()) + return "Return to NORMAL on the DIRECT device before testing MAIN."; + if(const auto error=liveOutputArmFault(false);error.isNotEmpty())return error; + if(secondaryOutput_.armed()) + return "Stop STREAM before testing the physical MAIN output."; + const auto pair=dryRoutingLab_.acceptedMainCallbackPair(); + if(pair[0]<0 || pair[1]<0 || pair[0]==pair[1]) + return "No verified MAIN output pair."; + mainTestEpoch_.store(dryRoutingLab_.epoch(),std::memory_order_relaxed); + mainTestPair_.store(static_cast(pair[0]) | + (static_cast(pair[1])<<16),std::memory_order_relaxed); + mainTestWasArmed_=isMonitorEnabled(); + mainTestPeak_.store(0.f,std::memory_order_relaxed); + diagnosticRoute_.store(wanted,std::memory_order_release); + setMonitorEnabled(true); // the operator explicitly requested this isolated tone + return {}; + } + if(currentRoute==Route::mainOutputTone) { + // A diagnostic ARM does not authorize microphone audio on exit. + if(!mainTestWasArmed_)setOutputMuted(true); + diagnosticRoute_.store(Route::normal,std::memory_order_release); + if(wanted==Route::normal)return {}; + } + if (dryRoutingLab_.hasAuthoredMixerContent()) + return "Use MAIN OUTPUT TONE to test the output without reopening the authored mixer."; if (handoff_.busy()) return "Finish the pending FX graph transition first"; if (independent_.active()) return "Disable independent clock mode before endpoint isolation tests"; if (wanted == diagnosticRoute_.load (std::memory_order_acquire) && @@ -1132,6 +1289,13 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback formats_,device->getCurrentSampleRate(), juce::jmax(32,device->getCurrentBufferSizeSamples())); if(error.isEmpty() && dryRoutingLab_.epoch()==epoch) { + // The real SOURCE NONE graph is editable before any hardware IN + // patch; one ChannelId publisher remains the PCM authority. + if(!dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count, + juce::jmax(32,device->getCurrentBufferSizeSamples()), + allOutputsDisarmed(),currentOriginalCh1Lease(),true)) + return "Prepared silent mixer could not admit native ChannelId graph"; acceptedMixerBinding_=readMixerBinding(*device); acceptedWasapiBinding_=std::move(profile); } @@ -1573,6 +1737,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return {}; } + // Cold-start restore ONLY: the installed native SOURCE NONE starter has + // never been edited, so the durable saved Show can safely take ownership. + bool hasPristineStartupMixer() const noexcept { + return dryRoutingLab_.canReplacePristineStartupMixer(); + } // A single explicit user Play gesture prepares the previously verified // MAIN and creates its owned virtual MUSIC channel if absent. No manual // PATCH, MONITOR or ARM control is part of the ordinary user workflow. @@ -2164,6 +2333,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback : deviceManager_.getCurrentAudioDevice(); auto* capture = dual ? independent_.captureDevice() : d; o->setProperty ("dryRoutingLab",dryRoutingLab_.status(capture)); + o->setProperty("waitingAsioInputs",dryRoutingLab_.waitingAsioInputCount()); // NORMAL mode is never silently served by the legacy CH1 fallback. // This state is for operator feedback; it does not authorize output. o->setProperty ("productionRoutingState", @@ -2335,6 +2505,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("peak", outputPeak_.load()); o->setProperty ("peakLeft", outputPeakL_.load()); o->setProperty ("peakRight", outputPeakR_.load()); + o->setProperty ("driverBufferPeakLeft",driverBufferPeakL_.load(std::memory_order_relaxed)); + o->setProperty ("driverBufferPeakRight",driverBufferPeakR_.load(std::memory_order_relaxed)); + o->setProperty ("driverBufferProvenance","JUCE_CALLBACK_OUTPUT_POST_GATE"); + o->setProperty ("mainTestLastPeak",mainTestPeak_.load(std::memory_order_relaxed)); const auto loudness = masterLoudness_.read(); const bool measuredDirect = !dual && loudness.supported; o->setProperty ("masterAnalysisProvenance", @@ -2435,7 +2609,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const auto rate=device->getCurrentSampleRate(); const auto frames=device->getCurrentBufferSizeSamples(); if(inputs!=setup.inputChannels || outputs!=setup.outputChannels || - inputs.isZero() || outputs.countNumberOfSetBits()<2 || + outputs.countNumberOfSetBits()<2 || !std::isfinite(rate) || rate<8000.0 || rate!=setup.sampleRate || frames<16 || frames>LiveDryRoutingLab::Block::hardFrameLimit || frames!=setup.bufferSize)return {}; @@ -2491,8 +2665,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const armix::device::AsioRegistrationPolicy::Identity* expectedAsio = nullptr) { auto* device=deviceManager_.getCurrentAudioDevice(); - if (device == nullptr || device->getActiveInputChannels().isZero() - || device->getActiveOutputChannels().isZero()) + if (device == nullptr || device->getActiveOutputChannels().isZero()) return false; // JUCE BigInteger has no fixed 64-bit channel limit: preserve all // channel bits when locking an explicitly approved ASIO/WASAPI route. @@ -2502,6 +2675,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const auto inputMask=device->getActiveInputChannels().toString (16); const auto outputMask=device->getActiveOutputChannels().toString (16); armix::device::AsioRegistrationPolicy::Identity candidate; + if (backend != "ASIO" && expectedAsio != nullptr)return false; if (backend == "ASIO") { const auto selected = armix::device::AsioRegistryIdentityProbe::resolve ( @@ -2534,8 +2708,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool resumeVerifiedDirectRoute() { auto* device=deviceManager_.getCurrentAudioDevice(); - if (device == nullptr || device->getActiveInputChannels().isZero() - || device->getActiveOutputChannels().isZero()) + if (device == nullptr || device->getActiveOutputChannels().isZero()) return false; const auto backend=device->getTypeName(); const auto name=device->getName(); @@ -2592,11 +2765,15 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback LiveDryRoutingLab dryRoutingLab_; std::atomic diagnosticRoute_ {armix::diagnostics::Route::normal}; std::atomic routeReconfiguring_ {false}; + std::atomic mainTestEpoch_{0}; + std::atomic mainTestPair_{0}; + bool mainTestWasArmed_=false; // control thread only std::optional savedLiveSetup_; // Indexed atomic bypass flags: instant RT-safe toggles, no graph detachment. // Temporary publication silence never changes operator MONITOR or MAIN MUTE. // The DIRECT device fence and physical-output verification remain separate. std::atomic topologyPublicationMute_ { false }; + std::atomic resumeMainAfterAsioReset_{false}; std::atomic monitor_ { false }, channelMute_ { false }, masterMute_ { false }, masterMono_ { false }, dryTest_ { false }; std::atomic masterGain_ { 1.f }, channelGain_ { 1.f }, channelPan_ { 0.f }; std::atomic inputPeak_ { 0.f }, postFxPeak_ { 0.f }, outputPeak_ { 0.f }; @@ -2604,6 +2781,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback std::atomic captureObservationBlocks_ {0}; // per native device epoch, even UNPATCHED armix::rt::CaptureBoundaryEvidence captureBoundary_; // callback-only PCM continuity std::atomic outputPeakL_ { 0.f }, outputPeakR_ { 0.f }; + std::atomic driverBufferPeakL_{0.f},driverBufferPeakR_{0.f},mainTestPeak_{0.f}; std::atomic callbackInputs_ { 0 }, callbackOutputs_ { 0 }; std::atomic callbackCount_ { 0 }; // Audio-thread-only timestamp and cheap atomically published counters. @@ -2646,10 +2824,13 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const juce::AudioDeviceManager::AudioDeviceSetup& expected) { const auto* active = deviceManager_.getCurrentAudioDevice(); + // A previously verified OUTPUT-ONLY mixer must be recoverable with + // the same zero-capture identity. Only the physical stereo output is + // compulsory; resumeVerifiedDirectRoute() separately rechecks exact + // backend/device/input/output masks before PCM can be armed. if (active == nullptr || deviceManager_.getCurrentAudioDeviceType() != "Windows Audio" || - active->getActiveInputChannels().isZero() || - active->getActiveOutputChannels().isZero()) return false; + active->getActiveOutputChannels().countNumberOfSetBits()<2) return false; juce::AudioDeviceManager::AudioDeviceSetup current; deviceManager_.getAudioDeviceSetup (current); return current.inputDeviceName == expected.inputDeviceName @@ -2679,6 +2860,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void audioDeviceAboutToStart (juce::AudioIODevice* d) override { + // Some ASIO implementations announce a new callback before STOP. + // Remember the existing MAIN intent before muting this epoch; only + // the verified same-driver CONTROL rebind may resume it. No RT work. + if(monitor_.load(std::memory_order_acquire)) + resumeMainAfterAsioReset_.store(true,std::memory_order_release); setOutputMuted(true); secondaryOutput_.invalidateSource(); // source clock may have changed dryRoutingLab_.prepareDevice(d); // exact active mask, before callback @@ -2728,11 +2914,13 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback inputPeak_.store (0.f); postFxPeak_.store (0.f); outputPeak_.store (0.f); + publishDriverBufferPeaks(0.f,0.f); } void audioDeviceStopped() override { - setOutputMuted(true); + if(monitor_.exchange(false,std::memory_order_acq_rel)) + resumeMainAfterAsioReset_.store(true,std::memory_order_release); secondaryOutput_.invalidateSource(); // explicit reconnect required after device stop masterLoudness_.prepare (0.0); // clear validity across device epoch dryRoutingLab_.deviceStopped(); @@ -2745,6 +2933,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback captureBoundary_.reset(); // no stale pin peaks after disconnect inputPeak_.store (0.f); outputPeak_.store (0.f); + publishDriverBufferPeaks(0.f,0.f); } // ONE original CH1 rack processor for M4 compatibility and the native @@ -2835,6 +3024,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return fx; } + void publishDriverBufferPeaks(float left,float right) noexcept { + driverBufferPeakL_.store(left,std::memory_order_relaxed); + driverBufferPeakR_.store(right,std::memory_order_relaxed); + } + void audioDeviceIOCallbackWithContext ( const float* const* inputs, int inputChannels, float* const* outputs, int outputChannels, int samples, const juce::AudioIODeviceCallbackContext&) override @@ -2844,7 +3038,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // while the user is changing devices. Atomic gate only: no name hash, // allocations, OS calls or device restart on the realtime callback. // An independent WASAPI bridge has its own verified endpoint guard. - const auto activeDiagnosticRoute = diagnosticRoute_.load (std::memory_order_relaxed); + const auto activeDiagnosticRoute = diagnosticRoute_.load (std::memory_order_acquire); // DRY_THROUGH still routes a live microphone to the hardware output: // it MUST use the same DIRECT authorization fence as NORMAL. Only // genuinely isolated OUTPUT_ONLY_TONE / CAPTURE_ONLY tests may bypass @@ -2856,6 +3050,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { for (int c=0; c (samples), std::memory_order_relaxed); return; @@ -2900,6 +3095,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback outputPeak_.store(0.f, std::memory_order_relaxed); outputPeakL_.store(0.f, std::memory_order_relaxed); outputPeakR_.store(0.f, std::memory_order_relaxed); + publishDriverBufferPeaks(0.f,0.f); handoff_.endCycle(cycle); // ACK prepared FX graph even in silence return; } @@ -3025,7 +3221,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback peak=juce::jmax(peak,std::abs(out[i])); } if(c==0)movedPeakL=peak; - else movedPeakR=peak; + else if(c==1)movedPeakR=peak; } if(routedFxMove==1 && cycle.graph) { cycle.graph->orderPacked.store( @@ -3072,6 +3268,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback for(int channel=0;channel outputPair{{0,1}}; + if(route==armix::diagnostics::Route::mainOutputTone) { + const auto packed=mainTestPair_.load(std::memory_order_relaxed); + outputPair={{static_cast(packed&0xffffu),static_cast(packed>>16)}}; + if(!dryRoutingLab_.ready() || + mainTestEpoch_.load(std::memory_order_relaxed)!=dryRoutingLab_.epoch()) + outputPair={{-1,-1}}; + } + const auto testPair=armix::mixer::NativeOutputPairTap::select(outputs,outputChannels,outputPair); const bool captureTest = route == armix::diagnostics::Route::captureOnly; - if (toneTest && outputChannels > 0) + if (toneTest && testPair[0]) testOutputFrames_.fetch_add (static_cast (samples), std::memory_order_relaxed); if (captureTest && inputChannels > 0) testCaptureFrames_.fetch_add (static_cast (samples), std::memory_order_relaxed); @@ -3120,7 +3329,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { auto* left = scratch_.getWritePointer (0); auto* right = scratch_.getWritePointer (1); - const bool audible = enabled && !masterMute_.load (std::memory_order_relaxed); + const bool audible = testPair[0] && enabled && !masterMute_.load (std::memory_order_relaxed); for (int i = 0; i < frames; ++i) left[i] = right[i] = diagnosticTone_.next (audible); } @@ -3154,6 +3363,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const float* left = scratch_.getReadPointer (0); const float* right = scratch_.getReadPointer (1); float* dst = outputs[c] + offset; + if(toneTest && (!testPair[0] || (c!=outputPair[0] && c!=outputPair[1]))) { + juce::FloatVectorOperations::clear(dst,frames); + continue; + } const float fromL = mono ? monoL : (c == 0 ? matrix.ll : matrix.rl); const float fromR = mono ? monoR : (c == 0 ? matrix.lr : matrix.rr); float channelPeak = 0.f; @@ -3173,8 +3386,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback channelPeak = juce::jmax (channelPeak, std::abs (value)); } outPeak = juce::jmax (outPeak, channelPeak); - if (c == 0) outPeakL = juce::jmax (outPeakL, channelPeak); - if (c == 1) outPeakR = juce::jmax (outPeakR, channelPeak); + if (c == outputPair[0]) outPeakL = juce::jmax (outPeakL, channelPeak); + if (c == outputPair[1]) outPeakR = juce::jmax (outPeakR, channelPeak); } } if (!independent_.active()) @@ -3187,6 +3400,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } inputPeak_.store (juce::jmin (1.f, inPeak), std::memory_order_relaxed); postFxPeak_.store (juce::jmin (1.f, postFxPeak), std::memory_order_relaxed); + publishDriverBufferPeaks(outPeakL,outPeakR); + if(route==armix::diagnostics::Route::mainOutputTone) + mainTestPeak_.store(juce::jmax(mainTestPeak_.load(std::memory_order_relaxed),outPeak), + std::memory_order_relaxed); outputPeak_.store (juce::jmin (1.f, outPeak), std::memory_order_relaxed); outputPeakL_.store (juce::jmin (1.f, outPeakL), std::memory_order_relaxed); outputPeakR_.store (juce::jmin (1.f, outPeakR), std::memory_order_relaxed); diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index f404be1a4..1ebdf7a70 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -94,7 +94,7 @@ class LiveDryRoutingLab final { device,generation,snapshot,reason))return; const int inputs=snapshot.inputs.enabledCount; const int outputs=snapshot.outputCount; - if(inputs<=0 || outputs<2) return; // stereo monitoring LAB only + if(inputs<0 || outputs<2) return; // output-only is a real SILENT native session for(int i=0;isetProperty("channels",juce::var(channels)); const FxSelections none{}; - // Same publisher/graph as a real user APPLY, but no authorization. - // Never briefly advertise a synthetic route as LIVE. + // Keep M4's historical unpatched/fail-silent behavior. Startup + // explicitly promotes this same genuine SOURCE NONE graph to PCM. return apply(juce::var(request.release()),directPermitted, independentClock,loadedFx,none,formats, sampleRate,deviceFrames,false); @@ -220,7 +220,7 @@ class LiveDryRoutingLab final { if(topologyFault_.load(std::memory_order_acquire)) return "Device callback channel layout changed; reopen AUDIO SETUP before applying"; const int countNow=portCount_.load(std::memory_order_acquire); - if(countNow<=0 || countNow>armix::device::LiveInputPortRegistry::limit) + if(countNow<0 || countNow>armix::device::LiveInputPortRegistry::limit) return "Invalid active device input channel mask"; std::array physicalPorts{}; for(int i=0;i0)!=externalCh1.populated() || - !hasExplicitRoute()||!ready() || + (!hasExplicitRoute()&&!silentStarter)||!ready() || topologyFault_.load(std::memory_order_acquire)) return false; const auto generation=epoch(),m4Revision=revision(); const auto* old=publisher_.controlPrepared(generation,m4Revision); if(!old || deviceFrames<=0) return false; + const auto& route=silentStarter?sourceTemplate_:acceptedRoute_; + // This admission never upgrades a draft with unverified capture. + if(silentStarter) { + const auto* rows=route.getProperty("channels",juce::var()).getArray(); + if(!rows || rows->size()!=count)return false; + for(const auto& row:*rows) + if(row.getProperty("mode",{}).toString()!="NONE")return false; + } armix::mixer::NativeDryRouteCommand decoded; juce::String problem; if(!armix::mixer::NativeDryRouteCommand::decode( - acceptedRoute_,decoded,problem))return false; + route,decoded,problem))return false; // A native IN is a callback ordinal, not the numerical physical // port label. Preserve original order including sparse ASIO pins. const int inputs=portCount_.load(std::memory_order_acquire); - if(inputs<=0||inputs>armix::device::LiveInputPortRegistry::limit) + if(inputs<0||inputs>armix::device::LiveInputPortRegistry::limit) return false; std::array ports{}; for(int i=0;i staged; std::set hashes; juce::int64 total=0; @@ -2252,6 +2266,34 @@ class LiveDryRoutingLab final { } catch(...) {return "Native graph/VST3 state capture failed";} } + bool describeRetainedAsioSession(armix::session::MixerSessionDocument& document) const { + if(!hasRetainedNativeSession() || + !nativeAccepted_.matches(nativePublisher_,nativeAccepted_.deviceEpoch, + nativeAccepted_.pcmRevision))return false; + document.roster=nativeAccepted_.graph.roster; + document.request=nativeAccepted_.graph.request; + document.legacyIds=nativeAccepted_.graph.ids; + document.outputs=nativeAccepted_.hardware; + document.waitingAsioInputs=waitingAsioInputs_; + return true; + } + + bool rebindRetainedAsioSession(armix::session::MixerSessionDocument document, + const armix::device::JuceActivePortSnapshot& pins,int deviceFrames) { + const auto next=nativeGraphRevisionForRestore(); + const auto previous=document.request.maxFrames; + // Existing processors can still use their prepared quantum. Larger + // device blocks are split by the same render path used before reset. + document.request.maxFrames=armix::device::retainedMixerQuantum(previous, + deviceFrames,Block::hardFrameLimit,false,true); + if(!next || !document.request.maxFrames || !hasRetainedNativeSession())return false; + auto bank=std::make_shared(); + if(armix::mixer::DynamicChannelFxLeaseBank::rebindSameFormat( + pins.epoch,next,*nativeAccepted_.fxOwners,*bank)!= + armix::mixer::DynamicChannelFxLeaseBank::Fault::none)return false; + return restoreNativeMixerSession(std::move(document),std::move(bank),pins,true).isEmpty(); + } + // Match CONTROL's live device readback to the masks registered for the // actual callback epoch. Neither a saved document nor an M4 graph // attests which physical pins the current callback can address. @@ -2310,6 +2352,7 @@ class LiveDryRoutingLab final { nativeAccepted_.graph.roster=std::move(document.roster); nativeAccepted_.graph.request=std::move(document.request); nativeAccepted_.graph.ids=document.legacyIds; + waitingAsioInputs_=std::move(document.waitingAsioInputs); nativeAccepted_.graph.revision=nativeAccepted_.graph.roster.revision(); nativeAccepted_.hardware=document.outputs; nativeAccepted_.fxOwners=std::move(bank); @@ -2507,6 +2550,20 @@ class LiveDryRoutingLab final { return channelIdPhysicalPcmActive() && nativeStructureLive_ ?nativeAccepted_.pcmRevision:revision(); } + // The first accepted SOURCE NONE ChannelId graph is a disposable + // bootstrap topology, not an authored Show. A persisted .smix may replace + // it once on cold start; any accepted FX, control, WIRE, BUS or source + // mutation immediately makes that replacement unsafe. + // CONTROL THREAD ONLY: hasAuthoredMixerContent traverses roster/FX. + bool canReplacePristineStartupMixer() const noexcept { + return channelIdPhysicalPcmActive() && sourceTemplate_.isObject() && + !acceptedRoute_.isObject() && !nativeStructureLive_ && + !nativeControlDirty_ && nativeAccepted_.fxOwners && + nativeAccepted_.graph.request.sources.empty() && + !hasAuthoredMixerContent(); + } + std::span waitingAsioInputs() const noexcept {return waitingAsioInputs_;} + int waitingAsioInputCount() const noexcept {return static_cast(waitingAsioInputs_.size());} bool hasVerifiedNativeSources() const noexcept { return channelIdPhysicalPcmActive() && !nativeAccepted_.graph.request.sources.empty(); } @@ -2523,6 +2580,7 @@ class LiveDryRoutingLab final { nativeControlDirty_=false; nativePublisher_.unpublish(); // CONTROL-only; audio lease retires safely nativeAccepted_=armix::mixer::UnifiedLegacyAccepted{}; + waitingAsioInputs_.clear(); userPatched_.store(false,std::memory_order_release); enabled_.store(false,std::memory_order_release); publishedEpoch_.store(0,std::memory_order_release); @@ -2551,6 +2609,9 @@ class LiveDryRoutingLab final { // CONTROL ONLY: hardware loss makes ready() false but does not erase // authored values, FX identity, GROUP/FX_RETURN buses or accepted WIREs. // Never downgrade this dynamic document to the fixed 10CH/4AUX schema. + std::uint64_t retainedNativeEpoch() const noexcept { + return hasRetainedNativeSession()?nativeAccepted_.deviceEpoch:0; + } bool hasRetainedNativeSession() const noexcept { return !channelIdPhysicalPcmActive() && nativeAccepted_.fxOwners && hasAuthoredMixerContent(); } @@ -2647,6 +2708,17 @@ class LiveDryRoutingLab final { } std::uint64_t revision() const noexcept {return publisher_.lastRevision();} // control only + // Control thread only. The test uses the exact pair the current mixer + // owns, including non-contiguous physical pins mapped to compact indices. + std::array acceptedMainCallbackPair() const noexcept { + if(!ready())return {{-1,-1}}; + if(channelIdPhysicalPcmActive()) + return {{nativeAccepted_.hardware.mainL,nativeAccepted_.hardware.mainR}}; + if(const auto* graph=publisher_.controlPrepared(epoch(),revision())) + return {{graph->mainOutputLeft(),graph->mainOutputRight()}}; + return {{-1,-1}}; + } + // JUCE render callback, with a verified single-clock device. Routing // publishes at the BLOCK boundary. Missing/stale ports output SILENCE. // A failed run never falls through to an unrelated microphone/plugin path. @@ -3079,6 +3151,7 @@ class LiveDryRoutingLab final { return juce::var(out.release()); } private: + std::vector waitingAsioInputs_; // Four 9-bit callback indices (0 means absent) and the prepared quantum. // One atomic read gives AUDIO a coherent destination/quantum contract. std::atomic nativeHardware_{0}; diff --git a/src/Main.cpp b/src/Main.cpp index e7b88e1a8..381b1e9d0 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -17,6 +17,7 @@ #include "DiagnosticsRecorder.h" #include "../engine/device/DirectRestoreBackoff.h" #include "../engine/device/AudioSetupRecoveryPolicy.h" +#include "../engine/device/AsioRestartRecoveryGate.h" #include "../engine/device/PeriodCapabilityEvidence.h" #include "../engine/diagnostics/CrackleEvidenceWindow.h" #if defined(_WIN32) @@ -1010,8 +1011,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr (void) armix::console::projectRetainedNativeChannelIdGraph (accepted, live); // Sole control-thread SessionSnapshot from the installed PCM publisher. armix::console::publishAuthoritativeMixerSession(accepted); - if(auto* obj=accepted.getDynamicObject()) + if(auto* obj=accepted.getDynamicObject()) { obj->setProperty("channelAppearance",channelAppearance_.snapshot(accepted.getProperty("graph",{}))); + obj->setProperty("waitingAsioInputs",live.getProperty("waitingAsioInputs",0)); + } return accepted; } @@ -1060,6 +1063,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // ENGINE callback. This code executes on the JUCE message thread, not RT. void handleApprovedNativeControl(const juce::var& request) { + if(audioDeviceApplyActive_) { + auto ack=std::make_unique(); + ack->setProperty("requestId",request.getProperty("requestId",{})); + ack->setProperty("status","REJECTED"); + ack->setProperty("errorCode","AUDIO_DEVICE_APPLY_IN_PROGRESS"); + browser_.emitEventIfBrowserIsVisible("arMixConsoleAck",juce::var(ack.release())); + return; + } const auto beforeLive=engine_.status(); const auto before=approvedNativeSnapshot(beforeLive); const auto route=beforeLive.getProperty("dryRoutingLab",{}); @@ -1092,9 +1103,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr armix::builtin_fx::ChannelCompressorProcessor::catalogIdentity; const bool builtInHarmony=catalogId== armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity; - const auto* plugin=(builtInEq||builtInComp||builtInHarmony)?nullptr:catalog_.find(catalogId); + // Built-in DSP is compiled into the native host. Its admit + // path must remain usable even while third-party VST3 metadata + // discovery blocks or scans in the background. External + // plugins still require a fully verified, idle catalog. + const bool externalCatalog=!builtInEq&&!builtInComp&&!builtInHarmony; + const auto* plugin=externalCatalog?catalog_.find(catalogId):nullptr; std::uint64_t ep=0,rev=0,roster=0,target=0; - if((!builtInEq&&!builtInComp&&!builtInHarmony&&!plugin)||catalog_.busy()||nativeShowBusy_|| + if((externalCatalog&&(!plugin||catalog_.busy()))||nativeShowBusy_|| studioBackupBusy_||engine_.isGraphSwitchPending()) { nativeError="NATIVE_VST3_CATALOG_OR_HOST_BUSY"; } else if(!armix::console::approvedNativeId( @@ -1272,7 +1288,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr o->setProperty("open",device!=nullptr&&device->isOpen()); o->setProperty("authorized",engine_.directRouteAuthorized()); o->setProperty("outputMuted",engine_.isOutputMuted()); - o->setProperty("deviceGeneration",engine_.status().getProperty("deviceGeneration",0)); + const auto live=engine_.status(); + o->setProperty("deviceGeneration",live.getProperty("deviceGeneration",0)); + o->setProperty("mainOutputs",live.getProperty("dryRoutingLab",{}).getProperty("mainOutputs",{})); juce::Array inputNames,outputNames,inputPins,outputPins,rates,buffers; if(device!=nullptr&&device->isOpen()) { const auto inputs=device->getInputChannelNames(); @@ -1303,6 +1321,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // One-shot on a verified setup or startup, including the first input // patch. A later device epoch or a user MUTE cancels the pending arm. std::uint64_t autoMainEpoch_=0; + bool autoMainRequiresInput_=true; std::optional autoMainCheckedRevision_; void serviceAutomaticMain() { if(autoMainEpoch_==0)return; @@ -1316,24 +1335,73 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto revision=engine_.outputArmRevision(); if(autoMainCheckedRevision_==revision)return; if(engine_.isGraphSwitchPending()||!engine_.hasBoundMixerRoute())return; + // A transient native graph/FX ACK must not permanently consume + // the only automatic MAIN attempt for this control revision. + // Retry only the cheap CONTROL preflight until it is genuinely safe. + if(engine_.liveOutputArmFault(autoMainRequiresInput_).isNotEmpty())return; autoMainCheckedRevision_=revision; - if(engine_.liveOutputArmFault().isNotEmpty())return; engine_.setMonitorEnabled(true); autoMainEpoch_=0; diagnostics_.record("MAIN_AUTO_ENABLED","Verified device, input and MAIN output"); } - void requestAutomaticMain() { + void requestAutomaticMain(bool requireInput=true) { + autoMainRequiresInput_=requireInput; autoMainEpoch_=engine_.dryRoutingLabEpoch(); autoMainCheckedRevision_.reset(); serviceAutomaticMain(); } + using MixerBindingMode=armix::session::MixerDeviceBindingPolicy::Mode; + bool audioDeviceApplyActive_=false; // JUCE message thread, including nested driver dispatch + + juce::String openSelectedAudioDevice(const juce::String& backend, + const juce::AudioDeviceManager::AudioDeviceSetup& setup,bool resetDefaults=false) { + auto& manager=engine_.devices(); + if(manager.getCurrentAudioDeviceType()==backend && !resetDefaults) { + if(auto* device=manager.getCurrentAudioDevice();device && !device->isOpen()) + manager.closeAudioDevice(); + return manager.setAudioDeviceSetup(setup,true); + } + + // JUCE's setCurrentAudioDeviceType opens its remembered/default + // device first and sleeps on the message thread. Initialise the + // exact named backend and requested masks in one open instead. + auto xml=manager.createStateXml(); + if(!xml)xml=std::make_unique("DEVICESETUP"); + xml->setAttribute("deviceType",backend); + xml->removeAttribute("audioDeviceName"); + xml->setAttribute("audioInputDeviceName",setup.inputDeviceName); + xml->setAttribute("audioOutputDeviceName",setup.outputDeviceName); + xml->setAttribute("audioDeviceRate",setup.sampleRate); + xml->setAttribute("audioDeviceBufferSize",setup.bufferSize); + const auto setMask=[&](const char* key,bool useDefault,const juce::BigInteger& mask) { + if(useDefault)xml->removeAttribute(key); + else xml->setAttribute(key,mask.toString(2)); + }; + setMask("audioDeviceInChans",setup.useDefaultInputChannels,setup.inputChannels); + setMask("audioDeviceOutChans",setup.useDefaultOutputChannels,setup.outputChannels); + diagnostics_.record("CUSTOM_AUDIO_PHASE","CLOSE_PREVIOUS | "+manager.getCurrentAudioDeviceType()); + manager.closeAudioDevice(); + diagnostics_.record("CUSTOM_AUDIO_PHASE","OPEN_SELECTED | "+backend); + return manager.initialise(2,2,xml.get(),false); + } + void applyCustomAudioDevice(const juce::var& args) { - // Synchronous manager operations stay on JUCE's established message - // thread. A vendor driver may block; never pretend JS async fixes it. + // JUCE device lifecycle runs on the message thread, including ASIO's + // modal callbacks. Serialize transactions across nested dispatch. const auto id=args.getProperty("requestId",{}).toString().substring(0,64); + if(audioDeviceApplyActive_) { + auto ack=std::make_unique(); + ack->setProperty("requestId",id); + ack->setProperty("ok",false); + ack->setProperty("state","BUSY"); + ack->setProperty("error","Audio I/O is already applying a device change."); + browser_.emitEventIfBrowserIsVisible("arMixAudioDeviceApplyAck",juce::var(ack.release())); + return; + } + const juce::ScopedValueSetter applying(audioDeviceApplyActive_,true); const auto oldGeneration=engine_.status().getProperty("deviceGeneration",0); auto send=[&](bool ok,const juce::String& state,const juce::String& error, bool canReusePins=false) @@ -1360,7 +1428,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(nativeShowBusy_||studioBackupBusy_||mixerSessionWorker_.busy()|| engine_.isGraphSwitchPending()|| static_cast(nativeRoute.getProperty("pending",false))|| - engine_.independentClockActive()||engine_.hasTemporaryDiagnosticDevice()|| + engine_.independentClockActive()|| + engine_.diagnosticRoute()!=armix::diagnostics::Route::normal|| engine_.secondaryArmed()) return send(false,"REJECTED", "Stop STREAM and finish Show/FX/diagnostic/clock transition first"); @@ -1369,9 +1438,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto typeName=config.getProperty("backend",{}).toString(); const auto capture=config.getProperty("captureDevice",{}).toString(); const auto playback=config.getProperty("playbackDevice",{}).toString(); - if(typeName.isEmpty()||capture.isEmpty()||playback.isEmpty()|| + if(typeName.isEmpty()||playback.isEmpty()|| typeName.length()>160||capture.length()>250||playback.length()>250) - return send(false,"REJECTED","Choose actual capture and playback devices"); + return send(false,"REJECTED","Choose an actual playback device"); auto& manager=engine_.devices(); juce::AudioIODeviceType* selectedType=nullptr; for(auto* type:manager.getAvailableDeviceTypes()) @@ -1380,8 +1449,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Do not let JS submit arbitrary names or combine unmatched ASIO devices. const auto namesIn=selectedType->getDeviceNames(true); const auto namesOut=selectedType->getDeviceNames(false); - if(!namesIn.contains(capture)||!namesOut.contains(playback)|| - (!selectedType->hasSeparateInputsAndOutputs()&&capture!=playback)) + // A separate-input/output backend can legitimately open a render + // endpoint WITHOUT capture hardware. Empty capture is a deliberate + // operator choice, never an inferred name or a fake input port. + // ASIO/non-separate drivers retain exact duplex device identity; + // they may still expose zero enabled capture *pins*. + const bool separate=selectedType->hasSeparateInputsAndOutputs(); + const bool outputOnly=separate&&capture.isEmpty(); + if((!outputOnly&&!namesIn.contains(capture))||!namesOut.contains(playback)|| + (!separate&&capture!=playback)) return send(false,"REJECTED","Device names or duplex pairing are not reported by JUCE"); auto sample=config.getProperty("sampleRate",{}), period=config.getProperty("bufferSize",{}); if(!(sample.isInt()||sample.isDouble()||sample.isInt64())|| @@ -1403,6 +1479,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const bool previousWasOpen=previousDevice!=nullptr&&previousDevice->isOpen(); const bool previousMixerBound=engine_.hasBoundMixerRoute(); const bool previousMonitor=engine_.isMonitorEnabled(); + const auto assignMain=config.getProperty("assignSelectedPlaybackPinsToMain",false); + if(!assignMain.isBool()) + return send(false,"REJECTED","Invalid MAIN playback pin selection"); + const bool explicitMain=static_cast(assignMain); const auto confirm=config.getProperty("confirmRetainedPinMapping",false); if(!confirm.isBool()) return send(false,"REJECTED","Invalid retained mixer mapping confirmation"); @@ -1410,7 +1490,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // The first Apply must open and verify the selected device. // Confirmation binds only that exact, still-open generation; // draft rate, buffer and pin changes use the normal Apply path. - if(!sameEndpoint || !previousWasOpen || rate!=before.sampleRate || + if(explicitMain || !sameEndpoint || !previousWasOpen || rate!=before.sampleRate || block!=before.bufferSize || !engine_.confirmRetainedWasapiPortMapping()) return send(false,"NEEDS_REMAP", @@ -1443,6 +1523,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto recovery=armix::device::AudioSetupRecoveryPolicy::select( sameEndpoint,previousWasOpen,typeName=="ASIO", pinInput.isArray()&&pinOutput.isArray()); + if(explicitMain && (!recovery.reuseActivePins || + pinOutput.getArray()->size()!=2)) + return send(false,"REJECTED","Select exactly two inspected playback pins for MAIN."); if(recovery.reuseActivePins) { const auto inCount=juce::jmin(64,previousDevice->getInputChannelNames().size()); const auto outCount=juce::jmin(64,previousDevice->getOutputChannelNames().size()); @@ -1459,14 +1542,18 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr }; juce::BigInteger inMask,outMask; if(!parsePins(pinInput,inCount,inMask)||!parsePins(pinOutput,outCount,outMask)|| - inMask.countNumberOfSetBits()<1||outMask.countNumberOfSetBits()<2) - return send(false,"REJECTED","Choose >=1 verified capture and >=2 playback pins"); + (outputOnly&&!inMask.isZero())||outMask.countNumberOfSetBits()<2) + return send(false,"REJECTED","Select real input pins (or none) and >=2 verified playback pins"); candidate.useDefaultInputChannels=false; candidate.useDefaultOutputChannels=false; candidate.inputChannels=inMask; candidate.outputChannels=outMask; }else { - candidate.useDefaultInputChannels=true; + // The requested 0-IN option must not reopen a microphone merely + // because JUCE defaults to enabling available capture channels. + // Output pin selection still requires actual driver readback. + candidate.useDefaultInputChannels=!outputOnly; + if(outputOnly)candidate.inputChannels.clear(); candidate.useDefaultOutputChannels=true; } auto* active=manager.getCurrentAudioDevice(); @@ -1488,7 +1575,6 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto start=monotonicMilliseconds(); autoMainEpoch_=0; engine_.beginManualAudioSetup(); - if(!unchangedDevice)manager.setCurrentAudioDeviceType(typeName,false); // JUCE setAudioDeviceSetup() can return success without reopening when // setup == currentSetup and currentAudioDevice != nullptr, even when // that driver object has stopped. closeAudioDevice() deletes it but @@ -1500,18 +1586,47 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr typeName+" | "+(previousWasOpen?"REFRESH_ASIO_PINS":"CLOSED_DEVICE_RECOVERY")); manager.closeAudioDevice(); } - auto error=manager.getCurrentAudioDeviceType()==typeName - ?manager.setAudioDeviceSetup(candidate,true) - :juce::String("Selected audio backend could not be opened"); + diagnostics_.record("CUSTOM_AUDIO_PHASE","APPLY | "+typeName); + auto error=openSelectedAudioDevice(typeName,candidate); + diagnostics_.record("CUSTOM_AUDIO_PHASE","VERIFY_READBACK | "+typeName); juce::AudioDeviceManager::AudioDeviceSetup actual; manager.getAudioDeviceSetup(actual); auto* opened=manager.getCurrentAudioDevice(); - const bool changedAsioPinLayout=error.isEmpty()&&recovery.verifyAsioPinIdentity&& + bool changedAsioPinLayout=error.isEmpty()&&recovery.verifyAsioPinIdentity&& opened!=nullptr&&opened->isOpen()&& (opened->getInputChannelNames()!=originalInputNames|| opened->getOutputChannelNames()!=originalOutputNames); + const bool refreshedAsio4All=typeName=="ASIO" && playback.startsWithIgnoreCase("ASIO4ALL") && + recovery.reuseActivePins && (changedAsioPinLayout || error.isNotEmpty()); + bool explicitPairStillIdentified=explicitMain; + if(refreshedAsio4All) { + // Never replay an index into a newly enumerated ASIO aggregate. + // Preserve verified selected names if they still exist, including + // VB-Cable capture moved past newly enabled input channels. + using BindingPolicy=armix::session::MixerDeviceBindingPolicy; + const auto freshInputNames=changedAsioPinLayout?opened->getInputChannelNames():juce::StringArray{}; + const auto freshOutputNames=changedAsioPinLayout?opened->getOutputChannelNames():juce::StringArray{}; + const auto capturePins=changedAsioPinLayout?BindingPolicy::translateNamedPins( + candidate.inputChannels,originalInputNames,freshInputNames):std::nullopt; + const auto playbackPins=changedAsioPinLayout?BindingPolicy::translateNamedPins( + candidate.outputChannels,originalOutputNames,freshOutputNames):std::nullopt; + candidate.useDefaultInputChannels=!capturePins && !candidate.inputChannels.isZero(); + candidate.useDefaultOutputChannels=!playbackPins; + if(capturePins)candidate.inputChannels=*capturePins; + if(playbackPins)candidate.outputChannels=*playbackPins; + explicitPairStillIdentified=explicitMain && playbackPins.has_value(); + diagnostics_.record("CUSTOM_AUDIO_PHASE","REFRESH_ASIO4ALL_INVENTORY"); + error=openSelectedAudioDevice(typeName,candidate,true); + manager.getAudioDeviceSetup(actual); + opened=manager.getCurrentAudioDevice(); + changedAsioPinLayout=error.isEmpty() && opened && opened->isOpen() && + ((capturePins && opened->getInputChannelNames()!=freshInputNames) || + (playbackPins && opened->getOutputChannelNames()!=freshOutputNames)); + } + // Never consume the automatic recovery epoch before a mixer bind. + // A transient ASIO4ALL pin inventory can settle on the next tick. if(changedAsioPinLayout) - error="ASIO pin layout changed. Output remains muted; review the NEW capture and playback pins and Apply again"; + error="ASIO pin layout changed. Output remains muted; review the new playback pins."; if(error.isEmpty()&&(opened==nullptr||!opened->isOpen()|| manager.getCurrentAudioDeviceType()!=typeName|| actual.inputDeviceName!=capture||actual.outputDeviceName!=playback|| @@ -1521,15 +1636,18 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr (!candidate.useDefaultOutputChannels&&actual.outputChannels!=candidate.outputChannels)|| opened->getActiveInputChannels()!=actual.inputChannels|| opened->getActiveOutputChannels()!=actual.outputChannels|| - opened->getActiveInputChannels().countNumberOfSetBits()<1|| opened->getActiveOutputChannels().countNumberOfSetBits()<2|| std::abs(opened->getCurrentSampleRate()-actual.sampleRate)>1.0|| opened->getCurrentBufferSizeSamples()!=actual.bufferSize)) error="Driver readback mismatch; device setting was not accepted"; - if(error.isEmpty()&&!finishAudioSetupAndRecoverMixer(true)) { + if(error.isEmpty())diagnostics_.record("CUSTOM_AUDIO_PHASE","BIND_MIXER | "+typeName); + const auto bindingMode=explicitPairStillIdentified?MixerBindingMode::verifiedMainPinApply: + MixerBindingMode::verifiedDeviceApply; + if(error.isEmpty()&&!finishAudioSetupAndRecoverMixer(bindingMode)) { if(!previousMixerBound && engine_.directRouteAuthorized() && (engine_.hasRetainedUnboundMixer() || mixerSessionRecoveryPending_)) { - const juce::String needsRemap="Device opened. Mixer retained and muted; its port mapping or FX processing format needs review"; + const auto needsRemap=mixerSessionError_.isNotEmpty()?mixerSessionError_: + juce::String("Device opened, but the mixer could not bind to its playback pins."); diagnostics_.record("CUSTOM_AUDIO_NEEDS_REMAP",needsRemap); send(false,"NEEDS_REMAP",needsRemap,engine_.stageRetainedWasapiPortMapping()); emitApprovedNativeSnapshot(); @@ -1542,6 +1660,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr startupError_.clear(); deviceSettingsDirty_=true; directRestore_.cancel(); + asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); diagnostics_.record("CUSTOM_AUDIO_APPLY_OK", typeName+" | "+juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); requestAutomaticMain(); @@ -1559,11 +1678,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // One rollback, never blind default endpoint fallback, no auto-unmute. // A previously CLOSED device was never a verified rollback target. engine_.beginManualAudioSetup(); - if(recovery.priorKnownOpen&&manager.getCurrentAudioDeviceType()!=previousType&&previousType.isNotEmpty()) - manager.setCurrentAudioDeviceType(previousType,false); + diagnostics_.record("CUSTOM_AUDIO_PHASE","ROLLBACK | "+previousType); const auto restored=recovery.priorKnownOpen&&previousType.isNotEmpty()&& - manager.getCurrentAudioDeviceType()==previousType&& - manager.setAudioDeviceSetup(before,true).isEmpty(); + openSelectedAudioDevice(previousType,before).isEmpty()&& + manager.getCurrentAudioDeviceType()==previousType; juce::AudioDeviceManager::AudioDeviceSetup checked; manager.getAudioDeviceSetup(checked); const bool verified=restored&& @@ -1579,6 +1697,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr (manager.getCurrentAudioDevice()->getInputChannelNames()==originalInputNames&& manager.getCurrentAudioDevice()->getOutputChannelNames()==originalOutputNames))&& finishAudioSetupAndRecoverMixer(); + if(verified)asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); diagnostics_.record("CUSTOM_AUDIO_APPLY_FAIL",error+" | rollback="+ (verified?"RESTORED":"RECOVERY_REQUIRED")+" | "+ juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); @@ -1595,7 +1714,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Suspend physical output but retain ALL authored mixer state while // the real JUCE device selector is visible (including no-change close). autoMainEpoch_=0; - engine_.beginManualAudioSetup(); + engine_.beginManualAudioSetup(true); // The native JUCE device list is cached after first construction: // reopening the settings window avoids repeating full widget setup. @@ -1618,7 +1737,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (safe == nullptr) return; if (safe->finishAudioSetupAndRecoverMixer()) { - safe->requestAutomaticMain(); + safe->requestAutomaticMain(!safe->engine_.takeAsioResetMonitorIntent()); safe->deviceSettingsDirty_ = true; safe->startupError_.clear(); safe->diagnostics_.record ("DIRECT_ROUTE_APPROVED", @@ -1639,11 +1758,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr { safe->playerOutputPendingIndex_=-1; safe->diagnostics_.record ("DIRECT_ROUTE_REJECTED", - "No valid full-duplex device; audio remains gated"); + "No verified stereo playback device; audio remains gated"); safe->emitNotice ( safe->engine_.hasRetainedUnboundMixer() - ? "Mixer and plugin state retained. Device binding changed; output stays muted until a verified full-session rebind." - : "Choose a working capture and render device. Audio remains muted.", true); + ? "Playback unavailable. Mixer and plugin settings are saved." + : "Choose a working stereo output in Audio I/O. Input hardware is optional.", true); safe->emitApprovedNativeSnapshot(); } }); @@ -1778,7 +1897,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: " << juce::JUCEApplication::getInstance()->getApplicationVersion() + << " | Source HEAD: " << ARMIX_BUILD_SOURCE_SHA << "\n"; result << "Platform: " << juce::SystemStats::getOperatingSystemName() << "\n"; result << "CPU: " << juce::SystemStats::getCpuModel() << "\n"; result << "Logical cores: " << juce::SystemStats::getNumCpus() @@ -2216,16 +2336,33 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr diagnostics_.record("DYNAMIC_MIXER_VST3_REMAP_REQUIRED",error); return error; } + if(bindingMode==MixerBindingMode::exact && startupOnSavedDevice && + armix::session::MixerDeviceBindingPolicy::isAsio4All(doc.binding)) + bindingMode=MixerBindingMode::verifiedAsioRestart; const bool resume=startupOnSavedDevice && - bindingMode==armix::session::MixerDeviceBindingPolicy::Mode::exact && + (bindingMode==MixerBindingMode::exact || bindingMode==MixerBindingMode::verifiedAsioRestart) && !usedPrevious && !retained && doc.resumeMain.value_or(true); const auto live=engine_.status().getProperty("dryRoutingLab",{}); - if(static_cast(live.getProperty("nativeChannelIdPcmActive",false))) { + const bool nativeAlreadyActive=static_cast( + live.getProperty("nativeChannelIdPcmActive",false)); + // A fresh silent ChannelId starter is now admitted before the saved + // Show is inspected. Only THAT unmodified bootstrap may be replaced + // by cold-start restore or by verified Apply after a failed startup. User-authored FX, + // WIRE, BUS and fader edits must never be overwritten by late scan. + // A verified PREVIOUS checkpoint is also eligible: the separate + // resume policy keeps MAIN muted after recovery from corrupt HEAD. + const bool recoveringAfterDeviceApply=bindingMode!=MixerBindingMode::exact && + mixerSessionRecoveryPending_; + const bool replacePristineStartup=nativeAlreadyActive && !retained && + (startupOnSavedDevice || recoveringAfterDeviceApply) && + engine_.hasPristineStartupMixer(); + if(nativeAlreadyActive && !replacePristineStartup) { mixerSessionStatus_="LIVE_MIXER_UNCHANGED"; - return "Live native mixer already active; refusing to replace it"; + return "Live native mixer already edited; refusing to replace it"; } - error=engine_.restoreNativeMixerSession(std::move(doc),states,false,nullptr,bindingMode); + error=engine_.restoreNativeMixerSession(std::move(doc),states, + replacePristineStartup,nullptr,bindingMode); if(error.isNotEmpty()) { mixerSessionStatus_=error.contains("NEEDS_REMAP") ?"NEEDS_REMAP":"RESTORE_REJECTED"; @@ -2234,7 +2371,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return error; } mixerSessionRecoveryPending_=false; - if(resume)requestAutomaticMain(); + if(resume)requestAutomaticMain(bindingMode!=MixerBindingMode::verifiedAsioRestart); mixerSessionStatus_=engine_.isMonitorEnabled()?"RESTORED_MONITORING":"RESTORED_MUTED"; mixerSessionError_.clear(); diagnostics_.record("DYNAMIC_MIXER_RESTORED",mixerSessionStatus_); @@ -2543,6 +2680,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void onAction (const juce::var& args) { auto action = args.getProperty ("action", {}).toString(); + if(audioDeviceApplyActive_ && action!="audioDeviceApply")return; const auto value = args.getProperty ("value", {}); const int slot = static_cast (args.getProperty ("slot", -1)); if(action=="playerChooseOutput") { @@ -4352,7 +4490,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr lastDirectRestoreError_.clear(); // One-sided device routes are temporary and must never leak into // normal user configuration or the persisted audio-devices.xml. - if (engine_.hasTemporaryDiagnosticDevice()) + if (engine_.hasTemporaryDiagnosticDevice() || + engine_.diagnosticRoute()==armix::diagnostics::Route::mainOutputTone) { const auto error = engine_.setDiagnosticRoute (armix::diagnostics::Route::normal); if (error.isNotEmpty()) return emitNotice (error, true); @@ -4371,9 +4510,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr deviceSettingsDirty_ = true; } using Route = armix::diagnostics::Route; - const auto selected = value.toString(); + auto selected = value.toString(); + if(selected=="TOGGLE_MAIN_OUTPUT_TONE") + selected=engine_.diagnosticRoute()==Route::mainOutputTone?"NORMAL":"MAIN_OUTPUT_TONE"; auto route = Route::normal; if (selected == "OUTPUT_ONLY_TONE") route = Route::outputOnlyTone; + else if (selected == "MAIN_OUTPUT_TONE") route = Route::mainOutputTone; else if (selected == "CAPTURE_ONLY") route = Route::captureOnly; else if (selected == "DRY_THROUGH") route = Route::dryThrough; else if (selected != "NORMAL") return emitNotice ("Unsupported diagnostic mode", true); @@ -4388,8 +4530,11 @@ 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)); - emitNotice ("Audio diagnostic: " + selected + - ". Use low headphone volume and MARK CRACKLE on audible faults."); + if(route==Route::mainOutputTone) + emitNotice("MAIN test tone active. Use low speaker volume. Press Test MAIN output again to stop."); + else + emitNotice ("Audio diagnostic: " + selected + + ". Use low headphone volume and MARK CRACKLE on audible faults."); } else if (action == "diagnosticMark") { @@ -4743,6 +4888,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr fault=engine_.liveOutputArmFault(); if (fault.isEmpty()) { autoMainEpoch_=0; + if(!arm)engine_.cancelAsioResetMonitorIntent(); engine_.setMonitorEnabled(arm); diagnostics_.record("OUTPUT_MUTE",arm?"OFF":"ON"); } @@ -4774,19 +4920,22 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } } - bool finishAudioSetupAndRecoverMixer(bool verifiedDeviceApply=false) { - const bool bound=engine_.finishManualAudioSetup(); + bool finishAudioSetupAndRecoverMixer(MixerBindingMode bindingMode=MixerBindingMode::exact) { + const bool bound=engine_.finishManualAudioSetup(bindingMode!=MixerBindingMode::verifiedMainPinApply); if(!engine_.directRouteAuthorized())return false; const auto lab=engine_.status().getProperty("dryRoutingLab",{}); - if(static_cast(lab.getProperty("nativeChannelIdPcmActive",false)))return true; - if(engine_.hasRetainedNativeSession() || - armix::session::NativeMixerSessionStore(settingsDirectory()).exists()) { - using BindingMode=armix::session::MixerDeviceBindingPolicy::Mode; - const auto error=restoreSavedMixerSession(false,verifiedDeviceApply? - BindingMode::verifiedDeviceApply:BindingMode::exact); + const bool hasCheckpoint=armix::session::NativeMixerSessionStore(settingsDirectory()).exists(); + const bool recoverPristine=bindingMode!=MixerBindingMode::exact && hasCheckpoint && + mixerSessionRecoveryPending_ && engine_.hasPristineStartupMixer(); + if(static_cast(lab.getProperty("nativeChannelIdPcmActive",false)) && + !recoverPristine)return true; + if(engine_.hasRetainedNativeSession() || hasCheckpoint) { + if(bindingMode==MixerBindingMode::exact && engine_.sameRetainedAsioDriver()) + bindingMode=MixerBindingMode::verifiedAsioRestart; + const auto error=restoreSavedMixerSession(false,bindingMode); if(error.isNotEmpty()) { mixerSessionError_=error; - emitNotice("Mixer retained; "+error,true); + emitNotice(error.startsWith("NEEDS_REMAP:")?error.fromFirstOccurrenceOf(": ",false,false):error,true); return false; } return true; @@ -4794,8 +4943,112 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return bound; } + std::uint64_t asioRecoveryEpoch_=0; // last successfully bound generation + armix::device::AsioRestartRecoveryGate asioRecoveryGate_; + + void serviceAsioMixerRestart() { + const auto epoch=engine_.dryRoutingLabEpoch(); + if(epoch==asioRecoveryEpoch_ || !engine_.hasRetainedNativeSession() || + audioDeviceApplyActive_ || (audioSetupWindow_ && audioSetupWindow_->isVisible()) || + nativeShowBusy_ || studioBackupBusy_ || mixerSessionWorker_.busy() || catalog_.busy() || + engine_.isGraphSwitchPending() || engine_.independentClockActive() || + engine_.diagnosticRoute()!=armix::diagnostics::Route::normal)return; + auto* device=engine_.devices().getCurrentAudioDevice(); + if(device) { + if(device->getTypeName()!="ASIO" || + !device->getName().startsWithIgnoreCase("ASIO4ALL") || + !engine_.sameRetainedAsioDriver())return; + } else if(!engine_.selectedRetainedAsioDriverForReopen()) { + // The device pointer disappeared: never open an unapproved or + // guessed driver name, even if ASIO4ALL happens to be installed. + return; + } + const auto now=monotonicMilliseconds(); + asioRecoveryGate_.observeEpoch(epoch,now); + if(!asioRecoveryGate_.due(now))return; // let ASIO4ALL WDM pin inventory settle + const juce::ScopedValueSetter applying(audioDeviceApplyActive_,true); + if(!device || !device->isOpen() || + device->getActiveOutputChannels().countNumberOfSetBits()<2) { + // A missing, closed or output-less ASIO device requires a vendor call. + // Never reopen it repeatedly on each UI timer tick. + if(!asioRecoveryGate_.mayChangeDriver()) { + asioRecoveryGate_.waitForReadback(now); + return; + } + juce::AudioDeviceManager::AudioDeviceSetup setup; + engine_.devices().getAudioDeviceSetup(setup); + // A deliberate 0-IN session remains 0-IN. Never resurrect a mic. + setup.useDefaultInputChannels=!setup.inputChannels.isZero(); + setup.useDefaultOutputChannels=true; + asioRecoveryGate_.driverTransaction(now); + if(!device)diagnostics_.record("ASIO4ALL_DEVICE_MISSING", + "Reopening previously approved registered ASIO driver; no fallback"); + const auto error=openSelectedAudioDevice("ASIO",setup,true); + asioRecoveryGate_.carryInternalEpoch(engine_.dryRoutingLabEpoch()); + device=engine_.devices().getCurrentAudioDevice(); + if(error.isNotEmpty() || !device || !device->isOpen()) { + diagnostics_.record("ASIO4ALL_REOPEN_FAILED",error); + emitApprovedNativeSnapshot(); + return; + } + } + if(!engine_.authorizeRetainedAsioRestart()) { + // Admission can lag driver restart without any driver call. + // It MUST NOT exhaust the bounded reopen/correction allowance. + asioRecoveryGate_.waitForReadback(now); + diagnostics_.record("ASIO4ALL_BIND_NOT_READY","Waiting for verified callback/readback"); + return; + } + if(const auto corrected=engine_.asioRestartPinCorrection()) { + if(!asioRecoveryGate_.mayChangeDriver()) { + asioRecoveryGate_.waitForReadback(now); + diagnostics_.record("ASIO4ALL_PIN_CORRECTION_DEFERRED", + "Driver transaction budget exhausted for this physical epoch"); + return; + } + const auto inputNames=device->getInputChannelNames(); + const auto outputNames=device->getOutputChannelNames(); + asioRecoveryGate_.driverTransaction(now); + const auto error=openSelectedAudioDevice("ASIO",*corrected); + asioRecoveryGate_.carryInternalEpoch(engine_.dryRoutingLabEpoch()); + auto* reopened=engine_.devices().getCurrentAudioDevice(); + if(error.isNotEmpty() || !reopened || !reopened->isOpen() || + reopened->getInputChannelNames()!=inputNames || + reopened->getOutputChannelNames()!=outputNames || + reopened->getActiveInputChannels()!=corrected->inputChannels || + reopened->getActiveOutputChannels()!=corrected->outputChannels || + !engine_.authorizeRetainedAsioRestart()) { + diagnostics_.record("ASIO4ALL_PIN_CORRECTION_FAILED", + error.isNotEmpty()?error:juce::String("Readback changed during correction")); + emitApprovedNativeSnapshot(); + return; + } + } + const auto error=engine_.reattachRetainedAsioMixer()?juce::String{}: + restoreSavedMixerSession(false,MixerBindingMode::verifiedAsioRestart); + if(error.isNotEmpty()) { + // A native graph/FX lease may become ready after the driver's + // current epoch; retry without reopening hardware at an + // exponentially bounded CONTROL cadence. + asioRecoveryGate_.bindFailed(now); + diagnostics_.record("ASIO4ALL_REATTACH_FAILED",error); + emitApprovedNativeSnapshot(); + return; + } + asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); + asioRecoveryGate_.carryInternalEpoch(asioRecoveryEpoch_); + asioRecoveryGate_.recovered(); + mixerSessionStatus_="RESTORED_MUTED"; + mixerSessionError_.clear(); + if(engine_.takeAsioResetMonitorIntent())requestAutomaticMain(false); + if(engine_.isMonitorEnabled())mixerSessionStatus_="RESTORED_MONITORING"; + diagnostics_.record("ASIO4ALL_REATTACHED","Verified driver and current MAIN pair"); + emitApprovedNativeSnapshot(); + } + void changeListenerCallback (juce::ChangeBroadcaster*) override { + if(audioDeviceApplyActive_)return; // synchronous transaction owns recovery // Save device state only after a real change, not on every 3-second tick. deviceSettingsDirty_ = true; // The retention gate closes only on an actual epoch/owner change. @@ -4811,6 +5064,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void timerCallback() override { + if(audioDeviceApplyActive_)return; // a vendor modal loop may re-enter JUCE // Always disabled unless the user explicitly starts a bounded trace. const bool timing = guiPerf_.active; const double tickStart = timing ? juce::Time::getMillisecondCounterHiRes() : 0.0; @@ -4873,11 +5127,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr mixerSessionRecoveryPending_=true; const auto error=restoreSavedMixerSession(startupError_.isEmpty()); if(error.isNotEmpty()) - emitNotice("Saved mixer retained; "+error,true); + emitNotice(error.startsWith("NEEDS_REMAP:")?error.fromFirstOccurrenceOf(": ",false,false):error,true); else deviceSettingsDirty_=true; }else if(startupError_.isEmpty())requestAutomaticMain(); } + serviceAsioMixerRestart(); // ONE actionable notice per unexpected DIRECT reroute. The audio // callback has already zero-filled output atomically; status, log and // WebView notifications belong only on this JUCE control timer. @@ -4891,7 +5146,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr unexpectedRouteNoticeSent_ = true; diagnostics_.record ("DIRECT_ROUTE_BLOCKED", "A device or backend changed unexpectedly; host output held at zero"); - emitNotice ("Audio device changed unexpectedly. Live output muted; confirm your ASIO/WASAPI device in AUDIO SETUP.", true); + if(!engine_.sameRetainedAsioDriver()) + emitNotice ("Audio device changed unexpectedly. Live output muted; confirm your ASIO/WASAPI device in AUDIO SETUP.", true); } if (!blocked) unexpectedRouteNoticeSent_ = false; // Audio thread publishes only fault flags. A bounded message-thread diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index 24cbacda3..68ce4c659 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -1,5 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-only #pragma once +#include #include #include "../engine/core/UnifiedLegacyProductionAdmission.h" #include "NativeShowStore.h" @@ -7,7 +8,9 @@ #include #include #include +#include #include +#include #include // The logical session and its hardware binding are deliberately separate. @@ -24,6 +27,12 @@ struct HardwareBinding final { // still decode without inventing an ASIO pin inventory. juce::StringArray inputNames,outputNames; }; +// A disconnected source has a physical identity but no live PCM ordinal. +struct WaitingAsioInput final { + ChannelId id{}; + int left=-1,right=-1; // physical pin indices, for legacy files without labels + juce::String leftName,rightName; +}; struct StoredInsert final { ChannelId channel{}; std::size_t slot=0; @@ -39,6 +48,7 @@ struct MixerSessionDocument final { LegacyChannelIds legacyIds{}; VerifiedNativeOutputs outputs{}; HardwareBinding binding{}; + std::vector waitingAsioInputs; std::vector inserts; std::vector rackBypassed; float masterGain=1.f; @@ -65,54 +75,90 @@ struct MixerDeviceBindingPolicy final { (!a.monitorEnabled || (a.monitorL==b.monitorL && a.monitorR==b.monitorR)); } - enum class Mode { exact, verifiedDeviceApply }; + enum class Mode { exact, verifiedDeviceApply, verifiedMainPinApply, verifiedAsioRestart }; + static bool isAsio4All(const HardwareBinding& binding) { + return binding.backend=="ASIO" && binding.playback.startsWithIgnoreCase("ASIO4ALL"); + } + static std::optional translateNamedPins( + const juce::BigInteger& previous,const juce::StringArray& oldNames, + const juce::StringArray& newNames) { + juce::BigInteger result; + for(int pin=previous.findNextSetBit(0);pin>=0;pin=previous.findNextSetBit(pin+1)) { + const int next=findSamePin(oldNames,newNames,pin); + if(next<0 || next>=64)return {}; + result.setBit(next); + } + return result; + } + static bool addReturningCapturePins(std::span waiting, + const juce::StringArray& names,juce::BigInteger& mask) { + const auto previous=mask; + for(const auto& patch:waiting) { + const int left=uniquePin(names,patch.leftName); + const int right=uniquePin(names,patch.rightName); + if(left<0 || left>=64 || (patch.right>=0 && (right<0 || right>=64 || right==left)))continue; + mask.setBit(left); + if(patch.right>=0)mask.setBit(right); + } + return mask!=previous; + } static VerifiedNativeOutputs proposedOutputs(const MixerSessionDocument& document, const HardwareBinding& live,int count,Mode mode=Mode::exact) { const auto& saved=document.binding; - if(mode==Mode::verifiedDeviceApply && - (saved.backend!=live.backend || saved.playback!=live.playback)) - return count==2?VerifiedNativeOutputs{count,0,1,-1,-1,false}: - VerifiedNativeOutputs{count,-1,-1,-1,-1,false}; - // A matching endpoint name does NOT prove an unchanged physical - // jack inventory. Reject rather than silently rebase MAIN to 1/2 - // if pin labels changed or an unknown ASIO inventory lost pins. - if(mode==Mode::verifiedDeviceApply && - ((!saved.outputNames.isEmpty() && saved.outputNames!=live.outputNames) || - (saved.outputNames.isEmpty() && live.backend=="ASIO" && - saved.outputMask!=live.outputMask))) - return {count,-1,-1,-1,-1,false}; + const VerifiedNativeOutputs unavailable{count,-1,-1,-1,-1,false}; + if(mode==Mode::verifiedMainPinApply || + (mode==Mode::verifiedDeviceApply && + (saved.backend!=live.backend || saved.playback!=live.playback))) + return count==2?VerifiedNativeOutputs{count,0,1,-1,-1,false}:unavailable; + if(mode==Mode::verifiedAsioRestart && + (!isAsio4All(live) || saved.backend!=live.backend || saved.playback!=live.playback)) + return unavailable; auto outputs=document.outputs; outputs.activeOutputChannels=count; - if(saved.outputMask!=live.outputMask) { - const auto oldPins=mask(saved.outputMask); - const auto newPins=mask(live.outputMask); - outputs.mainL=remapPin(oldPins,newPins,outputs.mainL); - outputs.mainR=remapPin(oldPins,newPins,outputs.mainR); + const auto oldPins=mask(saved.outputMask),newPins=mask(live.outputMask); + if(mode!=Mode::exact || saved.outputMask!=live.outputMask) { + const auto remap=[&](int ordinal) { + return remapPin(oldPins,newPins,saved.outputNames,live.outputNames, + ordinal,live.backend=="ASIO"); + }; + outputs.mainL=remap(outputs.mainL); + outputs.mainR=remap(outputs.mainR); if(outputs.monitorEnabled) { - outputs.monitorL=remapPin(oldPins,newPins,outputs.monitorL); - outputs.monitorR=remapPin(oldPins,newPins,outputs.monitorR); + outputs.monitorL=remap(outputs.monitorL); + outputs.monitorR=remap(outputs.monitorR); } } if(!outputs.valid()) { outputs.monitorL=outputs.monitorR=-1; outputs.monitorEnabled=false; } - // Never substitute the first available pair when the saved MAIN - // physical connectors disappear. Audio may only return after the - // operator explicitly patches MAIN to available output pins. + // The same approved ASIO4ALL driver can expose a different speaker + // after a WDM selection. Adopt the sole verified physical pair. + if(!outputs.valid() && (mode==Mode::verifiedDeviceApply || mode==Mode::verifiedAsioRestart) && + isAsio4All(live) && count>=2) { + // ASIO4ALL can expose virtual and physical WDM outputs together. + // A unique, enabled physical stereo pair is safe to recover even + // when its callback ordinals are 3/4 or arrive in reverse order. + // Ambiguous speakers and virtual-only inventories remain muted. + if(const auto pair=uniqueNamedSpeakerPair(newPins,live.outputNames)) + return {count,pair->first,pair->second,-1,-1,false}; + } return outputs; } static juce::String apply(MixerSessionDocument& document, const HardwareBinding& live, const VerifiedNativeOutputs& outputs, int callbackInputs,Mode mode) { - if(!outputs.valid() || callbackInputs<1 || callbackInputs>256 || - live.backend.isEmpty() || live.capture.isEmpty() || + if(callbackInputs<0 || callbackInputs>256 || + live.backend.isEmpty() || + (callbackInputs>0 && live.capture.isEmpty()) || live.playback.isEmpty() || live.inputMask.isEmpty() || live.outputMask.isEmpty() || !std::isfinite(live.rate) || live.rate<8000. || live.rate>384000. || live.frames<16 || live.frames>8192) return "NEEDS_REMAP: live device verification incomplete"; + if(!outputs.valid()) + return "NEEDS_REMAP: saved MAIN pair unavailable on the active playback pins"; const auto oldPins=mask(document.binding.inputMask); const auto newPins=mask(live.inputMask); if(oldPins.countNumberOfSetBits()!=document.request.physicalInputs || @@ -128,42 +174,71 @@ struct MixerDeviceBindingPolicy final { return exact?juce::String{}:juce::String( "NEEDS_REMAP: select the saved audio device and pin layout in Audio I/O"); - // An Apply of the SAME playback endpoint must keep the saved - // physical MAIN connectors. The current mask only changes their - // ordinals; it never authorizes quietly switching MAIN to another - // jack. Compare against the policy-computed remap even when a caller - // supplies a valid but DIFFERENT output pair. - if(saved.backend==live.backend && saved.playback==live.playback) { - const auto mapped=proposedOutputs(document,live, - outputs.activeOutputChannels,Mode::verifiedDeviceApply); + if(mode==Mode::verifiedMainPinApply || mode==Mode::verifiedAsioRestart || + (saved.backend==live.backend && saved.playback==live.playback)) { + const auto mapped=proposedOutputs(document,live,outputs.activeOutputChannels,mode); if(!mapped.valid() || !sameOutputs(mapped,outputs)) - return "NEEDS_REMAP: saved MAIN output pins are no longer selected; explicitly choose MAIN outputs"; + return "NEEDS_REMAP: MAIN does not match the verified playback pair"; } auto& sources=document.request.sources; - if(saved.backend!=live.backend || saved.capture!=live.capture || - !samePinNames(saved.inputNames,live.inputNames,live.backend)) { - // Different capture hardware invalidates PHYSICAL pins only. - // PlayerDeck is a DEVICE-INDEPENDENT source with no ASIO ordinal. - // Preserve it (still muted until physical output is verified). - sources.erase(std::remove_if(sources.begin(),sources.end(), - [](const DynamicSourcePatch& p) { - return p.kind==DynamicSourceKind::physical; - }),sources.end()); - } else if(oldPins!=newPins) { - std::vector mapped; - mapped.reserve(sources.size()); - for(auto source:sources) { + if(isAsio4All(saved) && isAsio4All(live) && saved.playback==live.playback) { + // Binding playback is independent of capture. Keep the user's + // patch by physical identity until the selected input returns. + auto desired=std::move(document.waitingAsioInputs); + desired.reserve(desired.size()+sources.size()); + std::vector virtualSources; + virtualSources.reserve(sources.size()); + for(const auto& source:sources) { + // ASIO capture remap never translates virtual music into pin 0. if(source.kind==DynamicSourceKind::playerDeck) { - mapped.push_back(source); // no physical input pin to remap + virtualSources.push_back(source); continue; } - source.inputL=remapPin(oldPins,newPins,source.inputL); - if(source.stereo)source.inputR=remapPin(oldPins,newPins,source.inputR); - if(source.inputL>=0 && (!source.stereo || source.inputR>=0)) - mapped.push_back(source); + const auto left=physicalAt(oldPins,source.inputL); + const auto right=physicalAt(oldPins,source.inputR); + desired.push_back({source.id,left,right, + saved.inputNames[left],saved.inputNames[right]}); + } + sources=std::move(virtualSources); + document.waitingAsioInputs.clear(); + for(auto& source:desired) { + const auto* channel=document.roster.find(source.id); + if(!channel || channel->role!=ChannelRole::input)continue; + const auto resolve=[&](int previous,const juce::String& label) { + const auto pin=label.isEmpty()?previous:uniquePin(live.inputNames,label); + return callbackAt(newPins,pin); + }; + const auto left=resolve(source.left,source.leftName); + const auto right=resolve(source.right,source.rightName); + const bool stereo=source.right>=0; + if(left>=0 && (!stereo || (right>=0 && left!=right))) + sources.push_back({source.id,left,right,stereo}); + else + document.waitingAsioInputs.push_back(std::move(source)); + } + } else { + document.waitingAsioInputs.clear(); + if(saved.backend!=live.backend || saved.capture!=live.capture) { + sources.erase(std::remove_if(sources.begin(),sources.end(), + [](const DynamicSourcePatch& p) { + return p.kind==DynamicSourceKind::physical; + }),sources.end()); + } else if(oldPins!=newPins || saved.inputNames!=live.inputNames) { + std::vector mapped; + mapped.reserve(sources.size()); + for(auto source:sources) { + if(source.kind==DynamicSourceKind::playerDeck) { + mapped.push_back(source); + continue; + } + source.inputL=remapPin(oldPins,newPins,saved.inputNames,live.inputNames,source.inputL,false); + if(source.stereo) + source.inputR=remapPin(oldPins,newPins,saved.inputNames,live.inputNames,source.inputR,false); + if(source.inputL>=0 && (!source.stereo || source.inputR>=0))mapped.push_back(source); + } + sources=std::move(mapped); } - sources=std::move(mapped); } document.request.physicalInputs=callbackInputs; document.binding=live; @@ -171,26 +246,75 @@ struct MixerDeviceBindingPolicy final { return {}; } private: - static bool samePinNames(const juce::StringArray& saved,const juce::StringArray& live, - const juce::String& backend) { - return saved.isEmpty()?backend!="ASIO":saved==live; - } static juce::BigInteger mask(const juce::String& text) { juce::BigInteger bits; bits.parseString(text,16); return bits; } - static int remapPin(const juce::BigInteger& saved,const juce::BigInteger& current,int ordinal) { + static std::optional> uniqueNamedSpeakerPair( + const juce::BigInteger& pins,const juce::StringArray& names) { + std::optional> chosen; + for(int leftPin=pins.findNextSetBit(0);leftPin>=0; + leftPin=pins.findNextSetBit(leftPin+1)) { + if(leftPin>=names.size() || uniquePin(names,names[leftPin])!=leftPin)continue; + const auto label=names[leftPin].trim().toLowerCase(); + if(!label.endsWith(" 1"))continue; + const auto stem=label.dropLastCharacters(2); + if(stem.isEmpty() || stem.contains("vb-audio") || stem.contains("cable") || + stem.contains("virtual") || stem.contains("loopback") || + stem.contains("monitor") || + !(stem.contains("realtek") || stem.contains("speaker") || + stem.contains("output with sst")))continue; + int rightPin=-1; + for(int pin=pins.findNextSetBit(0);pin>=0;pin=pins.findNextSetBit(pin+1)) { + if(pin=0)return {}; // duplicate right endpoint + rightPin=pin; + } + } + if(rightPin<0 || uniquePin(names,names[rightPin])!=rightPin)continue; + const int left=callbackAt(pins,leftPin),right=callbackAt(pins,rightPin); + if(left<0 || right<0 || left==right || chosen)return {}; + chosen=std::make_pair(left,right); + } + return chosen; + } + static int uniquePin(const juce::StringArray& names,const juce::String& name) { + if(name.isEmpty())return -1; + const auto pin=names.indexOf(name); + return pin>=0 && names.indexOf(name,false,pin+1)<0?pin:-1; + } + static int findSamePin(const juce::StringArray& previous,const juce::StringArray& live,int pin) { + const auto name=previous[pin]; + return uniquePin(previous,name)==pin?uniquePin(live,name):-1; + } + static int physicalAt(const juce::BigInteger& mask,int ordinal) { if(ordinal<0)return -1; - int physical=saved.findNextSetBit(0); - for(int i=0;i=0;++i) - physical=saved.findNextSetBit(physical+1); - if(physical<0 || !current[physical])return -1; + int pin=mask.findNextSetBit(0); + for(int i=0;i=0;++i)pin=mask.findNextSetBit(pin+1); + return pin; + } + static int callbackAt(const juce::BigInteger& mask,int physical) { + if(physical<0 || !mask[physical])return -1; int index=0; - for(int pin=current.findNextSetBit(0);pinsetProperty(k,v); } + static juce::var pinNames(const juce::StringArray& names) { + juce::Array values; + for(const auto& name:names)values.add(name); + return juce::var(values); + } + static bool readPinNames(const juce::var& value,juce::StringArray& names) { + const auto* values=value.getArray(); + if(!values || values->size()>256)return false; + for(const auto& entry:*values) { + juce::String name; + if(!textField(entry,name,256,true))return false; + names.add(name); + } + return true; + } static juce::var ids(const LegacyChannelIds& ids) { auto v=object(); juce::Array in,aux; @@ -270,7 +409,20 @@ class Codec final { set(bind,"outputMask",d.binding.outputMask); set(bind,"rate",d.binding.rate); set(bind,"frames",d.binding.frames); + if(!d.binding.inputNames.isEmpty())set(bind,"inputNames",pinNames(d.binding.inputNames)); + if(!d.binding.outputNames.isEmpty())set(bind,"outputNames",pinNames(d.binding.outputNames)); set(root,"binding",bind); + if(!d.waitingAsioInputs.empty()) { + juce::Array waiting; + for(const auto& pin:d.waitingAsioInputs) { + auto entry=object(); + set(entry,"id",decimal(pin.id.value)); + set(entry,"left",pin.left);set(entry,"right",pin.right); + set(entry,"leftName",pin.leftName);set(entry,"rightName",pin.rightName); + waiting.add(entry); + } + set(root,"waitingAsioInputs",juce::var(waiting)); + } auto output=object(); set(output,"active",d.outputs.activeOutputChannels); set(output,"mainL",d.outputs.mainL);set(output,"mainR",d.outputs.mainR); @@ -363,7 +515,7 @@ class Codec final { doc.savedMs=static_cast(ms); const auto binding=get(root,"binding"); if(!textField(get(binding,"backend"),doc.binding.backend,128)|| - !textField(get(binding,"capture"),doc.binding.capture,256)|| + !textField(get(binding,"capture"),doc.binding.capture,256,true)|| !textField(get(binding,"playback"),doc.binding.playback,256)|| !textField(get(binding,"inputMask"),doc.binding.inputMask,256)|| !textField(get(binding,"outputMask"),doc.binding.outputMask,256)) @@ -373,6 +525,10 @@ class Codec final { doc.binding.rate=n; if(!integral(get(binding,"frames"),doc.binding.frames,16,8192)) return false; + if((binding.getDynamicObject()->hasProperty("inputNames") && + !readPinNames(get(binding,"inputNames"),doc.binding.inputNames)) || + (binding.getDynamicObject()->hasProperty("outputNames") && + !readPinNames(get(binding,"outputNames"),doc.binding.outputNames)))return false; auto outputs=get(root,"outputs"); if(!integral(get(outputs,"active"),doc.outputs.activeOutputChannels,2,256)|| !integral(get(outputs,"mainL"),doc.outputs.mainL,0,255)|| @@ -442,13 +598,19 @@ class Codec final { (doc.legacyIds.monitor.value&&!seek(doc.legacyIds.monitor,ChannelRole::monitor))) return false; auto req=get(root,"request"); - if(!integral(get(req,"physicalInputs"),doc.request.physicalInputs,1,256)|| + if(!integral(get(req,"physicalInputs"),doc.request.physicalInputs,0,256)|| !integral(get(req,"maxFrames"),doc.request.maxFrames,16,8192)|| !strictBool(get(req,"mainMonoAfterFx"),doc.request.mainMonoAfterFx)) return false; const auto sourcesVar=get(req,"sources"); const auto* sources=sourcesVar.getArray(); + // An all-virtual MUSIC session is legitimate even with zero + // connected capture pins. The per-source decoder below still + // rejects EVERY physical ordinal when physicalInputs == 0. if(!sources||sources->size()>channels->size())return false; + if(doc.binding.capture.isEmpty() && + (doc.request.physicalInputs!=0 || doc.binding.inputMask!="0")) + return false; std::set seenSources; for(const auto& src:*sources) { DynamicSourcePatch p; @@ -477,6 +639,22 @@ class Codec final { } doc.request.sources.push_back(p); } + if(root.getDynamicObject()->hasProperty("waitingAsioInputs")) { + const auto waiting=get(root,"waitingAsioInputs"); + const auto* entries=waiting.getArray(); + if(!entries || entries->size()>channels->size() || + !MixerDeviceBindingPolicy::isAsio4All(doc.binding))return false; + for(const auto& entry:*entries) { + WaitingAsioInput pin; + if(!parseDecimal(get(entry,"id"),pin.id.value) || + !seenSources.insert(pin.id.value).second || !seek(pin.id,ChannelRole::input) || + !integral(get(entry,"left"),pin.left,0,255) || + !integral(get(entry,"right"),pin.right,-1,255) || pin.left==pin.right || + !textField(get(entry,"leftName"),pin.leftName,256,true) || + !textField(get(entry,"rightName"),pin.rightName,256,true))return false; + doc.waitingAsioInputs.push_back(std::move(pin)); + } + } const auto fxVar=get(root,"inserts"),racksVar=get(root,"rackBypassed"); const auto* fx=fxVar.getArray(); const auto* racks=racksVar.getArray(); diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index d4053e2c0..9448a846a 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -1,4 +1,4 @@ -"""Real compiled DOM from G0: first drag without OUT priming, first native +"""Real compiled DOM: hide reference G0, first drag without OUT priming, first native FX picker insert on original CH with structural=false, then vendor editor. Backend isolation is emulated; actual latency/sample evidence is CTest. """ @@ -41,6 +41,72 @@ def main(): addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") page.goto((out/'index.html').as_uri()) page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__?.enabled') + assert page.locator('.console-pane').is_hidden() + # Built-in JUCE DSP must be discoverable before ANY third-party + # VST3 catalog response. The native host never inserts demo FX. + for native_id in ('armix.builtin.channel-eq.v1', + 'armix.builtin.channel-compressor.v1', + 'armix.builtin.arson-harmony.v1'): + assert page.locator('#fastResults [data-fast-id="'+native_id+'"]').count()==1, ( + 'Compiled native FX missing from cold-start picker: '+native_id) + # Output-only playback is a REAL Audio I/O choice, not a hidden + # capture prerequisite. Verify native intent/ACK on the approved + # assembled Windows GUI at every supported viewport. + page.locator('.command-bar [data-native-io]').click() + io_inventory={ + 'types':[{'name':'Windows Audio','separate':True, + 'inputs':['Studio Mic'],'outputs':['Speakers']}], + 'active':{'backend':'Windows Audio','captureDevice':'Studio Mic', + 'playbackDevice':'Speakers','open':True, + 'authorized':True,'deviceGeneration':23, + 'inputNames':['Mic 1'],'outputNames':['L','R'], + 'enabledInputs':[0],'enabledOutputs':[0,1], + 'rate':48000,'buffer':480, + 'rates':[48000],'buffers':[480]}} + emit(page,'arMixAudioDeviceInventory',io_inventory) + capture_select=page.locator('.armix-audio-dialog [data-audio-field="capture"]') + capture_select.select_option(value='') + assert capture_select.input_value()=='' + assert page.locator('.armix-audio-dialog [data-audio-apply]').is_enabled() + page.locator('.armix-audio-dialog [data-audio-apply]').click() + request=page.evaluate("""()=>window.__events.filter(e=> + e.payload?.action==='audioDeviceApply').at(-1)?.payload""") + assert request and request['config']['captureDevice']=='' + assert request['config']['playbackDevice']=='Speakers' + assert request['config']['enabledInputs']==[] + assert request['config']['enabledOutputs']==[] + out_active={**io_inventory['active'],'captureDevice':'', + 'inputNames':[],'enabledInputs':[], + 'outputNames':['WDM L','WDM R','Realtek L','Realtek R']} + emit(page,'arMixAudioDeviceApplyAck',{ + 'requestId':request['requestId'],'ok':True, + 'state':'ACCEPTED_MUTED','active':out_active, + 'outputMuted':True,'mixerBound':True}) + assert page.locator('.armix-audio-shade').is_hidden() + page.locator('.command-bar [data-native-io]').click() + io_inventory['active']=out_active + emit(page,'arMixAudioDeviceInventory',io_inventory) + assert capture_select.input_value()=='' # reopening does not auto-patch a mic + page.locator('.armix-audio-dialog details summary').click() + assign_main=page.locator('[data-audio-main-pins]') + def playback_pin(index): + return page.locator(f'[data-audio-pin="output"][data-pin-index="{index}"]') + playback_pin(0).uncheck() + assert assign_main.is_hidden() + playback_pin(1).uncheck() + playback_pin(2).check() + playback_pin(3).check() + assign_main.click() + repatch=page.evaluate("""()=>window.__events.filter(e=> + e.payload?.action==='audioDeviceApply').at(-1)?.payload""") + assert repatch['config']['assignSelectedPlaybackPinsToMain'] is True + assert repatch['config']['enabledOutputs']==[2,3] + assert repatch['config']['enabledInputs']==[] + emit(page,'arMixAudioDeviceApplyAck',{ + 'requestId':repatch['requestId'],'ok':True, + 'state':'ACCEPTED_MUTED','active':{**out_active,'enabledOutputs':[2,3]}, + 'outputMuted':True,'mixerBound':True}) + assert page.locator('.armix-audio-shade').is_hidden() g0=json.loads((ROOT/'integration/console-v6/fixtures.json').read_text())['g0'] g0['mixerSession']={'authority':'NONE','deviceEpoch':g0['device']['epoch'],'channels':[]} g0['legacyM4']={'active':True,'routeAccepted':False,'routingRevision':'1'} @@ -90,6 +156,9 @@ def show_select(value): emit(page,"arMixNativeSessionAck",{"operation":"OPEN","ok":False,"error":"Invalid mixer JSON"}) assert page.get_by_text("Invalid mixer JSON",exact=True).count()>=1 assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='monitor')") + show_click("Test MAIN output") + assert page.evaluate("()=>window.__events.at(-1).payload")=={ + "action":"diagnosticRoute","value":"TOGGLE_MAIN_OUTPUT_TONE"} show_click("Browse Shows") assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" emit(page,"arMixNativeShowListAck",{"ok":True,"items":[ @@ -124,12 +193,10 @@ def show_select(value): assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" emit(page,"arMixNativeShowListAck",{"ok":True,"items":[]}) assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='monitor')") - if 'collapsed-send' in (page.locator('.console-body').get_attribute('class') or ''): - page.locator('.section-rail [data-section="send"]').click() - # Release before bootstrap SOURCE's later native readback arrives. - drag(page,1,2) + assert page.locator('.console-pane').is_hidden() assert not page.evaluate('()=>window.__nativeIntents.length') state=snapshot() + state['device'].update(enabledInputs=[],inputEndpoints=[]) state['graph']['edges'].pop(1) # genuinely no existing channel send state['graph']['capabilities']['supportedOps'] += ['LOAD_INSERT'] for ident, role, name in [('101','GROUP','Vocal Group'), @@ -142,6 +209,10 @@ def show_select(value): state['legacyM4']={'active':True,'routeAccepted':True,'routingRevision':'77', 'nativeBusStructural':False,'fxInstances':[[] for _ in range(14)]} emit(page,'arMixConsoleSnapshot',state) + page.locator('.console-pane').wait_for(state='visible') + if 'collapsed-send' in (page.locator('.console-body').get_attribute('class') or ''): + page.locator('.section-rail [data-section="send"]').click() + drag(page,1,2) page.wait_for_function('()=>window.__nativeIntents.length===1') route=page.evaluate('()=>window.__nativeIntents[0]') assert route['operation']=='APPLY_WIRE_TRANSACTION' @@ -209,16 +280,16 @@ def show_select(value): channels=copy.deepcopy(retained['graph']['channels'])) emit(page,'arMixConsoleSnapshot',retained) page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__.state().current?.retained') - assert page.locator('.status-bar .warning').inner_text().startswith('NEEDS REMAP') + assert page.locator('.status-bar .warning').inner_text().startswith('PLAYBACK UNAVAILABLE') assert page.locator('[data-native-monitor]').is_disabled() assert add_track.is_disabled() assert page.locator('#tracks .strip').count()==4 - assert 'OUT NEEDS REMAP' in page.locator('#transport').inner_text() + assert 'OUTPUT WAITING FOR DEVICE' in page.locator('#transport').inner_text() page.locator('#tracks .strip[data-id="1"] .wire-node-out').click() emit(page,'arMixConsoleSnapshot',retained) assert page.locator('#tracks .strip[data-id="2"] .wire-gain').is_disabled() strip=page.locator('#tracks .strip[data-id="1"]') - assert strip.locator('select[data-field="input"]').input_value()=='NEEDS REMAP' + assert strip.locator('select[data-field="input"]').input_value()=='Waiting for device' assert strip.locator('.fx-section [data-action="openPlugin"]').first.inner_text()=='Latency VST' before=page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="routingFxEditor").length') strip.locator('.fx-section [data-action="openPlugin"]').first.click() @@ -249,7 +320,8 @@ def show_select(value): 'state':'ACCEPTED_LIVE','active':active,'mixerBound':True,'outputMuted':False}) assert page.locator('.armix-audio-shade').is_hidden() rebound=copy.deepcopy(state) - rebound['device'].update(epoch='93',outputArmed=True) + rebound['device'].update(epoch='93',outputArmed=True, + enabledInputs=g0['device']['enabledInputs'],inputEndpoints=g0['device']['inputEndpoints']) rebound['graph']['revision']='6' rebound['graph']['capabilities']['supportedOps'].append('CREATE_CHANNEL') rebound['mixerSession'].update(deviceEpoch='93',routeRevision='6') diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 31f2539ef..d033abd7f 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -381,7 +381,10 @@ test("P0 first Add FX discovers real local VST3 lazily without an audio-thread s assert.match(bridge,/discoverFxOnFirstPickerOpen\(\);[\s\S]*?scope\?\.openFastPicker/); assert.match(native,/action == "scanVst3"[\s\S]*?catalog_\.scanDefaults\(\)/); assert.match(catalog,/struct Scanner final : juce::Thread/); - assert.match(bridge,/scope\?\.setNativeCatalog\?\.\(\[\.\.\.nativeCatalog\.values\(\)\]\)/); + // The approved picker publishes real compiled-in FX independently of + // external scanner state; the verified VST3 library follows those entries. + assert.match(bridge,/const presentFxCatalog=\(\)=>scope\?\.setNativeCatalog\?\.\(/); + assert.ok(bridge.includes('[...nativeBuiltins,...nativeCatalog.values()]')); // Neither startup nor audio callback can trigger a surprise system scan. assert.doesNotMatch(bridge.slice(0,bridge.indexOf("function discoverFxOnFirstPickerOpen")), /action:"scanVst3"/); @@ -563,7 +566,8 @@ test("P0 WIRE-to-MAIN and channel OUT use one acknowledged native transaction",( assert.match(native,/engine_\.repatchDryRoutingLabChannel\(channel,/); assert.match(bridge,/scope\?\.closeNativePicker\?\.\(\)/); assert.match(builder,/closeNativePicker\(\)\{setFastPicker\(false\);\}/); - assert.match(builder,/NATIVE JUCE VST3/); + assert.match(builder,/Native EQ\/Compressor\/Harmony ready/); + assert.match(builder,/external VST3 require verified scan/); assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); }); test("P0 typed mono-stereo, PAN detent, fader geometry & FX failure diagnostics",()=>{ @@ -703,7 +707,7 @@ test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ assert.match(engine,/MONITOR OFF: VB-Cable capture\/playback self-loop/); assert.match(bridge,/const virtualCableFeedbackPair=/); const native=read("src/Main.cpp"); - assert.match(native,/if\(engine_\.liveOutputArmFault\(\)\.isNotEmpty\(\)\)return;/); + assert.match(native,/if\(engine_\.liveOutputArmFault\(autoMainRequiresInput_\)\.isNotEmpty\(\)\)return;/); assert.match(native,/autoMainEpoch_!=engine_\.dryRoutingLabEpoch\(\)/); }); test("single /preview/ GUI: channel IN, actual OUT and correlated device safety ACK",()=>{ @@ -1238,15 +1242,66 @@ test("P0 native FX rack and per-slot readback update mounted strip without repla assert.equal(paints,2,"an actual VST instance identity change MUST re-project"); }); +test("P0 automatic cold-start Show replaces only pristine SOURCE NONE ChannelId",()=>{ + const main=read('src/Main.cpp'); + const engine=read('src/LiveAudioEngine.h'); + const route=read('src/LiveDryRoutingLab.h'); + assert.match(main,/nativeAlreadyActive && !retained &&/); + assert.match(main,/\(startupOnSavedDevice \|\| recoveringAfterDeviceApply\) &&/); + assert.match(main,/recoveringAfterDeviceApply=bindingMode!=MixerBindingMode::exact &&\s*mixerSessionRecoveryPending_/); + assert.match(main,/!usedPrevious && !retained/); // only normal auto-resume, not recovery admission + assert.match(main,/engine_\.hasPristineStartupMixer\(\)/); + assert.match(main,/restoreNativeMixerSession\(std::move\(doc\),states,\s*replacePristineStartup/); + assert.match(engine,/dryRoutingLab_\.canReplacePristineStartupMixer\(\)/); + assert.match(route,/bool canReplacePristineStartupMixer\(\) const noexcept/); + assert.match(route,/!nativeControlDirty_ && nativeAccepted_\.fxOwners/); +}); + test("P0 startup banner never demands legacy Patch CH1 / Arm wizard",()=>{ const bridge=read("web/approved-native-bridge.js"); assert.match(bridge,/SELECT CHANNEL IN · NATIVE MONITOR AFTER ACK/); - assert.match(bridge,/NO CAPTURE INPUT · OPEN AUDIO I\/O/); + assert.match(bridge,/next.admitted\?"NO HARDWARE IN · MIXER\/FX READY"/); + assert.doesNotMatch(bridge,/hardware\.device\.enabledInputs\.length>0/); assert.match(bridge,/NO VERIFIED INPUT ROUTE · OPEN AUDIO I\/O/); assert.doesNotMatch(bridge,/NO AUDIBLE OUTPUT · PATCH INPUT \+ ARM/); assert.match(bridge,/const preparedFirstSound=session\?\.authority==="NONE"/); assert.match(bridge,/const deviceReady=\(\)=>/); }); +test("P0 native built-in FX appear before vendor scan and remain after catalog refresh",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const builder=read("scripts/build_approved_native_gui.py"); + for(const id of ["armix.builtin.channel-eq.v1", + "armix.builtin.channel-compressor.v1", + "armix.builtin.arson-harmony.v1"]) + assert.ok(bridge.includes('id:"'+id+'"')); + assert.ok(bridge.includes('[...nativeBuiltins,...nativeCatalog.values()]')); + assert.ok(bridge.includes('presentFxCatalog(); // compiled native FX')); + assert.ok(builder.includes("x.format==='Native'?'Native':'VST3'")); + assert.ok(!bridge.includes('scope?.setNativeCatalog?.([])')); +}); +test("P0 built-in EQ/Compressor/Harmony load independent of slow external VST3 catalog scan",()=>{ + const cpp=read("src/Main.cpp"); + const gate=cpp.slice(cpp.indexOf('const bool builtInEq=catalogId=='), + cpp.indexOf('const auto result=builtInEq?',cpp.indexOf('const bool builtInEq=catalogId=='))); + assert.ok(gate.includes('const bool externalCatalog=!builtInEq&&!builtInComp&&!builtInHarmony')); + assert.ok(gate.includes('externalCatalog&&(!plugin||catalog_.busy())')); + assert.ok(!gate.includes('||catalog_.busy()||nativeShowBusy_'), + 'third-party metadata discovery must not disable compiled-in FX'); + assert.ok(gate.includes('nativeShowBusy_')&&gate.includes('studioBackupBusy_'), + 'native structural session/backup safety interlocks remain active'); +}); +test("P0 output-only Audio I/O is a real native configuration, never blocked by missing capture",()=>{ + const cpp=read("src/Main.cpp"),bridge=read("web/approved-native-bridge.js"); + assert.match(cpp,/const bool outputOnly=separate&&capture\.isEmpty\(\)/); + assert.match(cpp,/candidate\.useDefaultInputChannels=!outputOnly/); + assert.match(cpp,/if\(outputOnly\)candidate\.inputChannels\.clear\(\)/); + assert.match(cpp,/\(outputOnly&&!inMask\.isZero\(\)\)/); + assert.doesNotMatch(cpp,/opened->getActiveInputChannels\(\)\.countNumberOfSetBits\(\)<1/); + assert.match(bridge,/No hardware input \(Player \/ FX\)/); + assert.match(bridge,/t\?\.separate\?\["",\.\.\.\(t\.inputs\|\|\[\]\)\]/); + assert.doesNotMatch(bridge,/ack\.active\.enabledInputs\.length>0/); + assert.match(bridge,/FX\/WIRE available/); +}); test("P0 FIRST SOUND G0 offers verified input and leaves automatic MAIN to native",()=>{ const vm=require("node:vm"),sent=[],listeners=new Map(),renderedChoices=[]; let win; diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index dced419c2..576c4386a 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -637,6 +637,11 @@ static void installedCallbackAdmissionRegression(const juce::var& rawBus) { =="9007199254740993"); assert(std::abs(static_cast(session.getProperty("main",{}) .getProperty("db",0.))-(-13.5))<0.00001); + // The installed graph remains editable with playback and no capture pins. + dev.getDynamicObject()->setProperty("enabledInputs",juce::var(juce::Array{})); + assert(projectInstalledNativeChannelIdGraph(snap,live)); + publishAuthoritativeMixerSession(snap); + assert(snap.getProperty("mixerSession",{}).getProperty("authority","").toString()=="CHANNEL_ID"); // Real restart: lab routing epoch counts STOP+START, unlike M2 // deviceStartCount. This G0-to-native authority switch must advance. auto disconnected=canonicalSnapshot(); @@ -826,7 +831,18 @@ static void firstSoundRouteAdmissionRegression() { auto withoutInput=juce::JSON::parse(juce::JSON::toString(snapshot,false)); withoutInput.getProperty("device",{}).getDynamicObject() ->setProperty("enabledInputs",juce::var(juce::Array{})); - assert(!publishVerifiedFirstSoundState(withoutInput,live)); + assert(publishVerifiedFirstSoundState(withoutInput,live)); + assert(withoutInput.getProperty("legacyM4",{}) + .getProperty("channels",{}).getArray()->isEmpty()); // stale MONO mapping rejected + auto noCaptureRoute=juce::JSON::parse(juce::JSON::toString(live,false)); + auto noCaptureRows=noCaptureRoute.getProperty("dryRoutingLab",{}) + .getProperty("acceptedRoute",{}).getProperty("channels",{}); + auto* unpatched=noCaptureRows[4].getDynamicObject(); + unpatched->setProperty("mode","NONE"); + unpatched->setProperty("left",-1); + assert(publishVerifiedFirstSoundState(withoutInput,noCaptureRoute)); + assert(withoutInput.getProperty("legacyM4",{}) + .getProperty("channels",{}).getArray()->size()==10); } // Control-only fixture: validates exclusive M4 session normalization, diff --git a/tests/asio_restart_recovery_gate_test.cpp b/tests/asio_restart_recovery_gate_test.cpp new file mode 100644 index 000000000..07dc41d2e --- /dev/null +++ b/tests/asio_restart_recovery_gate_test.cpp @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/device/AsioRestartRecoveryGate.h" +#ifdef NDEBUG + #undef NDEBUG +#endif +#include +#include +#include + +int main() { + using armix::device::AsioRestartRecoveryGate; + AsioRestartRecoveryGate gate; + assert(!gate.due(999999)); + gate.observeEpoch(21,1000); + assert(!gate.due(1349) && gate.due(1350)); + gate.waitForReadback(1350); // no debit when ASIO panel is still settling + assert(gate.driverTransactions()==0 && !gate.due(2099) && gate.due(2100)); + gate.driverTransaction(2100); + gate.carryInternalEpoch(22); + gate.observeEpoch(22,2150); + assert(gate.trackedEpoch()==22 && gate.driverTransactions()==1); + assert(!gate.due(3299) && gate.due(3300)); + gate.driverTransaction(3300); // pin correction or reopened device + assert(gate.driverTransactions()==2 && !gate.due(7299)); + gate.bindFailed(3350); // never shorten a scheduled driver cool-down + assert(!gate.due(7299) && gate.due(7300)); + gate.driverTransaction(7300); + assert(!gate.mayChangeDriver()); + assert(!gate.due(15299) && gate.due(15300)); + gate.bindFailed(15300); // read-only rebind is still allowed after budget + assert(!gate.due(17699) && gate.due(17700)); + gate.observeEpoch(23,18000); // real external device change reopens budget + assert(gate.driverTransactions()==0 && gate.mayChangeDriver()); + assert(!gate.due(18349) && gate.due(18350)); + gate.recovered(); + assert(gate.driverTransactions()==0); + // avoid overflow across uptime wrap or synthetic test timestamps + gate.observeEpoch(24,std::numeric_limits::max()-10); + assert(!gate.due(std::numeric_limits::max()-1)); + assert(gate.due(std::numeric_limits::max())); +} diff --git a/tests/direct_restore_recovery_contract_test.mjs b/tests/direct_restore_recovery_contract_test.mjs index f9e1ec018..f91ce6bc8 100644 --- a/tests/direct_restore_recovery_contract_test.mjs +++ b/tests/direct_restore_recovery_contract_test.mjs @@ -35,6 +35,19 @@ test('actual device recoveries occur on message thread, not inside audio callbac assert.match(gate,/generation == generation_/); assert.match(gate,/State::exhausted/); }); +test('output-only SAME-device WASAPI recovery never invents or requires microphone pins',()=>{ + const begin=engine.indexOf('bool verifyRestoredDirectDevice ('); + const end=engine.indexOf('void detach()',begin); + assert.ok(begin>0&&end>begin); + const restore=engine.slice(begin,end); + assert.ok(restore.includes('active->getActiveOutputChannels().countNumberOfSetBits()<2')); + assert.ok(!restore.includes('active->getActiveInputChannels().isZero()'), + 'zero actual capture pins must not make a valid output-only mixer unrecoverable'); + assert.ok(restore.includes('current.inputDeviceName == expected.inputDeviceName')); + assert.ok(restore.includes('current.outputDeviceName == expected.outputDeviceName')); + assert.match(engine,/resumeVerifiedDirectRoute\(\)/); + assert.match(main,/No verified stereo playback device; audio remains gated/); +}); test('restore retry is bounded and disabled on success, explicit direct and setup paths',()=>{ assert.match(main,/directRestore_\.failed \(snapshot\.generation, now\)/); assert.match(main,/directRestore_\.recovered \(snapshot\.generation\)/); @@ -87,8 +100,10 @@ test('ASIO/WASAPI DIRECT authorizes the exact active input/output channel map',( } assert.ok(engine.includes('EXACT_ACTIVE_INPUT_AND_OUTPUT_CHANNEL_BITMASKS')); assert.ok(fence.includes('UNEXPECTED_DIRECT_BACKEND_DEVICE_OR_CHANNEL_MASK')); - assert.ok(fence.includes('!validMask(inputMask)')); - assert.ok(fence.includes('!validMask(outputMask)')); + // A real output-only playback session has the canonical zero input mask. + // The exact device fingerprint must still reject absent physical outputs. + assert.ok(fence.includes('!validMask(inputMask,true)')); + assert.ok(fence.includes('!validMask(outputMask,false)')); const callback=engine.slice(engine.indexOf('void audioDeviceIOCallbackWithContext')); assert.ok(callback.indexOf('!directFence_.permitted()')>=0); assert.ok(callback.indexOf('!directFence_.permitted()')