From ffde7900707804c8f7fe8b431cef2d6afcc6beae Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 29 Oct 2026 08:01:39 +0700 Subject: [PATCH 1/2] P4 stage 4: native verified DRY Shows browse and muted recall with exact device epoch and port guard --- CMakeLists.txt | 4 +- ..._NATIVE_DRY_SHOW_RECALL_STAGE4_20261029.md | 30 ++++ src/LiveAudioEngine.h | 6 + src/Main.cpp | 119 ++++++++++++++ src/NativeDryShowRecall.h | 130 +++++++++++++++ src/NativeShowSaveWorker.h | 153 ++++++++++++++---- tests/native_live_show_capture_test.cpp | 37 +++++ web/monitor.js | 56 ++++++- 8 files changed, 502 insertions(+), 33 deletions(-) create mode 100644 docs/P4_NATIVE_DRY_SHOW_RECALL_STAGE4_20261029.md create mode 100644 src/NativeDryShowRecall.h diff --git a/CMakeLists.txt b/CMakeLists.txt index d7b30c85f..e04538389 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/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 @@ -223,7 +223,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_RECALL_STAGE4_20261029.md b/docs/P4_NATIVE_DRY_SHOW_RECALL_STAGE4_20261029.md new file mode 100644 index 000000000..282387ba6 --- /dev/null +++ b/docs/P4_NATIVE_DRY_SHOW_RECALL_STAGE4_20261029.md @@ -0,0 +1,30 @@ +# P4 Stage 4 — Verified native DRY Show browse & recall (2026-10-29) + +**Status:** Real native recall transaction for **zero-VST3** saved Shows only, not browser scene simulation or hardware FAT qualification. + +## End-to-end operator path + +1. User manually opens the correct DIRECT ASIO/WASAPI device, verifies visible physical input ports in Routing LAB, APPLYs an initial zero-FX route, and MUTEs physical output. There is **no automatic hardware device selection** from saved files. +2. **BROWSE SHOWS** runs a bounded metadata walk of `Studio/Shows` on the same owned IO worker as SAVE, reading at most 256 Show directories and returning the most recent 64. No filesystem work or SHA hashing on the JUCE callback/GUI paint thread. The browser displays native IDs/names, never untrusted disk paths. +3. **RECALL SELECTED DRY** accepts a strict 36-character UUID, captures the current device epoch+graph revision token, and asks the worker to call the existing SHA-verified `NativeShowStore::load()`. Full manifest, ordered snapshots, AUX, referenced VST3 blob hashes, and bounded generation integrity are checked on read before the snapshot is returned. +4. After IO completes, on the JUCE message thread the app rereads native status and rejects stale epoch/revision, deactivated Routing LAB, unmuted output, independent clock, missing/changed physical input ports, or active VST3. +5. `NativeDryShowRecall::prepare()` decodes/revalidates schema V3, rejects any CH/AUX VST3, unsupported master pan / gain, and produces a **new** `NativeDryRouteCommand` containing actual 10 INPUT channel routing, four dedicated AUX, fader gains including exact zero, PAN/MUTE/SOLO, PRE/POST sends, BUS vs NONE, and master routing. The preflight does **not** publish, load a plugin, touch a hardware device, or mutate caller output on failure. +6. Only the existing `LiveAudioEngine::applyDryRoutingLab` can compile and publish the new immutable prepared graph. Its single-clock DIRECT gate, epoch+revision CAS, hardware sparse-mask validation, zero-VST condition, and RT snapshot retirement remain authoritative. On success, master linear gain/mute/mono apply on the control thread, with hardware output **still MUTED**. Failed preflight or publish leaves the prior route unaffected. +7. GUI shows explicit native ACK/rejection and refreshes routing draft from the *new* native acceptedRoute. **UNMUTE is disabled during any Show IO/USB backup**, preventing disk activity from racing an intentional live output unmute. User must verify input mapping at low headphone volume before explicitly unmuting. + +## Architectural constraints + +- One existing JUCE audio engine, no competing mixer, no callback alloc/lock/I/O/JSON, no third-party VST lifecycle calls in recall. +- Persisted physical port indexes are DEVICE-LOCAL. Existence on the newly selected device is verified, but matching numeric indexes alone are **not** proof of matching microphones: never auto-unmute, manually verify hardware identity/routing on another computer. +- VST3-equipped Shows are **fail-closed** even if all binaries/hashes exist. Correct vendor `getStateInformation` thread affinity and quiescence, cross-vendor state restore, latency/PDC, Orbit state and backup licensing remain future gates. +- The live Routing LAB remains an explicit engineering hardware mode; this milestone is not yet a production-scene playback guarantee. +- A pending Show load checks the captured epoch/revision again after IO; hotplug/STOP/another APPLY cannot publish stale recorded ports. The user may always STOP and keep output muted. + +## Acceptance + +- Native CTest covers end-to-end schema3 on-disk roundtrip, then live preflight conversion (10+4, BUS/NONE identity, sparse physical ports, hard linear zero, CH and AUX PRE/POST, master); rejects missing port, unmuted output, invalid current graph state, vendor VST3 and unsupported master gain without changing previously prepared command. +- Chromium UI smoke must pass for the new native browse/recall controls and event bridge. +- Windows MSVC must rebuild actual JUCE executable and pass all native CTest + embedded UI ZIP integrity. No CI run should be started until this bounded change is ready. +- On actual hardware require manual FAT for DIRECT ASIO/WASAPI, 1/2/10 INPUT, 4 AUX, 128/256/480 frames, STOP/replug, accidental unmute prevention, port identity, readback, zero FX and crackle #15. CI does **not** qualify real hardware. + +Related: #137, merged #138 (AUX Show store), merged #139 (live SAVE), #15 zero-plugin crackle. diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index cffdec53d..5a0d5a24a 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -470,6 +470,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { if (std::isfinite (value)) masterGain_.store (juce::Decibels::decibelsToGain (juce::jlimit (-60.f, 10.f, value))); } + // Validated native Show recall uses exact linear 0 (true silence), + // not a lossy dB roundtrip through -60 dB. + 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))); diff --git a/src/Main.cpp b/src/Main.cpp index 11f24c6d1..af968a0a6 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -19,6 +19,7 @@ #include "PortableWorkspace.h" #include "StudioBackup.h" #include "NativeLiveShowCapture.h" +#include "NativeDryShowRecall.h" #include "NativeShowSaveWorker.h" #include #include @@ -1084,6 +1085,122 @@ 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") + { + if(nativeShowBusy_ || studioBackupBusy_) + return emitNotice("Finish current Show IO or USB backup first.",true); + 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 emitNotice("Cannot start native Show browser.",true); + 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") { engine_.disableDryRoutingLab(); @@ -1501,6 +1618,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } else if (action == "monitor" && value.isBool()) { + if(bool(value) && (nativeShowBusy_ || studioBackupBusy_)) + return emitNotice("Finish Show IO/USB backup before unmuting physical output.",true); 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..6b0014d8c --- /dev/null +++ b/src/NativeDryShowRecall.h @@ -0,0 +1,130 @@ +// 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"; + 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 "Start and ACK the current native Routing LAB session 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/native_live_show_capture_test.cpp b/tests/native_live_show_capture_test.cpp index 5bfcb112e..c40438509 100644 --- a/tests/native_live_show_capture_test.cpp +++ b/tests/native_live_show_capture_test.cpp @@ -5,6 +5,7 @@ #include #include #include "../src/NativeLiveShowCapture.h" +#include "../src/NativeDryShowRecall.h" #include "../src/NativeShowStore.h" namespace { @@ -128,6 +129,42 @@ 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); 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/web/monitor.js b/web/monitor.js index 2512d2d7c..31ea32f1e 100644 --- a/web/monitor.js +++ b/web/monitor.js @@ -36,6 +36,9 @@ ".arRouteFoot{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end;margin-top:12px}.arRouteFoot button,.arRouteClose{color:#f0f7fa;background:#24475a;border:1px solid #587f91;border-radius:4px;padding:8px 12px;cursor:pointer}" + "#arRouteApply{background:#237566;border-color:#4ba48d}#arRouteStop{background:#50343c;border-color:#a8717c}" + "#arRouteFeedback{font-size:11px;min-height:18px;color:#8bdec1;margin-top:10px}" + + "#arSavedShows{margin:12px 0;padding:9px;background:#0c202b;border:1px solid #416071;border-radius:5px}" + + "#arSavedShows label{font-size:11px;color:#b6d9e1;margin-right:8px}#arSavedShowSelect{width:min(100%,340px);font-size:11px;color:#e3f0f5;background:#142b39;border:1px solid #547b8a;border-radius:4px;padding:7px}" + + "#arSavedShows button{padding:7px 10px;margin:4px;border:1px solid #517c89;border-radius:4px;background:#234657;color:#e3f0f5;cursor:pointer;font-size:11px}" + ".arAuxRow{display:grid;grid-template-columns:64px 52px 90px 70px 1fr;align-items:center;gap:7px;padding:7px;background:#0c202b;border-bottom:1px solid #36515f;font-size:11px}.arAuxRow label{display:flex;gap:4px;align-items:center}.arAuxRow select{min-width:0;width:100%;background:#0c202b;color:#dcecf3;border:1px solid #496b7a;padding:6px;border-radius:4px}#arAuxReturns h3{font-size:12px;color:#b1d4dd;margin:14px 0 8px}#arAuxReturns p{color:#90afbc;font-size:10px;margin:4px 0 7px}"; document.head.appendChild(css); // Signal Check is declared in the permanent toolbar; footer holds status only. @@ -73,6 +76,7 @@ '

