diff --git a/CMakeLists.txt b/CMakeLists.txt index f044cb834..1d1504fbd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,7 +19,7 @@ juce_add_gui_app(ARMixConsole juce_add_binary_data(ARMixAssets SOURCES web/index.html web/styles.css web/app.js web/bridge.js web/monitor.js) -target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/VstOrbitController.h engine/core/MixerRoutingPlan.h engine/core/ChannelRoutingContract.h engine/core/ChannelSendPlan.h engine/core/AuxBusPlan.h engine/core/PreparedMixerBlock.h engine/core/LiveChannelFxGraph.h engine/core/PreparedNativeMixerSession.h engine/core/NativeDryRouteCommand.h engine/core/RealtimeRoutePublisher.h engine/device/LiveInputPortRegistry.h src/LiveDryRoutingLab.h engine/core/OrbitPhase.h engine/core/OrbitControlPolicy.h engine/core/OrbitMotion.h engine/core/OrbitDistanceMapping.h engine/core/DearVrPolarPolicy.h src/PluginCatalog.h src/PluginVault.h src/PortableWorkspace.h src/StudioBackup.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/NativeShowSchema.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/core/CallbackCadenceEvidence.h engine/diagnostics/CrackleEvidenceWindow.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h engine/device/PeriodCapabilityEvidence.h engine/device/SessionLifecycle.h engine/device/WasapiCapabilityProbe.h engine/device/JuceIndependentClockDevice.h engine/device/ClockBridgeSizing.h engine/device/IndependentStreamFormatFence.h engine/device/DirectRestoreBackoff.h engine/device/IndependentStreamWatchdog.h engine/device/BridgeContinuityGate.h engine/device/EndpointIdentityPolicy.h engine/device/WasapiEndpointIdentityGuard.h engine/device/AsioStartupPolicy.h engine/device/AsioPriorityDeviceManager.h engine/device/JuceActivePortSnapshot.h engine/device/AsioRegistrationPolicy.h engine/device/AsioRegistryIdentityProbe.h engine/device/DirectRouteFence.h) +target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/VstOrbitController.h engine/core/MixerRoutingPlan.h engine/core/ChannelRoutingContract.h engine/core/ChannelSendPlan.h engine/core/AuxBusPlan.h engine/core/PreparedMixerBlock.h engine/core/MasterOutputMonoPolicy.h engine/core/LiveChannelFxGraph.h engine/core/PreparedNativeMixerSession.h engine/core/NativeDryRouteCommand.h engine/core/RealtimeRoutePublisher.h engine/device/LiveInputPortRegistry.h src/LiveDryRoutingLab.h engine/core/OrbitPhase.h engine/core/OrbitControlPolicy.h engine/core/OrbitMotion.h engine/core/OrbitDistanceMapping.h engine/core/DearVrPolarPolicy.h src/PluginCatalog.h src/PluginVault.h src/PortableWorkspace.h src/StudioBackup.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/NativeShowSchema.h src/NativeDryShowRecall.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/core/CallbackCadenceEvidence.h engine/diagnostics/CrackleEvidenceWindow.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h engine/device/PeriodCapabilityEvidence.h engine/device/SessionLifecycle.h engine/device/WasapiCapabilityProbe.h engine/device/JuceIndependentClockDevice.h engine/device/ClockBridgeSizing.h engine/device/IndependentStreamFormatFence.h engine/device/DirectRestoreBackoff.h engine/device/IndependentStreamWatchdog.h engine/device/BridgeContinuityGate.h engine/device/EndpointIdentityPolicy.h engine/device/WasapiEndpointIdentityGuard.h engine/device/AsioStartupPolicy.h engine/device/AsioPriorityDeviceManager.h engine/device/JuceActivePortSnapshot.h engine/device/AsioRegistrationPolicy.h engine/device/AsioRegistryIdentityProbe.h engine/device/DirectRouteFence.h) target_compile_definitions(ARMixConsole PRIVATE JUCE_WEB_BROWSER=1 JUCE_USE_WIN_WEBVIEW2=1 @@ -226,7 +226,7 @@ if(BUILD_TESTING) target_compile_features(ARMixShowSchemaTests PRIVATE cxx_std_20) add_test(NAME P4NativeShowSnapshotV2WireRoundTrip COMMAND ARMixShowSchemaTests) juce_add_console_app(ARMixLiveShowCaptureTests PRODUCT_NAME "ArSonMix Live Native Dry Show Capture Tests") - target_sources(ARMixLiveShowCaptureTests PRIVATE tests/native_live_show_capture_test.cpp src/NativeLiveShowCapture.h src/NativeShowStore.h) + target_sources(ARMixLiveShowCaptureTests PRIVATE tests/native_live_show_capture_test.cpp src/NativeLiveShowCapture.h src/NativeDryShowRecall.h src/NativeShowStore.h) target_link_libraries(ARMixLiveShowCaptureTests PRIVATE juce::juce_core juce::juce_cryptography juce::juce_recommended_config_flags) target_compile_features(ARMixLiveShowCaptureTests PRIVATE cxx_std_20) add_test(NAME P4NativeAcknowledgedDryShowCaptureAndStorage COMMAND ARMixLiveShowCaptureTests) diff --git a/docs/P4_NATIVE_DRY_SHOW_BROWSE_RECALL_20261029.md b/docs/P4_NATIVE_DRY_SHOW_BROWSE_RECALL_20261029.md new file mode 100644 index 000000000..d87bd71db --- /dev/null +++ b/docs/P4_NATIVE_DRY_SHOW_BROWSE_RECALL_20261029.md @@ -0,0 +1,19 @@ +# P4 Stage 4 — Native DRY Show Browse & Recall (2026-10-29) + +## Product milestone +ArSonMix now has one actual portable Studio/Shows lifecycle for **verified DRY routing snapshots**: SAVE (previous milestone), BROWSE current stored generations, SELECT immutable Show UUID, and RECALL a real device-bound 10 INPUT + 4 AUX + PRE/POST prepared graph. The UI is not localStorage or a fake preview. BROWSE scans at most 256 directories and displays the newest 64 metadata entries. No disk paths are exposed to the WebView. On RECALL the existing worker hashes/loads the complete immutable stored Show generation away from the audio callback and JUCE paint. + +After disk IO, the control thread rechecks **device epoch and native route revision** taken before dispatch; changed devices, CLEAR PATCH, concurrent routing APPLY, invalid physical input ports, stereo duplicates, unsupported master state, stale session or third-party VST3 all reject before publication. `NativeDryShowRecall::prepare` is pure control-plane and does not mutate caller command on validation failure. Only the original `LiveAudioEngine::applyDryRoutingLab` can apply the prepared graph with DIRECT and OUTPUT MUTE gates, publisher CAS and RT-safe retirement. On success native MASTER linear gain (including true exact-zero), mute and mono are restored; physical output **remains MUTED** and must be checked by the operator before manually arming. + +The existing native 10CH/4AUX processing callback implements MASTER mono with a 64-sample ramp and immediate muted-state priming. No callback allocation, lock, I/O, VST instance creation, graph duplication, per-frame JS repaint or WebView AudioWorklet. The existing CH1 borrowed VST3/Orbit graph is protected; DRY recall rejects any active CH1 FX rack, and stored vendor strip/AUX FX remain unsupported for state/identity safety. It makes **no claim** of port-number equivalence across different computers or audio interfaces. + +## Acceptance / anti-regression +- Native CTest exercises actual on-disk Save→load→decode→prepare, exact 10CH sparse physical indices, BUS/NONE, linear zero, CH and AUX sends, PRE/POST, MASTER mono/gain, and failure rollback for unmuted output, lost port, stale native routing, CH1/AUX VST3. +- Chromium smoke covers bounded native browse, rejecting invalid IDs, intentionally selected UUID recall with device READY, no automatic unmute, and visible negative ACK. +- Output-unmute is blocked while Studio/Shows IO runs; panic MUTE remains immediate. +- The same native IO worker serializes SAVE/BROWSE/RECALL, no redundant background threads or CI workflows. +- All merged B3 #160 changes take precedence; port on current main after its exact-head CI, never overwrite the new unpatched production session with an old operator LAB. +- P0 physical 0-VST crackle #15 remains unresolved and requires actual wired ASIO/WASAPI hardware FAT. This DRY functionality is **not** full VST-equipped Show state/portable licensing compatibility, PDC or hardware AUX OUTPUT patching. + +## Scope and provenance +Extracted carefully from the older #141 concept, **not bulk merged**. All main/JUCE routing adapters, current approved WebView UI, R2 AUX send matrix, FX shared picker and native graph lifecycle remain source-of-truth. Future full FX-equipped Show recall needs snapshot-safe vendor state capture/restore, instance lifetime, plugin affinity and PDC qualification on hardware. diff --git a/engine/core/MasterOutputMonoPolicy.h b/engine/core/MasterOutputMonoPolicy.h new file mode 100644 index 000000000..807ba19ce --- /dev/null +++ b/engine/core/MasterOutputMonoPolicy.h @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include + +// P4 mono master output mode is a control-plane policy with a click-safe +// fixed-sample interpolation. It owns one audio-callback-local scalar. +// No allocation, lock, timer, parameter read, or extra audio buffering. +namespace armix::dsp { +class MasterOutputMonoPolicy final { +public: + static constexpr int transitionSamples=64; + // Hardware output was already gated to silence, so prime the correct + // mono state BEFORE the first unmuted output sample. + void primeWhileMuted(bool mono) noexcept { blend_=mono?1.f:0.f; } + void process(bool mono,float& left,float& right) noexcept { + const float target=mono?1.f:0.f; + constexpr float step=1.f/static_cast(transitionSamples); + if(blend_target)blend_=std::max(target,blend_-step); + if(blend_==0.f)return; + const float center=(left+right)*.5f; + if(blend_==1.f) { + left=right=center; // bit-exact L/R in fully enabled MONO mode + return; + } + left+=blend_*(center-left); + right+=blend_*(center-right); + } + float blend() const noexcept {return blend_;} +private: + float blend_=0.f; // audio thread exclusively +}; +} // namespace armix::dsp diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 2b851d8dc..9a4eb85aa 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -533,6 +533,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { if (std::isfinite (value)) masterGain_.store (juce::Decibels::decibelsToGain (juce::jlimit (-60.f, 10.f, value))); } + // Restored Show snapshots preserve exact linear zero, unlike a dB + // conversion clamped at -60 dB. Message thread, atomic publish only. + void setMasterGainLinear(float value) noexcept { + if(std::isfinite(value) && value>=0.f && value<=2.f) + masterGain_.store(value,std::memory_order_release); + } void setChannelGainDb (float value) noexcept { if (std::isfinite (value)) channelGain_.store (juce::Decibels::decibelsToGain (juce::jlimit (-60.f, 10.f, value))); @@ -1565,7 +1571,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const bool routed=dryRoutingLab_.process(inputs,inputChannels,outputs, outputChannels,samples, masterGain_.load(std::memory_order_relaxed), - !outputPermitted,&ch1Lease,&processLegacyChannelOne); + !outputPermitted,&ch1Lease,&processLegacyChannelOne, + masterMono_.load(std::memory_order_relaxed)); // STOP can race after the outer active() check. Never leave a // callback's output untouched, and NEVER fall through into CH1. if(!routed) { diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 8ec275c27..caf144aae 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only #pragma once #include "../engine/core/PreparedMixerBlock.h" +#include "../engine/core/MasterOutputMonoPolicy.h" #include "../engine/core/LiveChannelFxGraph.h" #include "VstBusLayout.h" #include "../engine/core/NativeDryRouteCommand.h" @@ -383,7 +384,8 @@ class LiveDryRoutingLab final { float* const* outputs,int outputCount,int frames, float masterGain,bool masterMuted, void* externalContext=nullptr, - FxGraph::ExternalStripFx externalFx=nullptr) noexcept { + FxGraph::ExternalStripFx externalFx=nullptr, + bool masterMono=false) noexcept { if(!active())return false; for(auto& p:channelPeaks_)p.store(0.f,std::memory_order_relaxed); for(auto& p:auxPeaks_)p.store(0.f,std::memory_order_relaxed); @@ -436,6 +438,7 @@ class LiveDryRoutingLab final { // Prime a 256-sample fade FROM ZERO for the first unmuted block. // Never interpolate any previously audible sample while muted. if(masterMuted) { + masterMonoPolicy_.primeWhileMuted(masterMono); fadeRemaining_=rampFrames; fadeFromL_=fadeFromR_=0.f; lastOutputL_=lastOutputR_=0.f; @@ -472,6 +475,8 @@ class LiveDryRoutingLab final { r=fadeFromR_+(r-fadeFromR_)*t; --fadeRemaining_; } + // Sample-smoothed, zero-heap dual-mono MASTER output policy. + masterMonoPolicy_.process(masterMono,l,r); outputs[0][offset+i]=l; outputs[1][offset+i]=r; lastOutputL_=l; @@ -563,6 +568,7 @@ class LiveDryRoutingLab final { } private: Publisher publisher_; + armix::dsp::MasterOutputMonoPolicy masterMonoPolicy_; // audio thread only std::array channelEdits_{}; // JUCE message thread only std::array channelFxNames_{}; // status/control thread only std::array auxFxNames_{}; // dedicated bus FX diff --git a/src/Main.cpp b/src/Main.cpp index 961b873f9..4562c3651 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -20,6 +20,7 @@ #include "PortableWorkspace.h" #include "StudioBackup.h" #include "NativeLiveShowCapture.h" +#include "NativeDryShowRecall.h" #include "NativeShowSaveWorker.h" #include #include @@ -1112,6 +1113,132 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr nativeShowBusy_=true; return emitNotice("Saving ACK-verified dry routing to Studio/Shows on the IO worker."); } + if (action == "routingDryShowList") + { + auto rejectList=[this](const juce::String& error) { + if(browser_.loaded) { + auto ack=std::make_unique(); + ack->setProperty("ok",false); + ack->setProperty("error",error); + browser_.emitEventIfBrowserIsVisible( + "arMixNativeShowListAck",juce::var(ack.release())); + } + emitNotice("Native Show browse rejected: "+error,true); + }; + if(nativeShowBusy_ || studioBackupBusy_) + return rejectList("Finish current Show IO or USB backup first."); + auto safe=juce::Component::SafePointer(this); + const auto started=nativeShowWorker_.list(settingsDirectory(), + [safe](armix::shows::NativeShowSaveWorker::Result result) { + if(safe==nullptr)return; + safe->nativeShowBusy_=false; + auto ack=std::make_unique(); + ack->setProperty("ok",result.ok()); + ack->setProperty("error",result.error); + juce::Array items; + for(const auto& item:result.items) { + auto row=std::make_unique(); + row->setProperty("id",item.id); + row->setProperty("name",item.name); + items.add(juce::var(row.release())); + } + ack->setProperty("items",juce::var(items)); + if(safe->browser_.loaded) + safe->browser_.emitEventIfBrowserIsVisible( + "arMixNativeShowListAck",juce::var(ack.release())); + if(result.error.isNotEmpty()) + safe->emitNotice("Native Show browsing failed: "+result.error,true); + }); + if(!started)return rejectList("Cannot start native Show browser."); + nativeShowBusy_=true; + return; + } + if (action == "routingDryShowRecall") + { + const auto id=value.toString(); + auto reject=[this](const juce::String& error) { + if(browser_.loaded) { + auto ack=std::make_unique(); + ack->setProperty("ok",false); + ack->setProperty("error",error); + browser_.emitEventIfBrowserIsVisible( + "arMixNativeShowRecallAck",juce::var(ack.release())); + } + emitNotice("Native DRY Show unchanged: "+error,true); + }; + if(!armix::shows::detail::uuid(id)) + return reject("Select a native Show UUID from the saved list."); + if(nativeShowBusy_ || studioBackupBusy_ || catalog_.busy() || + engine_.isGraphSwitchPending() || !engine_.isOutputMuted()) + return reject("Mute native output and finish ongoing Studio work."); + const auto d=engine_.status().getProperty("dryRoutingLab",{}); + const auto ep=d.getProperty("epoch",{}),rev=d.getProperty("revision",{}); + if(!static_cast(d.getProperty("ready",false)) || + !(ep.isInt()||ep.isInt64()) || + !(rev.isInt()||rev.isInt64())) + return reject("Current native Routing LAB must be active and ACK'd."); + const auto epoch=static_cast(ep); + const auto revision=static_cast(rev); + auto safe=juce::Component::SafePointer(this); + const bool started=nativeShowWorker_.read(settingsDirectory(), + id,epoch,revision, + [safe](armix::shows::NativeShowSaveWorker::Result result) { + if(safe==nullptr)return; + juce::String error=result.error; + juce::var command; + if(error.isEmpty()) { + const auto state=safe->engine_.status(); + const auto lab=state.getProperty("dryRoutingLab",{}); + const auto ep=static_cast( + lab.getProperty("epoch",juce::var(0))); + const auto rev=static_cast( + lab.getProperty("revision",juce::var(0))); + if(ep!=result.requestEpoch || rev!=result.requestRevision) + error="Device epoch or route revision changed during disk read"; + else error=armix::shows::NativeDryShowRecall::prepare( + result.loaded,state,command); + if(error.isEmpty()) { + try { + std::array noVst3{}; + error=safe->engine_.applyDryRoutingLab(command,noVst3); + } catch(const std::exception& ex) { + error="Native DRY Show preparation exception: "+ + juce::String(ex.what()); + } catch(...) { + error="Native DRY Show preparation failed"; + } + } + if(error.isEmpty()) { + // Only AFTER native graph publication, and while + // physical output remains muted. Never auto-unmute. + safe->engine_.setMasterGainLinear( + static_cast(result.loaded.masterGain)); + safe->engine_.setMasterMuted(result.loaded.masterMute); + safe->engine_.setMasterMono(result.loaded.masterMono); + safe->diagnostics_.record("NATIVE_DRY_SHOW_RECALLED", + result.showId+" | "+result.snapshotId); + } + } + safe->nativeShowBusy_=false; + auto ack=std::make_unique(); + ack->setProperty("ok",error.isEmpty()); + ack->setProperty("error",error); + ack->setProperty("showId",result.showId); + ack->setProperty("state",safe->engine_.status().getProperty( + "dryRoutingLab",{})); + if(safe->browser_.loaded) + safe->browser_.emitEventIfBrowserIsVisible( + "arMixNativeShowRecallAck",juce::var(ack.release())); + if(error.isNotEmpty()) + safe->emitNotice("Native Show recall rejected: "+error,true); + else safe->emitNotice( + "Verified DRY Show applied to current native graph. Output remains MUTED; confirm physical routing before unmuting."); + }); + if(!started)return reject("Cannot launch native Show readback worker."); + nativeShowBusy_=true; + return; + } if (action == "routingDryStop") { // Backward-compatible command name: CLEAR PATCH keeps the one @@ -1541,6 +1668,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } else if (action == "monitor" && value.isBool()) { + // Panic MUTE must always work. Do not arm speakers during + // Show readback or Studio USB backup. + if(bool(value) && (nativeShowBusy_ || studioBackupBusy_)) { + emitNotice("Finish Studio/Shows IO before unmuting hardware OUTPUT.",true); + return; + } engine_.setMonitorEnabled (bool (value)); diagnostics_.record ("OUTPUT_MUTE", bool (value) ? "OFF" : "ON"); } diff --git a/src/NativeDryShowRecall.h b/src/NativeDryShowRecall.h new file mode 100644 index 000000000..d759536e8 --- /dev/null +++ b/src/NativeDryShowRecall.h @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "NativeShowSchema.h" +#include "../engine/core/NativeDryRouteCommand.h" +#include +#include + +// P4 stage 4: PREPARE ONLY. Turns a verified persisted DRY Show into +// an explicit new native routing transaction against the *current* live +// epoch and hardware mask. NEVER starts a device, unmutes, or applies a +// route. The caller must use LiveAudioEngine::applyDryRoutingLab to publish. +namespace armix::shows { +class NativeDryShowRecall final { + static juce::var object() {return juce::var(new juce::DynamicObject());} + static void put(juce::var& obj,const char* key,juce::var value) { + obj.getDynamicObject()->setProperty(juce::Identifier(key),std::move(value)); + } + static bool epoch(const juce::var& value,juce::int64& number) { + if(!(value.isInt()||value.isInt64()))return false; + number=static_cast(value); + return number>0; + } +public: + static juce::String prepare(const SnapshotV2& saved, + const juce::var& status, + juce::var& command) { + SnapshotV2 canonical; + if(!Codec::decode(Codec::encode(saved),canonical)) + return "Saved Show failed native schema validation"; + if(!status.isObject() || + !status.getProperty("monitor",{}).isBool() || + static_cast(status.getProperty("monitor",{})) || + !status.getProperty("adaptiveClockActive",{}).isBool() || + static_cast(status.getProperty("adaptiveClockActive",{})) || + status.getProperty("diagnosticRoute",{}).toString()!="NORMAL") + return "MUTE OUTPUT and choose a verified DIRECT device before Show recall"; + // Another native CH1 rack cannot be silently overwritten by DRY recall. + // The route FX counter excludes the borrowed CH1 vendor graph. + const auto borrowed=status.getProperty("chainCount",{}); + if(!borrowed.isInt() || static_cast(borrowed)!=0) + return "Remove CH1 vendor FX before restoring a DRY-only Show"; + const auto lab=status.getProperty("dryRoutingLab",{}); + if(!lab.isObject() || + !lab.getProperty("ready",{}).isBool() || + !static_cast(lab.getProperty("ready",{})) || + !lab.getProperty("active",{}).isBool() || + !static_cast(lab.getProperty("active",{}))) + return "Select a verified DIRECT native 10CH device before recall"; + const auto fx=lab.getProperty("fxCount",{}); + if(!fx.isInt() || static_cast(fx)!=0) + return "Stop native VST3 inserts before restoring a DRY Show"; + juce::int64 currentEpoch=0,currentRevision=0; + if(!epoch(lab.getProperty("epoch",{}),currentEpoch) || + !epoch(lab.getProperty("revision",{}),currentRevision)) + return "Current native device epoch and revision are missing"; + const auto portsValue=lab.getProperty("ports",{}); + const auto* ports=portsValue.getArray(); + if(!ports || ports->isEmpty())return "Verified hardware input mask unavailable"; + auto available=[ports](int target) { + if(target<0)return false; + for(const auto& p:*ports) { + const auto n=p.getProperty("port",{}); + if(n.isInt()&&static_cast(n)==target)return true; + } + return false; + }; + if(canonical.masterPan!=0.0 || canonical.masterGain>2.0 || + !std::isfinite(canonical.masterGain)) + return "Saved MASTER pan/gain is unsupported by this native mixer"; + juce::Array channels,auxes,sends; + for(int i=0;i(i)]; + if(!ch.fx.empty())return "Vendor VST3 state recall is not yet supported"; + const juce::String mode=ch.source==1?"MONO":ch.source==2? + "STEREO":ch.busReturn?"BUS":"NONE"; + if(ch.source>0 && + (!available(ch.inputA) || (ch.source==2&&!available(ch.inputB)))) + return "Saved physical input port is not enabled on current device; remap manually"; + auto v=object(); + put(v,"mode",mode); + put(v,"left",ch.inputA); + put(v,"right",ch.inputB); + put(v,"gain",ch.fader); + put(v,"pan",ch.pan); + put(v,"mute",ch.mute); + put(v,"solo",ch.solo); + put(v,"main",ch.toMaster); + put(v,"fxId",""); + channels.add(v); + for(const auto& s:ch.sends) { + auto row=object(); + put(row,"from",i); + put(row,"to",s.destination); + put(row,"tap",s.preFader?"PRE":"POST"); + put(row,"gain",s.gain); + put(row,"pan",s.pan); + sends.add(row); + } + } + for(int b=0;b(b)]; + if(!bus.fx.empty())return "Vendor AUX VST3 state recall is not supported"; + auto row=object(); + put(row,"enabled",bus.enabled); + put(row,"main",bus.toMaster); + put(row,"mute",bus.mute); + put(row,"gain",bus.gain); + put(row,"fxId",""); + auxes.add(row); + } + for(const auto& s:canonical.auxSends) { + auto row=object(); + put(row,"from",s.source); + put(row,"to",armix::mixer::stripCount+s.destination); + put(row,"tap",s.preFader?"PRE":"POST"); + put(row,"gain",s.gain); + put(row,"pan",s.pan); + sends.add(row); + } + auto proposed=object(); + put(proposed,"deviceEpoch",currentEpoch); + put(proposed,"revision",currentRevision); + put(proposed,"channels",juce::var(channels)); + put(proposed,"auxes",juce::var(auxes)); + put(proposed,"sends",juce::var(sends)); + armix::mixer::NativeDryRouteCommand decoded; + juce::String error; + if(!armix::mixer::NativeDryRouteCommand::decode(proposed,decoded,error)) + return "Saved Show cannot be applied to this routing engine: "+error; + // No partial mutation of caller's command on any failure. + command=std::move(proposed); + return {}; + } +}; +} // namespace armix::shows diff --git a/src/NativeShowSaveWorker.h b/src/NativeShowSaveWorker.h index 8d03a0ded..768ca813e 100644 --- a/src/NativeShowSaveWorker.h +++ b/src/NativeShowSaveWorker.h @@ -2,67 +2,82 @@ #pragma once #include "NativeShowStore.h" #include +#include #include #include #include #include #include +#include -// One opt-in DRY Show per commit, bounded by the existing transactional store. -// All disk I/O and SHA verification run outside the JUCE message/audio threads. -// The worker's native copy cannot observe subsequent live routing mutations. +// Message-thread controller owns one long-lived IO worker. Read/list/commit +// are mutually exclusive. No callback, WebView render or third-party VST +// processor ever executes any file operation or JSON decode. namespace armix::shows { class NativeShowSaveWorker final : private juce::Thread { public: + enum class Operation { save, list, read }; + struct Summary { + juce::String id,name; + juce::int64 modifiedMs=0; + }; struct Result { + Operation operation=Operation::save; juce::String showId, snapshotId, name, error; + juce::int64 requestEpoch=0,requestRevision=0; + std::vector items; + SnapshotV2 loaded; bool ok() const noexcept {return error.isEmpty();} }; using Completion=std::function; - NativeShowSaveWorker() : juce::Thread("ArSonMix Native Show Save") {} + NativeShowSaveWorker() : juce::Thread("ArSonMix Native Show IO") {} ~NativeShowSaveWorker() override { alive_->store(false,std::memory_order_release); signalThreadShouldExit(); stopThread(-1); } bool launch(juce::File studio,SnapshotV2 snapshot,Completion completion) { - if(isThreadRunning() || !completion || !detail::uuid(snapshot.id)) - return false; - studio_=std::move(studio); + if(!reserve(Operation::save,std::move(studio),std::move(completion)) || + !detail::uuid(snapshot.id))return false; snapshot_=std::move(snapshot); - finished_=std::move(completion); + if(startThread())return true; + return false; + } + bool list(juce::File studio,Completion completion) { + if(!reserve(Operation::list,std::move(studio),std::move(completion))) + return false; + return startThread(); + } + bool read(juce::File studio,juce::String showId, + juce::int64 epoch,juce::int64 revision,Completion completion) { + if(!detail::uuid(showId)||epoch<=0||revision<=0 || + !reserve(Operation::read,std::move(studio),std::move(completion))) + return false; + requestedId_=std::move(showId); + requestEpoch_=epoch;requestRevision_=revision; return startThread(); } private: + bool reserve(Operation mode,juce::File studio,Completion completion) { + if(isThreadRunning()||!completion)return false; + operation_=mode;studio_=std::move(studio); + finished_=std::move(completion); + return true; + } void run() override { Result result; - result.snapshotId=snapshot_.id; - result.name=snapshot_.name; - ShowV2 show; - show.id=juce::Uuid().toDashedString().toLowerCase(); - show.name=snapshot_.name; - show.createdMs=snapshot_.createdMs; - show.modifiedMs=snapshot_.modifiedMs; - show.currentSnapshotId=snapshot_.id; - show.snapshotOrder.push_back(snapshot_.id); - result.showId=show.id; + result.operation=operation_; + result.requestEpoch=requestEpoch_; + result.requestRevision=requestRevision_; try { NativeShowStore store(studio_); - result.error=store.commit(show,{snapshot_},{}); - if(result.error.isEmpty()) { - ShowV2 reread; - std::vector snapshots; - result.error=store.load(show.id,reread,snapshots); - if(result.error.isEmpty() && - (reread.currentSnapshotId!=snapshot_.id || - snapshots.size()!=1 || - Codec::encode(snapshots[0])!=Codec::encode(snapshot_))) - result.error="Saved DRY Show verification mismatch"; - } + if(operation_==Operation::save)save(store,result); + else if(operation_==Operation::list)listShows(result); + else readShow(store,result); } catch(const std::exception& e) { result.error="Native Show IO exception: "+juce::String(e.what()); } catch(...) { - result.error="Unknown native Show IO exception; existing Shows untouched"; + result.error="Unknown native Show IO exception; session unchanged"; } auto alive=alive_; auto done=finished_; @@ -72,8 +87,86 @@ class NativeShowSaveWorker final : private juce::Thread { done(std::move(result)); }); } + void save(NativeShowStore& store,Result& result) { + result.snapshotId=snapshot_.id; + result.name=snapshot_.name; + ShowV2 show; + show.id=juce::Uuid().toDashedString().toLowerCase(); + show.name=snapshot_.name; + show.createdMs=snapshot_.createdMs; + show.modifiedMs=snapshot_.modifiedMs; + show.currentSnapshotId=snapshot_.id; + show.snapshotOrder.push_back(snapshot_.id); + result.showId=show.id; + result.error=store.commit(show,{snapshot_},{}); + if(result.error.isNotEmpty())return; + ShowV2 verified; + std::vector snapshots; + result.error=store.load(show.id,verified,snapshots); + if(result.error.isEmpty() && + (verified.currentSnapshotId!=snapshot_.id || + snapshots.size()!=1 || + Codec::encode(snapshots[0])!=Codec::encode(snapshot_))) + result.error="Saved native Show readback mismatch"; + } + // Lightweight bounded metadata listing. Full data+SHA verification is + // performed again by NativeShowStore::load before any recall can apply. + void listShows(Result& result) { + const auto root=studio_.getChildFile("Shows"); + if(!root.isDirectory())return; + juce::DirectoryIterator iter(root,false,"*",juce::File::findDirectories); + int inspected=0; + while(iter.next()) { + if(++inspected>256) { + result.error="Too many Shows to browse safely (256 limit)"; + result.items.clear();return; + } + const auto folder=iter.getFile(); + const auto id=folder.getFileName(); + if(!detail::uuid(id))continue; + const auto head=folder.getChildFile("HEAD"); + if(!head.existsAsFile()||head.getSize()>128)continue; + const auto version=head.loadFileAsString().trim(); + if(!detail::uuid(version))continue; + const auto meta=folder.getChildFile("versions") + .getChildFile(version).getChildFile("show.json"); + if(!meta.existsAsFile()||meta.getSize()>maxJsonBytes)continue; + ShowV2 show; + if(!Codec::decode(meta.loadFileAsString(),show) || + !show.id.equalsIgnoreCase(id)||show.snapshotOrder.empty())continue; + result.items.push_back({show.id,show.name,show.modifiedMs}); + } + std::sort(result.items.begin(),result.items.end(), + [](const Summary& a,const Summary& b) { + if(a.modifiedMs!=b.modifiedMs)return a.modifiedMs>b.modifiedMs; + return a.id64)result.items.resize(64); + } + void readShow(NativeShowStore& store,Result& result) { + result.showId=requestedId_; + ShowV2 show; + std::vector saved; + result.error=store.load(requestedId_,show,saved); + if(result.error.isNotEmpty())return; + if(show.currentSnapshotId.isEmpty()) { + result.error="Saved Show has no current snapshot";return; + } + const auto at=std::find_if(saved.begin(),saved.end(),[&](const SnapshotV2& s) { + return s.id.equalsIgnoreCase(show.currentSnapshotId); + }); + if(at==saved.end()) { + result.error="Saved Show current snapshot missing";return; + } + result.loaded=*at; + result.snapshotId=at->id; + result.name=show.name; + } + Operation operation_=Operation::save; juce::File studio_; SnapshotV2 snapshot_; + juce::String requestedId_; + juce::int64 requestEpoch_=0,requestRevision_=0; Completion finished_; std::shared_ptr> alive_= std::make_shared>(true); diff --git a/tests/live_routing_ui_contract_test.mjs b/tests/live_routing_ui_contract_test.mjs index b0af31e7d..461e5dc8c 100644 --- a/tests/live_routing_ui_contract_test.mjs +++ b/tests/live_routing_ui_contract_test.mjs @@ -256,6 +256,39 @@ test("R2 AUX matrix is a bounded draft projection with PRE/POST and explicit nat assert.doesNotMatch(ui,/arAuxMatrixCell:hover|backdrop-filter:|filter:blur\(/); }); +test("P4 native DRY Shows browse and verified recall are worker-backed and ACK-owned",()=>{ + const main=readFileSync(new URL("../src/Main.cpp",import.meta.url),"utf8"); + const worker=readFileSync(new URL("../src/NativeShowSaveWorker.h",import.meta.url),"utf8"); + const recall=readFileSync(new URL("../src/NativeDryShowRecall.h",import.meta.url),"utf8"); + const engine=readFileSync(new URL("../src/LiveAudioEngine.h",import.meta.url),"utf8"); + const lab=readFileSync(new URL("../src/LiveDryRoutingLab.h",import.meta.url),"utf8"); + assert.match(main,/action == "routingDryShowList"/); + assert.match(main,/action == "routingDryShowRecall"/); + assert.match(main,/arMixNativeShowListAck/); + assert.match(main,/arMixNativeShowRecallAck/); + assert.match(main,/nativeShowWorker_\.read\(/); + assert.match(main,/result\.requestEpoch/); + assert.match(main,/result\.requestRevision/); + assert.match(main,/applyDryRoutingLab\(command,noVst3\)/); + assert.match(main,/setMasterGainLinear\(/); + assert.match(main,/if\(bool\(value\) && \(nativeShowBusy_ \|\| studioBackupBusy_\)\)/); + assert.match(worker,/store\.load\(requestedId_,show,saved\)/); + assert.match(worker,/if\(\+\+inspected>256\)/); + assert.match(worker,/result\.items\.resize\(64\)/); + assert.match(recall,/NativeDryRouteCommand::decode\(proposed,decoded,error\)/); + assert.match(recall,/Remove CH1 vendor FX/); + assert.match(recall,/!available\(ch\.inputA\)/); + assert.match(recall,/command=std::move\(proposed\)/); + assert.match(engine,/setMasterGainLinear\(float value\)/); + assert.match(lab,/masterMonoPolicy_\.process\(masterMono,l,r\)/); + assert.match(ui,/id="arRouteBrowseShows"/); + assert.match(ui,/id="arNativeShowBrowser"/); + assert.match(ui,/arMixNativeShowListAck/); + assert.match(ui,/arMixNativeShowRecallAck/); + assert.match(ui,/nativeShowUuid\.test\(nativeShowSelect\.value\)/); + assert.match(ui,/if\(reply\?\.ok && reply\?\.state\)/); +}); + test("R0B B3 routing GUI has one native engine, truthful UNPATCHED and safe CLEAR PATCH",()=>{ assert.match(ui,/id="arRouteClear"/); assert.doesNotMatch(ui,/id="arRouteStop"/); diff --git a/tests/native_artifact_packaging_contract_test.mjs b/tests/native_artifact_packaging_contract_test.mjs index 2d515c6af..eb611ce67 100644 --- a/tests/native_artifact_packaging_contract_test.mjs +++ b/tests/native_artifact_packaging_contract_test.mjs @@ -61,8 +61,12 @@ test('production Windows workflow rejects a tiny 648KB zip, test EXE, or missing assert.ok(workflow.indexOf('scripts/verify_native_windows_artifact.ps1') < workflow.indexOf('uses: actions/upload-artifact@v4')); }); -test('physical test protocol differentiates actual native channel 1 and GUI-only channels', () => { - assert.match(fat, /native engine implements \*\*Channel 1\*\* only/i); +test('physical hardware FAT documents verified 10CH and dedicated 4 AUX native mixer without claiming hardware qualification', () => { + assert.match(fat, /native 10CH \+ 4 AUX/i); + assert.match(fat, /UNPATCHED \/ SILENT/i); + assert.match(fat, /APPLY ROUTING/); + assert.match(fat, /CLEAR PATCH/); + assert.match(fat, /Experimental; not yet qualified for professional live audio/i); assert.match(fat, /OUTPUT_ONLY_TONE/); assert.match(fat, /CAPTURE_ONLY/); assert.match(fat, /DRY_THROUGH/); diff --git a/tests/native_live_show_capture_test.cpp b/tests/native_live_show_capture_test.cpp index 4e7d76a78..8c9732f6a 100644 --- a/tests/native_live_show_capture_test.cpp +++ b/tests/native_live_show_capture_test.cpp @@ -5,6 +5,8 @@ #include #include #include "../src/NativeLiveShowCapture.h" +#include "../src/NativeDryShowRecall.h" +#include "../engine/core/MasterOutputMonoPolicy.h" #include "../src/NativeShowStore.h" namespace { @@ -136,6 +138,52 @@ int main() { ShowV2 reread;std::vector snaps; assert(store.load(show.id,reread,snaps).isEmpty()); assert(snaps.size()==1&&Codec::encode(snaps[0])==prior); + // P4 stage 4: a verified disk snapshot is PREPARED against current + // native epoch + active sparse physical mask. Only LiveAudioEngine + // may publish the resulting control transaction after mute fencing. + juce::var prepared; + const auto prepareError=NativeDryShowRecall::prepare(snaps[0],setup(),prepared); + if(prepareError.isNotEmpty())std::cerr<<"Recall prep failed: "<(prepared.getProperty("deviceEpoch",{}))==9); + assert(static_cast(prepared.getProperty("revision",{}))==5); + armix::mixer::NativeDryRouteCommand parsed; + juce::String decodeError; + assert(armix::mixer::NativeDryRouteCommand::decode(prepared,parsed,decodeError)); + assert(parsed.channels.stripsAndMaster.strips[0].faderLinear==0.f); + assert(parsed.channels.stripsAndMaster.strips[1].inputB==8); + assert(parsed.sends.count==1&&parsed.aux.count==2); + assert(parsed.aux.sends[0].destination==0); + const auto previous=juce::JSON::toString(prepared,false); + auto absentPort=setup(); + auto absentLab=absentPort.getProperty("dryRoutingLab",{}); + juce::Array tinyMask;auto pp=obj();set(pp,"port",3);tinyMask.add(pp); + set(absentLab,"ports",juce::var(tinyMask)); + assert(NativeDryShowRecall::prepare(snaps[0],absentPort,prepared).isNotEmpty()); + assert(juce::JSON::toString(prepared,false)==previous); + auto unmuted=setup();set(unmuted,"monitor",true); + assert(NativeDryShowRecall::prepare(snaps[0],unmuted,prepared).isNotEmpty()); + auto staleLab=setup();auto staleRouting=staleLab.getProperty("dryRoutingLab",{}); + set(staleRouting,"ready",false); + assert(NativeDryShowRecall::prepare(snaps[0],staleLab,prepared).isNotEmpty()); + auto withVendorFx=snaps[0]; + withVendorFx.aux[0].fx.push_back({"Vendor|123",123, + juce::String("a").paddedRight('a',64),false}); + assert(NativeDryShowRecall::prepare(withVendorFx,setup(),prepared).isNotEmpty()); + auto badMaster=snaps[0];badMaster.masterGain=3.0; + assert(NativeDryShowRecall::prepare(badMaster,setup(),prepared).isNotEmpty()); + assert(juce::JSON::toString(prepared,false)==previous); + + // Mono policy lives in routed native audio callback; no extra buffer + // and no partial stereo leak after silent output arms. + armix::dsp::MasterOutputMonoPolicy mono; + mono.primeWhileMuted(true); + float l=1.f,rr=0.f;mono.process(true,l,rr); + assert(l==0.5f && rr==0.5f); + for(int i=0;i<64;++i){l=1.f;rr=0.f;mono.process(false,l,rr);} + assert(l==1.f && rr==0.f); + assert(mono.blend()==0.f); assert(home.deleteRecursively()); std::cout<<"PASS: actual ACK dry routing capture, 10 INPUT / 4 AUX, bus identity, live linear, master, PRE/POST, stale epoch/plugin/ports rejection, transactional persistence\n"; } diff --git a/tests/ui_smoke.py b/tests/ui_smoke.py index 4a134c5b2..412a469bd 100644 --- a/tests/ui_smoke.py +++ b/tests/ui_smoke.py @@ -1301,6 +1301,22 @@ async def image_for(selector): window.__arMixMockEvents.arMixCatalog({items}); }""") assert await native.locator(".arPatchFxTrigger").count()==14 + # P4: native Show BROWSE is a worker-backed request, not a + # WebView disk access or an implicit LIVE routing mutation. + await native.locator("#arRouteBrowseShows").click() + assert await native.locator("#arNativeShowBrowser").is_visible() + assert await native.locator("#arNativeShowRecall").is_disabled() + assert await native.evaluate( + "()=>window.__arMixSent.some(x=>x.payload?.action==='routingDryShowList')") + await native.evaluate("""()=>window.__arMixMockEvents.arMixNativeShowListAck({ + ok:true,items:[ + {id:"12345678-1234-1234-1234-123456789abc",name:"My Verified DRY Show"}, + {id:"../../unsafe",name:"NEVER TRUST PATHS"} + ] + })""") + assert await native.locator("#arNativeShowSelect option").count()==2 + await native.locator("#arNativeShowSelect").select_option("12345678-1234-1234-1234-123456789abc") + assert await native.locator("#arNativeShowRecall").is_disabled() await native.locator('[data-route-fx]').first.click() assert await native.locator("#arPatchFxPicker").evaluate( "(e)=>e.classList.contains('open')") @@ -1383,6 +1399,24 @@ async def image_for(selector): }""") assert await cell.get_attribute("data-patch-state")=="live" assert await native.locator("#arRouteApply").is_enabled() + # Native Show recall sends one explicit UUID only when a verified + # device is ready and OUTPUT is muted. Rejection keeps route intact. + await native.locator("#arRouteBrowseShows").click() + await native.evaluate("""()=>window.__arMixMockEvents.arMixNativeShowListAck({ + ok:true,items:[{id:"12345678-1234-1234-1234-123456789abc",name:"My Verified DRY Show"}] + })""") + await native.locator("#arNativeShowSelect").select_option("12345678-1234-1234-1234-123456789abc") + assert await native.locator("#arNativeShowRecall").is_enabled() + await native.locator("#arNativeShowRecall").click() + assert await native.evaluate("""()=>window.__arMixSent.some(x=> + x.payload?.action==="routingDryShowRecall" && + x.payload.value==="12345678-1234-1234-1234-123456789abc")""") + assert await native.locator("#arNativeShowRecall").is_disabled() + await native.evaluate("""()=>window.__arMixMockEvents.arMixNativeShowRecallAck({ + ok:false,error:"Device epoch changed" + })""") + assert "REJECTED" in await native.locator("#arNativeShowStatus").inner_text() + # Realistic AUX draft: explicitly enable return, add both taps, # edit gain and REVERT. No native APPLY may fire from matrix edits. await native.locator('[data-patch-tab="internal"]').click() diff --git a/web/monitor.js b/web/monitor.js index 2c2412309..40ce64996 100644 --- a/web/monitor.js +++ b/web/monitor.js @@ -85,6 +85,13 @@ #arRouteApply{background:#95e1b6;border-color:#49a785;color:#18382f} #arPatchRevert{background:#b4c1c6} #arRouteSaveDry{background:#a5b9c1} +#arNativeShowBrowser{margin-top:8px;padding:8px 12px;background:#122933;border-top:1px solid #43606c;color:#c4dce3} +#arNativeShowBrowser[hidden]{display:none} +.arNativeShowLine{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:10px} +#arNativeShowSelect{flex:1;min-width:180px;max-width:500px;background:#0c202a;color:#e3f0f2;border:1px solid #517580;border-radius:3px;padding:6px;font:11px 'Segoe UI',Arial,sans-serif} +#arNativeShowRecall{background:#a5dbbd;color:#173b2f;border:1px solid #3d906d;border-radius:3px;padding:6px 10px;font:600 10px 'Segoe UI',Arial,sans-serif;cursor:pointer} +#arNativeShowRecall:disabled{opacity:.45;cursor:default} +#arNativeShowStatus{flex-basis:100%;color:#a8c2c9;font-size:10px} #arPatchOutputMap{display:flex;gap:10px;flex-wrap:wrap} .arPatchOutput{flex:1 1 180px;padding:16px;background:#0b202a;border:1px solid #3e606e;border-radius:3px} .arPatchOutput b{display:block;margin-bottom:7px;color:#92e9c5;font-size:11px} @@ -178,7 +185,7 @@ '
UNPATCHEDLIVE · NATIVE ACKDRAFT · NOT APPLIEDLIVE UNTIL APPLY
10 CHANNEL INPUT PATCHUses actual enabled ASIO/WASAPI hardware ports
No auto-unmute. Stale devices, incomplete stereo assignments and invalid physical ports are rejected before APPLY. One input can feed multiple channels.
' + '
CHANNEL CONTROL / INTERNAL SENDSNative channel controls, VST3 inserts, 4 AUX returns and PRE/POST sends.

4 DEDICATED AUX / FX RETURNS

Independent stereo return with VST3, level and MAIN route.

CH → AUX SEND MATRIX · PRE / POST

10 channels × 4 AUX returns. Select a cell to edit PRE/POST sends; output changes only after MUTE + APPLY.

Select a CH / AUX cell to inspect sends.

ADVANCED · CH → CH SENDS

Directed channel sends remain available; feedback loops are rejected before native APPLY.

' + '
CURRENT HARDWARE OUTPUTCurrent hardware MAIN L/R is read-only. Configure output in AUDIO SETUP.
AUX-to-hardware-output patching is not available. Select physical device/output in AUDIO SETUP.
' + - '
Select actual input ports, then APPLY while output is muted.
'; + '
Select actual input ports, then APPLY while output is muted.
'; document.body.appendChild(routeOverlay); const draftRoutes=Array.from({length:10},()=>({mode:"NONE",left:-1,right:-1,gain:0.25,pan:0,main:true,mute:false,solo:false,fxId:""})); const draftAux=Array.from({length:4},()=>({enabled:false,gain:1,main:true,mute:false,fxId:""})); @@ -834,6 +841,7 @@ // patchPreflight above already checked epoch, enabled ports and stereo. // Enter pending only after *every* synchronous rejection gate has passed. patchPending=true; + showIdle(); renderPatchMatrix(); document.getElementById("arRouteFeedback").textContent="Applying verified native route (output remains MUTED)..."; api.emitEvent("arMixAction",{action:"routingDryApply",value:{ @@ -848,10 +856,88 @@ if(state.monitor){patchFeedback("MUTE OUTPUT FIRST · clear routing while speakers are safe.");return;} if(!window.confirm("Clear all native INPUT PATCH assignments? OUTPUT remains MUTED."))return; patchPending=true; + showIdle(); renderPatchMatrix(); patchFeedback("Clearing physical input patch; native mixer remains prepared and SILENT..."); api.emitEvent("arMixAction",{action:"routingDryStop"}); }); + document.getElementById("arRouteSaveDry").addEventListener("click",()=>{ + const d=state.dryRoutingLab||{}; + if(!d.ready || !d.active || !d.acceptedRoute || state.monitor || + Number(d.fxCount)!==0 || Number(state.chainCount)!==0){ + document.getElementById("arRouteFeedback").textContent= + "SAVE DRY SHOW requires an ACKnowledged native route, MUTED OUTPUT and zero VST3; no changes saved."; + return; + } + document.getElementById("arRouteFeedback").textContent= + "Saving acknowledged 10 INPUT + 4 AUX DRY state to Studio/Shows (not a live recall)..."; + api.emitEvent("arMixAction",{action:"routingDryShowSave"}); + }); + api.addEventListener("arMixNativeShowSaveAck",ack=>{ + document.getElementById("arRouteFeedback").textContent=ack?.ok + ? "NATIVE SHOW VERIFIED · "+String(ack.showId||"")+" · Studio/Shows · live recall not yet supported" + : "SHOW NOT SAVED · "+String(ack?.error||"Unknown storage failure"); + }); + // P4 Stage 4: native Show browse/recall is explicit, worker-backed and + // fails silent. This UI never treats a localStorage scene as a native Show. + const nativeShowBrowser=document.getElementById("arNativeShowBrowser"); + const nativeShowSelect=document.getElementById("arNativeShowSelect"); + const nativeShowRecall=document.getElementById("arNativeShowRecall"); + const nativeShowStatus=document.getElementById("arNativeShowStatus"); + let nativeShowBusy=false; + const nativeShowUuid=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + function showIdle(){ + nativeShowRecall.disabled=nativeShowBusy||patchPending||!nativeShowUuid.test(nativeShowSelect.value)|| + !!state.monitor||!state.dryRoutingLab?.ready; + } + document.getElementById("arRouteBrowseShows").addEventListener("click",()=>{ + if(nativeShowBusy)return; + nativeShowBrowser.hidden=false; + nativeShowSelect.replaceChildren(new Option("Loading saved native Shows...","")); + nativeShowStatus.textContent="Browsing Studio/Shows on native IO worker..."; + nativeShowBusy=true;showIdle(); + api.emitEvent("arMixAction",{action:"routingDryShowList"}); + }); + nativeShowSelect.addEventListener("change",showIdle); + nativeShowRecall.addEventListener("click",()=>{ + if(nativeShowBusy||patchPending||state.monitor||!state.dryRoutingLab?.ready|| + !nativeShowUuid.test(nativeShowSelect.value))return; + nativeShowBusy=true;showIdle(); + nativeShowStatus.textContent="Reading SHA-verified Show; OUTPUT remains MUTED..."; + api.emitEvent("arMixAction",{action:"routingDryShowRecall",value:nativeShowSelect.value}); + }); + api.addEventListener("arMixNativeShowListAck",reply=>{ + nativeShowBusy=false; + nativeShowSelect.replaceChildren(new Option("Choose a native DRY Show...","")); + if(reply?.ok && Array.isArray(reply.items)){ + for(const item of reply.items.slice(0,64)){ + if(!nativeShowUuid.test(item?.id))continue; + nativeShowSelect.add(new Option(String(item.name||"Native DRY Show"),item.id)); + } + } + nativeShowStatus.textContent=reply?.ok + ?(nativeShowSelect.options.length-1)+" saved native Shows; choose and RECALL while OUTPUT is MUTED." + :"SHOW BROWSE REJECTED · "+String(reply?.error||"Native IO unavailable"); + showIdle(); + }); + api.addEventListener("arMixNativeShowRecallAck",reply=>{ + nativeShowBusy=false; + if(reply?.ok && reply?.state){ + // One authoritative acceptedRoute from native; no local draft can + // invent a LIVE mapping before the revisioned native publication ACK. + state.dryRoutingLab=reply.state; + hydrateAcceptedRoute(); + syncNativeLevelsToRouteDraft(); + if(patchTab==="internal")drawRoutes(); + renderPatchMatrix(); + updateRouteLabIdentity(); + } + nativeShowStatus.textContent=reply?.ok + ?"NATIVE SHOW APPLIED · OUTPUT MUTED. Verify physical input mapping before unmute." + :"SHOW RECALL REJECTED · "+String(reply?.error||"Device/route changed"); + showIdle(); + }); + document.getElementById("arRouteSaveDry").addEventListener("click",()=>{ const d=state.dryRoutingLab||{}; if(!d.ready || !d.active || !d.acceptedRoute || state.monitor || @@ -872,6 +958,7 @@ api.addEventListener("arMixRoutingLabAck",reply=>{ const result=reply?.state||reply||{}; patchPending=false; + showIdle(); if(result && typeof result==="object" && "epoch" in result)state.dryRoutingLab=result; if(reply?.ok===true){ if(result.acceptedRoute)hydrateAcceptedRoute();