Real hardware routing test: independent stereo-compatible VST3 insert per channel, PRE/POST sends, and BUS returns. No portable route recall. Use headphones at LOW volume. ' + 'The normal CH1 VST3 host resumes after STOP. Every port shown is from the device active input mask.

' + '

4 DEDICATED AUX / FX RETURNS · INPUT CH1–10 REMAIN AVAILABLE

Each AUX has a separate stereo return, VST3, level and MASTER routing. PRE/POST sends may target AUX1–4 without consuming CH strips.

INTERNAL SENDS · PRE / POST FADER (MAX 32)

' + + '
Current hardware ports only · output stays MUTED · no VST3 recall
' + '
Select channels, BUS returns and sends; APPLY is a native graph transaction.
' + '
'; document.body.appendChild(routeOverlay); @@ -301,10 +305,60 @@ "Saving acknowledged 10 INPUT + 4 AUX DRY state to Studio/Shows (not a live recall)..."; api.emitEvent("arMixAction",{action:"routingDryShowSave"}); }); + const savedShowSelect=document.getElementById("arSavedShowSelect"); + document.getElementById("arShowBrowse").addEventListener("click",()=>{ + document.getElementById("arRouteFeedback").textContent="Reading native Studio/Shows metadata..."; + api.emitEvent("arMixAction",{action:"routingDryShowList"}); + }); + api.addEventListener("arMixNativeShowListAck",ack=>{ + if(!ack?.ok){ + document.getElementById("arRouteFeedback").textContent= + "SHOW BROWSE FAILED · "+String(ack?.error||"Unknown storage error");return; + } + const selected=savedShowSelect.value; + savedShowSelect.replaceChildren(); + const placeholder=document.createElement("option"); + placeholder.value="";placeholder.textContent="Select a saved native Show"; + savedShowSelect.appendChild(placeholder); + for(const item of (Array.isArray(ack.items)?ack.items:[])){ + if(!item || typeof item.id!=="string")continue; + const option=document.createElement("option"); + option.value=item.id;option.textContent=String(item.name||item.id); + savedShowSelect.appendChild(option); + } + if(Array.from(savedShowSelect.options).some(o=>o.value===selected)) + savedShowSelect.value=selected; + document.getElementById("arRouteFeedback").textContent= + "NATIVE SHOW BROWSE · "+(savedShowSelect.options.length-1)+" saved Shows (full verification on recall)"; + }); + document.getElementById("arShowRecall").addEventListener("click",()=>{ + const showId=savedShowSelect.value; + if(!showId){ + document.getElementById("arRouteFeedback").textContent= + "Browse and choose a saved native Show first.";return; + } + const d=state.dryRoutingLab||{}; + if(!d.ready||!d.active||state.monitor||Number(d.fxCount)!==0) { + document.getElementById("arRouteFeedback").textContent= + "RECALL requires current native Routing LAB ACK, MUTED OUTPUT and zero VST3.";return; + } + document.getElementById("arRouteFeedback").textContent= + "Reading and verifying saved Show on IO worker; output remains muted..."; + api.emitEvent("arMixAction",{action:"routingDryShowRecall",value:showId}); + }); + api.addEventListener("arMixNativeShowRecallAck",ack=>{ + if(ack?.state&&typeof ack.state==="object")state.dryRoutingLab=ack.state; + document.getElementById("arRouteFeedback").textContent=ack?.ok + ? "NATIVE SHOW RECALL ACK · verified routing published · OUTPUT STAYS MUTED" + : "RECALL REJECTED · "+String(ack?.error||"Unknown native error"); + if(ack?.ok){hydrateAcceptedRoute();drawRoutes();} + updateRouteLabIdentity(); + }); api.addEventListener("arMixNativeShowSaveAck",ack=>{ document.getElementById("arRouteFeedback").textContent=ack?.ok - ? "NATIVE SHOW VERIFIED · "+String(ack.showId||"")+" · Studio/Shows · live recall not yet supported" + ? "NATIVE SHOW VERIFIED · "+String(ack.showId||"")+" · Studio/Shows" : "SHOW NOT SAVED · "+String(ack?.error||"Unknown storage failure"); + if(ack?.ok)api.emitEvent("arMixAction",{action:"routingDryShowList"}); }); api.addEventListener("arMixRoutingLabAck",reply=>{ const result=reply?.state||reply||{}; From 1267acc682146c01d091defc10e1933845ae17af Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 29 Oct 2026 08:17:24 +0700 Subject: [PATCH 2/2] P4 recall hardening: correct mono-master RT render and master SSOT sync, native and Chromium regression --- CMakeLists.txt | 2 +- ..._NATIVE_DRY_SHOW_RECALL_STAGE4_20261029.md | 2 +- engine/core/MasterOutputMonoPolicy.h | 33 ++++++++++++++ src/LiveAudioEngine.h | 3 +- src/LiveDryRoutingLab.h | 8 +++- tests/prepared_mixer_block_test.cpp | 16 +++++++ tests/ui_smoke.py | 21 +++++++++ web/bridge.js | 43 ++++++++++++------- 8 files changed, 108 insertions(+), 20 deletions(-) create mode 100644 engine/core/MasterOutputMonoPolicy.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e04538389..773311e10 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/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_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 diff --git a/docs/P4_NATIVE_DRY_SHOW_RECALL_STAGE4_20261029.md b/docs/P4_NATIVE_DRY_SHOW_RECALL_STAGE4_20261029.md index 282387ba6..c391ca525 100644 --- a/docs/P4_NATIVE_DRY_SHOW_RECALL_STAGE4_20261029.md +++ b/docs/P4_NATIVE_DRY_SHOW_RECALL_STAGE4_20261029.md @@ -9,7 +9,7 @@ 3. **RECALL SELECTED DRY** accepts a strict 36-character UUID, captures the current device epoch+graph revision token, and asks the worker to call the existing SHA-verified `NativeShowStore::load()`. Full manifest, ordered snapshots, AUX, referenced VST3 blob hashes, and bounded generation integrity are checked on read before the snapshot is returned. 4. After IO completes, on the JUCE message thread the app rereads native status and rejects stale epoch/revision, deactivated Routing LAB, unmuted output, independent clock, missing/changed physical input ports, or active VST3. 5. `NativeDryShowRecall::prepare()` decodes/revalidates schema V3, rejects any CH/AUX VST3, unsupported master pan / gain, and produces a **new** `NativeDryRouteCommand` containing actual 10 INPUT channel routing, four dedicated AUX, fader gains including exact zero, PAN/MUTE/SOLO, PRE/POST sends, BUS vs NONE, and master routing. The preflight does **not** publish, load a plugin, touch a hardware device, or mutate caller output on failure. -6. Only the existing `LiveAudioEngine::applyDryRoutingLab` can compile and publish the new immutable prepared graph. Its single-clock DIRECT gate, epoch+revision CAS, hardware sparse-mask validation, zero-VST condition, and RT snapshot retirement remain authoritative. On success, master linear gain/mute/mono apply on the control thread, with hardware output **still MUTED**. Failed preflight or publish leaves the prior route unaffected. +6. Only the existing `LiveAudioEngine::applyDryRoutingLab` can compile and publish the new immutable prepared graph. Its single-clock DIRECT gate, epoch+revision CAS, hardware sparse-mask validation, zero-VST condition, and RT snapshot retirement remain authoritative. On success, master linear gain/mute/mono apply on the control thread, with hardware output **still MUTED**. Failed preflight or publish leaves the prior route unaffected. Dedicated MASTER MONO is now honored by the native Routing LAB callback: zero-allocation 64-sample stereo-to-mono ramp while unmuted, primed to exact mono while hardware output is muted. MASTER controls are synchronized through one native bridge helper for both CH1 and LAB paths; prior LAB early return may no longer skip the master fader/MUTE/MONO state. 7. GUI shows explicit native ACK/rejection and refreshes routing draft from the *new* native acceptedRoute. **UNMUTE is disabled during any Show IO/USB backup**, preventing disk activity from racing an intentional live output unmute. User must verify input mapping at low headphone volume before explicitly unmuting. ## Architectural constraints 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 5a0d5a24a..544847fcf 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1326,7 +1326,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const bool routed=dryRoutingLab_.process(inputs,inputChannels,outputs, outputChannels,samples, masterGain_.load(std::memory_order_relaxed), - !outputPermitted); + !outputPermitted, + 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 778eef173..cf5308654 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" @@ -324,7 +325,7 @@ class LiveDryRoutingLab final { // A failed run never falls through to an unrelated microphone/plugin path. bool process(const float* const* inputs,int inputCount, float* const* outputs,int outputCount,int frames, - float masterGain,bool masterMuted) noexcept { + float masterGain,bool masterMuted,bool masterMono) 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); @@ -365,6 +366,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); // RT-only; no startup stereo leak fadeRemaining_=rampFrames; fadeFromL_=fadeFromR_=0.f; lastOutputL_=lastOutputR_=0.f; @@ -400,6 +402,9 @@ class LiveDryRoutingLab final { r=fadeFromR_+(r-fadeFromR_)*t; --fadeRemaining_; } + // 64-sample click-safe mono transition, with exact dual-mono + // L/R at blend=1. No extra device quantum or buffer latency. + masterMonoPolicy_.process(masterMono,l,r); outputs[0][offset+i]=l; outputs[1][offset+i]=r; lastOutputL_=l; @@ -490,6 +495,7 @@ class LiveDryRoutingLab final { } private: Publisher publisher_; + armix::dsp::MasterOutputMonoPolicy masterMonoPolicy_; // audio callback only std::array channelEdits_{}; // JUCE message thread only std::array channelFxNames_{}; // status/control thread only std::array auxFxNames_{}; // dedicated bus FX diff --git a/tests/prepared_mixer_block_test.cpp b/tests/prepared_mixer_block_test.cpp index 326eb4796..4bbc7c640 100644 --- a/tests/prepared_mixer_block_test.cpp +++ b/tests/prepared_mixer_block_test.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/core/PreparedMixerBlock.h" +#include "../engine/core/MasterOutputMonoPolicy.h" #if defined(NDEBUG) #undef NDEBUG // P1D must run assertions even under MSVC Release. #endif @@ -140,6 +141,21 @@ int main() { assert(!fold.process(audio,4,outputL.data(),outputR.data(),9,noFx)); for(int i=0;i<9;++i)assert(outputL[i]==0.f&&outputR[i]==0.f); + // Real master output policy: mute primes full mono; live stereo <-> mono + // ramps without allocating or adding an output frame of latency. + armix::dsp::MasterOutputMonoPolicy monoPolicy; + float monoL=.3f,monoR=.7f; + monoPolicy.primeWhileMuted(true); + const auto monoAlloc=allocations.load(std::memory_order_relaxed); + monoPolicy.process(true,monoL,monoR); + assert(monoL==monoR && near(monoL,.5f)); + assert(allocations.load(std::memory_order_relaxed)==monoAlloc); + for(int n=0;n<64;++n){monoL=.3f;monoR=.7f;monoPolicy.process(false,monoL,monoR);} + assert(monoPolicy.blend()==0.f && near(monoL,.3f)&&near(monoR,.7f)); + for(int n=0;n<64;++n){monoL=.3f;monoR=.7f;monoPolicy.process(true,monoL,monoR);} + assert(monoPolicy.blend()==1.f && monoL==monoR); + assert(allocations.load(std::memory_order_relaxed)==monoAlloc); + // Repeat block execution to verify no cumulative send residue / leakage. for(int i=0;i<1000;++i) { const auto pre=allocations.load(std::memory_order_relaxed); diff --git a/tests/ui_smoke.py b/tests/ui_smoke.py index 11cfff9f0..0bba192ab 100644 --- a/tests/ui_smoke.py +++ b/tests/ui_smoke.py @@ -1169,6 +1169,27 @@ async def image_for(selector): return Number.parseFloat(l.style.getPropertyValue('--led-lit'))>7 && Number.parseFloat(r.style.getPropertyValue('--led-lit'))>7; }""",timeout=3000) + # Native P4 recall MUST synchronize MASTER even while 10CH Lab + # controls are acknowledged. The old bridge returned early here. + await native.evaluate("""()=>{ + window.__arMixMockEvents.arMixStatus({ + connected:true,error:'',driver:'Windows Audio',rate:48000,buffer:480, + monitor:false,channelDb:0,masterDb:-12,channelPan:0, + masterMute:true,masterMono:true, + inputPeak:0,peak:0,peakLeft:0,peakRight:0, + deviceOutputChannels:2, + dryRoutingLab:{active:true,ready:true,epoch:9,revision:5, + channelControls:Array.from({length:10},()=>({ + db:0,pan:0,mute:false,solo:false + })),channelPeaks:Array(10).fill(0)} + }); + }""") + await native.wait_for_function("""()=>{ + const m=document.querySelector('[data-fader="master"]'); + return Number(m?.getAttribute('aria-valuenow'))===-12 && + document.querySelector('#masterMute')?.getAttribute('aria-pressed')==="true" && + document.querySelector('#masterMode')?.getAttribute('aria-pressed')==="true"; + }""",timeout=3000) assert not native_errors,native_errors await native.close() await browser.close() diff --git a/web/bridge.js b/web/bridge.js index f5df81da9..eb9af8570 100644 --- a/web/bridge.js +++ b/web/bridge.js @@ -1256,6 +1256,29 @@ for(const event of ["pointerdown","pointerup","pointercancel","wheel","keydown"]) document.addEventListener(event,markNativeUiEdit,true); // A restored GUI-only snapshot must not masquerade as a live native setting. + // MASTER belongs to the same native SSOT in both the CH1 host and + // 10CH Routing LAB. Never return before syncing it on a recall ACK. + // Called on existing telemetry, no extra DOM polling/RAF work. + function syncNativeMasterControls(d,editing){ + let changed=false; + const masterDb=Number(d.masterDb); + if(!editing && Number.isFinite(masterDb) && + typeof masterGain!=="undefined" && Math.abs(masterGain-masterDb)>.05){ + masterGain=masterDb;changed=true; + const fader=document.querySelector('[data-fader="master"]'); + if(fader){fader.querySelector(".cap")?.style.setProperty("--pos",levelToTop(masterDb)+"%");fader.setAttribute("aria-valuenow",masterDb.toFixed(1));} + document.querySelectorAll(".master-db").forEach(e=>e.textContent=fmt(masterDb)); + } + if(typeof masterMute!=="undefined" && typeof d.masterMute==="boolean" && masterMute!==d.masterMute){ + masterMute=d.masterMute;changed=true; + const mute=document.querySelector("#masterMute"); + if(mute){mute.classList.toggle("active",masterMute);mute.setAttribute("aria-pressed",String(masterMute));} + } + if(typeof masterMono!=="undefined" && typeof d.masterMono==="boolean" && masterMono!==d.masterMono){ + setMasterMono(d.masterMono,false);changed=true; + } + return changed; + } function syncNativeMixerControls(d){ if(typeof channels==="undefined" || !channels[0])return; const lab=d.dryRoutingLab; @@ -1288,12 +1311,13 @@ if(b){b.classList.toggle("active",ch[key]);b.setAttribute("aria-pressed",String(ch[key]));} } } + if(syncNativeMasterControls(d,editing))changed=true; if(changed)patchMixer(); return; } - const channelDb=Number(d.channelDb), masterDb=Number(d.masterDb); + const channelDb=Number(d.channelDb); const channelPan=Math.round(Number(d.channelPan)*100); - if(!Number.isFinite(channelDb)||!Number.isFinite(masterDb)||!Number.isFinite(channelPan))return; + if(!Number.isFinite(channelDb)||!Number.isFinite(channelPan))return; const channel=channels[0]; const editing=Date.now()0.05){ - masterGain=masterDb;changed=true; - const fader=document.querySelector('[data-fader="master"]'); - if(fader){fader.querySelector(".cap")?.style.setProperty("--pos",levelToTop(masterDb)+"%");fader.setAttribute("aria-valuenow",masterDb.toFixed(1));} - document.querySelectorAll(".master-db").forEach(e=>e.textContent=fmt(masterDb)); - } - if(typeof masterMute!=="undefined" && typeof d.masterMute==="boolean" && masterMute!==d.masterMute){ - masterMute=d.masterMute;changed=true; - const mute=document.querySelector("#masterMute"); - if(mute){mute.classList.toggle("active",masterMute);mute.setAttribute("aria-pressed",String(masterMute));} - } - if(typeof masterMono!=="undefined" && typeof d.masterMono==="boolean" && masterMono!==d.masterMono){ - setMasterMono(d.masterMono,false);changed=true; - } + if(syncNativeMasterControls(d,editing))changed=true; if(changed)patchMixer(); } backend.addEventListener("arMixStatus",d=>{