diff --git a/AR-MIX-Live-FX-Host-Standalone-v0.3.html b/AR-MIX-Live-FX-Host-Standalone-v0.3.html index be538ea4c..61e38caee 100644 --- a/AR-MIX-Live-FX-Host-Standalone-v0.3.html +++ b/AR-MIX-Live-FX-Host-Standalone-v0.3.html @@ -5449,5 +5449,184 @@ document.documentElement.dataset.arMixerShell='rail-modes'; })(); + + diff --git a/CMakeLists.txt b/CMakeLists.txt index c12e3a0af..fdc0d5fb2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,9 +17,9 @@ juce_add_gui_app(ARMixConsole NEEDS_CURL FALSE) juce_add_binary_data(ARMixAssets SOURCES - web/index.html web/styles.css web/plugin-ui.css web/app.js web/plugin-ui.js web/bridge.js web/monitor.js web/mixer-io.js web/mixer-io.css web/mixer-layout.js web/mixer-layout.css web/assets/audio-interface.svg) + web/index.html web/styles.css web/plugin-ui.css web/app.js web/plugin-ui.js web/bridge.js web/monitor.js web/mixer-io.js web/mixer-io.css web/mixer-layout.js web/mixer-layout.css web/studio-bus.js web/studio-bus.css web/assets/audio-interface.svg) -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/FactoryFxRegistry.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/LiveSecondaryOutputDevice.h engine/core/LiveOutputRouteGate.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 src/LiveDynamicBusSession.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/FactoryFxRegistry.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/LiveSecondaryOutputDevice.h engine/core/LiveOutputRouteGate.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/M3E_LIVE_NATIVE_GROUP_CALLBACK_FAT_20261101.md b/docs/M3E_LIVE_NATIVE_GROUP_CALLBACK_FAT_20261101.md new file mode 100644 index 000000000..eb8c02e7e --- /dev/null +++ b/docs/M3E_LIVE_NATIVE_GROUP_CALLBACK_FAT_20261101.md @@ -0,0 +1,28 @@ +# M3E — actual live independent Group in ONE JUCE hardware callback + +2026-11-01 · ArSonMix Studio Console · native pilot for physical 0FX testing + +## This is a real vertical slice, not another offline-only test +New `src/LiveDynamicBusSession.h` prepares **11 existing ChannelIds (CH01–10 + MAIN) plus an independent Group**. Native `DynamicChannelRoster::createBusForSelected` rewrites the selected channels' **exclusive primary OUT** to the Group, and Group OUT→MAIN. The Group is **ChannelId #12**, not a spare CH10 channel; the input-bank size stays 10. Prepared PCM is compiled and atomically published under actual device epoch, verified input pin callback ordinals, current physical MAIN output pair, and all-outputs-disarmed gate. A failure changes nothing audible/accepted. + +`LiveAudioEngine::audioDeviceIOCallbackWithContext` is still the **single registered JUCE callback**. For one accepted native Group it uses the dynamic published PCM **INSTEAD of** the existing `LiveDryRoutingLab::process` (never both); MAIN renders on actually ACKed physical L/R. The same output fence, MUTE, secondary-output guard, input PCM diagnostics, loudness/meter path and callback timing remain. Stale device epochs or invalid ports fail silent. A bounded 256-sample first-unmute Group fade protects the physical output on a structural handoff. UI Stage/ACK never performs audio processing. + +The native Group has a **real fader**: browser -60..+10 dB → guarded native `ChannelId` atomic parameter → 64-sample DSP ramp. The BUS source count and named fan-in come from the **same prepared PCM revision** returned by `DynamicConsoleRoutingView`; not a fake browser assignment. Ctrl/Shift-click on existing input names selects multiple physical inputs. A compact GROUP rail shows live group ID, source names, and STOP GROUP. JS/HTML are mirrored for native and offline preview (preview is never described as audio live). + +## Deliberate admission limits (do NOT silently lose the user's Show) +This opt-in M3E cutover is the first audible **dry Group** pilot: one Group, no existing VST3, auxiliary sends/returns, internal channel sends, independent MONITOR patch, or borrowed legacy BUS strips. The engine rejects these cases explicitly and preserves the original native 10CH graph without changing the user's accepted route. Dynamic VST3 lease transfer from M4 #261, MASTER plugins, multi-Group editing, persistent V5 Show and full native parameter parity remain separate. While the pilot owns PCM, old 10CH routing, FX bypass/edits, source switching and Show capture cannot falsely ACK changes not audible in the new graph. STOP GROUP (after MUTE+secondary DISARM) returns to the untouched original 10CH route. Device change immediately invalidates the Group and prevents stale output. + +## Physical FAT protocol — Maono PS22 / normal Windows endpoint +1. Use a Windows executable built from **this exact branch HEAD**, not an earlier main artifact; otherwise this feature is absent. +2. Configure and **APPLY** verified ASIO Maono / WASAPI device and capture pins. Native status must read back actual driver + output L/R; choose and APPLY input source CH01 and CH02, verify raw input PCM with no FX. +3. **MUTE hardware MAIN and DISARM secondary stream**. Ctrl-click CH01 and CH02 names in Mixer, choose **+ BUS FOR SELECTED**. Verify positive **native ACK**, Group ID **12**, fan-in **CH1+CH2**, and Group OUT→physical MAIN. +4. ARM MAIN with the existing verified audio-safety workflow, headphone volume low. Listen to two inputs; compare direct mix before Group with Group unity: no doubled dry. Move native Group fader to -6 dB: MAIN signal should drop about 6 dB in both channels without graph restart/crackle. +5. MUTE output and **STOP GROUP**. The exact previous 10CH accepted route must return. Switch output pins or restart device; stale Group status must disappear, not route to unexpected hardware. +6. Record whether crackles occur with **0 VST**, along with driver identity, rate/buffer, capture discontinuities, raw input PCM, callback cadence and output routing. #15 is **not** closed by a successful CTest. + +## Next meaningful milestone (M4→M5) +Finish #261 unified live VST3 CH1–10 leases, then move the SAME leases into the dynamic ChannelId slot adapter so a real **new Group can own compressor/EQ** and FX Return can host reverb. Convert monitor/AUX/Show snapshot by stable ID in one accepted transaction and turn off this restricted-pilot gate only when native PCM+vendor chunk+device-epoch tests pass. Then offer true standalone Add Channel/Add Bus/Add FX with keyed strips and professional comprehensive routing. Preserve one callback and no DAW timeline, recorder, OBS-only output, duplicated graph, or extra latency claims. + +## Evidence gates +- New 10 input+MAIN+Group (12 IDs) native PCM regression proves exclusive primary Group routing, unity/no double dry, actual Group live -6 dB, output-armed rollback and stale-epoch fail-silent. +- Existing full Windows MSVC native CTest + Chromium/standalone JS parity must pass on exact PR head before merge. Physical Maono FAT remains not performed in CI. diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index a80004bf0..27d62c31e 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -7,6 +7,7 @@ #include "VstBusLayout.h" #include "LiveGraphHandoff.h" #include "LiveDryRoutingLab.h" +#include "LiveDynamicBusSession.h" #include "../engine/dsp/NativeMasterLoudness.h" #include "DiagnosticTone.h" #include "../engine/device/JuceIndependentClockDevice.h" @@ -330,6 +331,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Suppress any live output while selecting/changing a device, even if JUCE // starts its new callback before the selector window is closed. void beginManualAudioSetup() noexcept { + liveStudioBus_.invalidate(); // driver/pin change cannot inherit a native GROUP setOutputMuted(true); directFence_.suspend(); dryRoutingLab_.disable(); // explicit control-thread reset; not RT @@ -1028,6 +1030,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const juce::var& command, const LiveDryRoutingLab::FxSelections& fx, const LiveDryRoutingLab::FxRestores* restored=nullptr) { + if(liveStudioBus_.active())return "M3E live Group active: MUTE OUTPUT and STOP GROUP before editing legacy routing/FX"; if (!allOutputsDisarmed()) return "MUTE hardware output and DISARM STREAM before APPLY routing"; if (handoff_.busy()) return "A VST3 graph handoff is in progress"; if (routeReconfiguring_.load(std::memory_order_acquire)) @@ -1054,11 +1057,46 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } void disableDryRoutingLab() noexcept { setOutputMuted(true); // never expose CH1 unexpectedly on STOP + liveStudioBus_.invalidate(); dryRoutingLab_.disable(); } + // Actual single-callback dynamic GROUP operator command. No additional + // device, signal path, VST instance or hidden borrowed input strip. + juce::String applyStudioBusForSelected( + const armix::mixer::LiveDynamicBusSession::Selection& selected) { + if(!allOutputsDisarmed())return "MUTE MAIN and DISARM STREAM first"; + if(!directFence_.permitted()||independent_.active()|| + diagnosticRoute()!=armix::diagnostics::Route::normal|| + savedDirectSetup_||savedLiveSetup_||handoff_.busy()|| + routeReconfiguring_.load(std::memory_order_acquire)) + return "Studio Bus requires stable DIRECT ASIO/WASAPI with no graph transition"; + if(!dryRoutingLab_.hasExplicitRoute()||graphOwned_->count!=0) + return "Studio Bus dry pilot requires ACKed input route and empty legacy CH1 VST rack"; + auto* const device=deviceManager_.getCurrentAudioDevice(); + if(!device||!device->isOpen())return "DIRECT audio device is not open"; + const auto status=dryRoutingLab_.status(device); + return liveStudioBus_.createForSelected( + status.getProperty("acceptedRoute",{}),status,selected, + dryRoutingLab_.epoch(), + device->getActiveInputChannels().countNumberOfSetBits(), + device->getActiveOutputChannels().countNumberOfSetBits(), + juce::jmax(32,device->getCurrentBufferSizeSamples()), + allOutputsDisarmed()); + } + juce::String stopStudioBus() { + if(!allOutputsDisarmed())return "MUTE hardware MAIN and DISARM STREAM before STOP GROUP"; + liveStudioBus_.stop(); + return {}; + } + bool studioBusLive() const noexcept {return liveStudioBus_.active();} + bool setStudioBusGain(std::uint64_t epoch,std::uint64_t revision,float linear) noexcept { + return liveStudioBus_.setGroupGain(epoch,revision,linear); + } + juce::String switchDryRoutingLabSource(int strip,std::uint64_t epoch, std::uint64_t revision,const juce::String& mode, int left,int right) noexcept { + if(liveStudioBus_.active())return "STOP live GROUP first; its source graph is authoritative"; if(independent_.active()||routeReconfiguring_.load(std::memory_order_acquire)|| handoff_.busy()||!directFence_.permitted()|| diagnosticRoute_.load(std::memory_order_acquire) @@ -1070,10 +1108,14 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool setDryRoutingLabParameter(int strip,std::uint64_t epoch, std::uint64_t revision,const juce::String& parameter, float value) noexcept { + // The old 10CH parameter publisher is inactive while a new dynamic + // Group owns PCM; never ACK a fader that does not reach the callback. + if(liveStudioBus_.active())return false; return dryRoutingLab_.setChannelParameter(strip,epoch,revision,parameter,value); } bool setDryRoutingLabAuxBusGain(int bus,std::uint64_t epoch, std::uint64_t revision,float gain) noexcept { + if(liveStudioBus_.active())return false; if(independent_.active()||routeReconfiguring_.load(std::memory_order_acquire)|| diagnosticRoute_.load(std::memory_order_acquire) !=armix::diagnostics::Route::normal|| @@ -1083,6 +1125,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } bool setDryRoutingLabAuxSendGain(int source,int bus,std::uint64_t epoch, std::uint64_t revision,float gain) noexcept { + if(liveStudioBus_.active())return false; if(independent_.active()||routeReconfiguring_.load(std::memory_order_acquire)|| diagnosticRoute_.load(std::memory_order_acquire) !=armix::diagnostics::Route::normal|| @@ -1093,6 +1136,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool setDryRoutingLabFxBypass(int lane,int slot,std::uint64_t epoch, std::uint64_t revision,const juce::String& instanceId, bool bypass) noexcept { + if(liveStudioBus_.active())return false; if(routeReconfiguring_.load(std::memory_order_acquire)|| diagnosticRoute_.load(std::memory_order_acquire) !=armix::diagnostics::Route::normal)return false; @@ -1109,6 +1153,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } juce::String captureRoutedFxStates(std::uint64_t epoch,std::uint64_t revision, std::vector& states) noexcept { + if(liveStudioBus_.active())return "STOP live GROUP before native Show/FX capture"; if(!allOutputsDisarmed()||independent_.active()|| routeReconfiguring_.load(std::memory_order_acquire)|| diagnosticRoute_.load(std::memory_order_acquire) @@ -1124,12 +1169,14 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::var status() { dryRoutingLab_.poll(); // off-RT reclaim after callback quiescence + liveStudioBus_.poll(); auto o = std::make_unique(); const bool dual = independent_.active(); auto* d = dual ? independent_.renderDevice() : deviceManager_.getCurrentAudioDevice(); auto* capture = dual ? independent_.captureDevice() : d; o->setProperty ("dryRoutingLab",dryRoutingLab_.status(capture)); + o->setProperty ("studioBus",liveStudioBus_.status()); // NORMAL mode is never silently served by the legacy CH1 fallback. // This state is for operator feedback; it does not authorize output. o->setProperty ("productionRoutingState", @@ -1449,6 +1496,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback armix::dsp::NativeMasterLoudness masterLoudness_; armix::diagnostics::DiagnosticTone diagnosticTone_; LiveDryRoutingLab dryRoutingLab_; + armix::mixer::LiveDynamicBusSession liveStudioBus_; // same JUCE callback, dry-only pilot + std::uint64_t studioBusAudioGeneration_=0; // AUDIO only + int studioBusFadeRemaining_=0; // AUDIO only std::atomic diagnosticRoute_ {armix::diagnostics::Route::normal}; std::atomic routeReconfiguring_ {false}; std::optional savedLiveSetup_; @@ -1536,6 +1586,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void audioDeviceAboutToStart (juce::AudioIODevice* d) override { secondaryOutput_.invalidateSource(); // source clock may have changed + liveStudioBus_.invalidate(); // no old BUS survives a new hardware pin mask dryRoutingLab_.prepareDevice(d); // exact active mask, before callback if (!independent_.active()) { @@ -1587,6 +1638,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void audioDeviceStopped() override { secondaryOutput_.invalidateSource(); // explicit reconnect required after device stop + liveStudioBus_.invalidate(); masterLoudness_.prepare (0.0); // clear validity across device epoch dryRoutingLab_.deviceStopped(); deviceStopCount_.fetch_add (1, std::memory_order_relaxed); @@ -1770,12 +1822,67 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback LegacyChannelOneLease ch1Lease{this,cycle.graph}; std::array nativeMainPair{{-1,-1}}; std::array nativeMonitorPair{{-1,-1}}; - const bool routed=dryRoutingLab_.process(inputs,inputChannels,outputs, + // M3E: one native callback, ONE selected producer. The dynamic + // ChannelId graph replaces (never sums with) the old dry graph + // only following an exact ACK of a 0FX GROUP+MAIN session. + const bool studioBus=liveStudioBus_.active(); + float studioPeakL=0.f,studioPeakR=0.f; + bool routed=false; + if(studioBus) { + const auto pair=liveStudioBus_.mainPair(); + const bool valid=liveStudioBus_.activeFor( + dryRoutingLab_.epoch(),inputChannels,outputChannels) && + outputs&&pair[0]>=0&&pair[1]>=0&& + pair[0]0) { + const float fade=1.f-static_cast( + studioBusFadeRemaining_-1)/256.f; + l*=fade;r*=fade; + --studioBusFadeRemaining_; + } + outputs[pair[0]][i]=l; + outputs[pair[1]][i]=r; + studioPeakL=juce::jmax(studioPeakL,std::abs(l)); + studioPeakR=juce::jmax(studioPeakR,std::abs(r)); + } + } + } + if(!routed)studioBusFadeRemaining_=256; + // Only AFTER the dynamically prepared graph has consumed all + // input PCM may unused hardware outputs be cleared (ASIO + // input/output buffer aliasing is supported). + for(int c=0;c +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// M3E live, strictly dry and 0-FX pilot. ONE JUCE callback renders either +// legacy 10CH or this dynamic graph, NEVER both. A Group consumes a genuinely +// new ChannelId, not an unused input strip. The control plane may accept a +// candidate only while all physical and secondary outputs are disarmed. +// Explicitly refuse complex legacy AUX/FX/monitor/Show routes rather than +// converting them incompletely and losing audio behind the operator's back. +namespace armix::mixer { +class LiveDynamicBusSession final { +public: + static constexpr int maxPhysicalPins=256; + LiveDynamicBusSession()=default; + LiveDynamicBusSession(const LiveDynamicBusSession&)=delete; + LiveDynamicBusSession& operator=(const LiveDynamicBusSession&)=delete; + + struct Selection final { + std::array channels{}; + int count=0; + }; + + juce::String createForSelected(const juce::var& accepted, + const juce::var& status, + const Selection& selection, + std::uint64_t deviceEpoch, + int actualInputs,int actualOutputs, + int frames,bool disarmed) { + if(!disarmed)return "MUTE MAIN and DISARM secondary output before creating a Bus"; + if(active_.load(std::memory_order_acquire)) + return "Stop the current live Group before modifying the pilot Bus route"; + if(deviceEpoch==0||actualInputs<1||actualInputs>maxPhysicalPins || + actualOutputs<2||actualOutputs>maxPhysicalPins || + frames<32||frames>8192) + return "Native device mask/quantum is unavailable for Dynamic Bus"; + if(selection.count<1||selection.count>10) + return "Select one or more active INPUT channels for GROUP Bus"; + if(!accepted.isObject()||!status.isObject()) + return "First APPLY an actual native 10CH physical INPUT route"; + const auto routeRows=accepted.getProperty("channels",{}); + const auto* rows=routeRows.getArray(); + if(!rows||rows->size()!=10) + return "Selected Show is not an accepted 10CH physical source route"; + // This deliberately isolates zero-FX GROUP latency/PCM proof; FX and + // Aux migration must reuse M4 owner rather than duplicate VST objects. + if(static_cast(status.getProperty("fxCount",0))!=0 || + static_cast(status.getProperty("auxCount",0))!=0 || + static_cast(status.getProperty("sendCount",0))!=0 || + static_cast(status.getProperty("auxSendCount",0))!=0) + return "M3E dry Bus pilot requires 0 VST3, AUX and prior Sends; preserve existing route"; + // juce::var owns each Array; never retain getArray() from a + // temporary property value (would dangle before native preparation). + const auto controlsValue=status.getProperty("channelControls",{}); + const auto* effective=controlsValue.getArray(); + if(!effective||effective->size()!=10) + return "Native effective channel controls unavailable; refuse to reset live faders"; + const auto monitorsValue=status.getProperty("monitorOutputs",{}); + const auto portsValue=status.getProperty("ports",{}); + const auto outputsValue=status.getProperty("outputPorts",{}); + const auto mainValue=status.getProperty("mainOutputs",{}); + const auto* mons=monitorsValue.getArray(); + if(mons&&!mons->isEmpty()) + return "M3E dry Bus pilot needs MONITOR disabled; preserve existing monitor patch"; + const auto* ports=portsValue.getArray(); + const auto* outs=outputsValue.getArray(); + const auto* main=mainValue.getArray(); + if(!ports||!outs||!main||main->size()!=2|| + ports->size()!=actualInputs||outs->size()!=actualOutputs) + return "Native INPUT/MAIN readback changed; retry after DEVICE/APPLY ACK"; + auto findInput=[&](int port)->int { + for(const auto& p:*ports) + if(static_cast(p.getProperty("port",-1))==port) + return static_cast(p.getProperty("callback",-1)); + return -1; + }; + auto findOutput=[&](int physical)->int { + for(int k=0;ksize();++k) + if(static_cast((*outs)[k])==physical)return k; + return -1; + }; + const int left=findOutput(static_cast((*main)[0])); + const int right=findOutput(static_cast((*main)[1])); + if(left<0||right<0||left==right)return "MAIN output pins are not active in this driver"; + std::array isSelected{}; + for(int k=0;k=10||isSelected[static_cast(idx)]) + return "Invalid or duplicated channel selection"; + isSelected[static_cast(idx)]=true; + } + DynamicChannelRoster roster; + std::vector add; + add.reserve(11); + for(int i=0;i<11;++i){ + ChannelEdit row;row.kind=ChannelEdit::Kind::add;row.position=i; + row.role=i==10?ChannelRole::main:ChannelRole::input; + const auto mode=i==10?juce::String("STEREO"): + (*rows)[i].getProperty("mode",{}).toString(); + const auto format=i==10?juce::String("STEREO"): + (*rows)[i].getProperty("channelFormat",mode).toString(); + row.format=format=="STEREO"?ProcessingFormat::stereo:ProcessingFormat::mono; + row.text=i==10?"MAIN":"CH "+std::to_string(i+1); + if(i!=10 && mode!="NONE"&&mode!="MONO"&&mode!="STEREO") + return "Legacy BUS/unsupported source needs full Show migration; route unchanged"; + if(i<10 && isSelected[static_cast(i)]&&mode=="NONE") + return "Selected channel has no native physical source; route unchanged"; + add.push_back(std::move(row)); + } + const auto first=roster.edit(0,add); + if(!first.ok()||first.createdIds.size()!=11) + return "Native dynamic ChannelId allocation rejected"; + std::vector links; + links.reserve(55); + DynamicGraphRequest req; + req.physicalInputs=actualInputs; + req.maxFrames=frames; + req.maxScratchBytes=64u*1024u*1024u; + for(int i=0;i<10;++i){ + const auto& row=(*rows)[i]; + const auto mode=row.getProperty("mode",{}).toString(); + const auto& state=(*effective)[i]; + const double linear=static_cast(state.getProperty("linear",-1.0)); + const double pan=static_cast(state.getProperty("pan",999.0))/100.0; + if(!std::isfinite(linear)||linear<0.0||linear>4.0|| + !std::isfinite(pan)||pan< -1.0||pan>1.0) + return "Native live source fader/PAN readback invalid; route unchanged"; + ChannelEdit gainEdit;gainEdit.kind=ChannelEdit::Kind::setFader; + gainEdit.id=first.createdIds[i];gainEdit.value=static_cast(linear); + links.push_back(std::move(gainEdit)); + ChannelEdit panEdit;panEdit.kind=ChannelEdit::Kind::setPan; + panEdit.id=first.createdIds[i];panEdit.value=static_cast(pan); + links.push_back(std::move(panEdit)); + if(static_cast(state.getProperty("mute",false))) { + ChannelEdit mute;mute.kind=ChannelEdit::Kind::setMute; + mute.id=first.createdIds[i];mute.enabled=true; + links.push_back(std::move(mute)); + } + if(static_cast(state.getProperty("solo",false))) { + ChannelEdit solo;solo.kind=ChannelEdit::Kind::setSolo; + solo.id=first.createdIds[i];solo.enabled=true; + links.push_back(std::move(solo)); + } + if(mode=="NONE")continue; + const int inL=findInput(static_cast(row.getProperty("left",-1))); + const int inR=mode=="STEREO"? + findInput(static_cast(row.getProperty("right",-1))):-1; + if(inL<0||inL>=actualInputs || + (mode=="STEREO"&&(inR<0||inR>=actualInputs||inL==inR))) + return "Physical capture port absent from current driver readback"; + req.sources.push_back({first.createdIds[i],inL,inR,mode=="STEREO"}); + // OUT NONE is a real operator route, not implicitly MAIN. + // Selected channels are redirected to GROUP by the following + // atomic createBusForSelected even if their old OUT was NONE. + if(static_cast(row.getProperty("main",true))) { + ChannelEdit link; + link.kind=ChannelEdit::Kind::setPrimaryOutput; + link.id=first.createdIds[i];link.target=first.createdIds[10]; + links.push_back(std::move(link)); + } + } + const auto wired=roster.edit(roster.revision(),links); + if(!wired.ok())return "Unable to create source to MAIN routing"; + std::vector selected; + selected.reserve(selection.count); + for(int k=0;k(result.fault))+")"; + roster_=std::move(roster); + group_=bus.createdIds.front(); + main_=first.createdIds[10]; + groupGain_.store(1.f,std::memory_order_relaxed); + actualMainL_.store(left,std::memory_order_relaxed); + actualMainR_.store(right,std::memory_order_relaxed); + inputCount_.store(actualInputs,std::memory_order_relaxed); + epoch_.store(deviceEpoch,std::memory_order_release); + generation_.fetch_add(1,std::memory_order_release); + active_.store(true,std::memory_order_release); + return {}; + } + + // Safe device lifecycle invalidation; never publish stale routing after + // ASIO port masks or callback generations change. No allocation here. + void invalidate() noexcept { + active_.store(false,std::memory_order_release); + generation_.fetch_add(1,std::memory_order_release); + } + void stop() noexcept { + invalidate(); + generation_.fetch_add(1,std::memory_order_release); + // Keep publisher alive across device stop. Old prepared snapshots are + // retired only after native callback lease release on control poll. + publisher_.unpublish(); + } + // A real GROUP fader: one native ChannelId atomic target, smoothed on + // the audio thread. No structural APPLY, VST rebuild or device STOP. + bool setGroupGain(std::uint64_t epoch,std::uint64_t revision, + float linear) noexcept { + if(!active()||epoch!=epoch_.load(std::memory_order_acquire)|| + !std::isfinite(linear)||linear<0.f||linear>4.f) + return false; + if(!publisher_.setChannelMix(epoch,revision,group_,linear,0.f)) + return false; + (void)roster_.rememberLiveMix(group_,linear,0.f); + groupGain_.store(linear,std::memory_order_release); + return true; + } + void poll() noexcept {publisher_.pollRetirement();} + bool active() const noexcept {return active_.load(std::memory_order_acquire);} + bool activeFor(std::uint64_t epoch,int inputs,int outputs) const noexcept { + return active()&&epoch==epoch_.load(std::memory_order_acquire)&& + inputs==inputCount_.load(std::memory_order_relaxed)&& + actualMainL_.load(std::memory_order_relaxed)>=0&& + actualMainR_.load(std::memory_order_relaxed) mainPair() const noexcept { + return {actualMainL_.load(std::memory_order_relaxed), + actualMainR_.load(std::memory_order_relaxed)}; + } + std::uint64_t generation() const noexcept { + return generation_.load(std::memory_order_acquire); + } + std::uint64_t acceptedRevision() const noexcept {return publisher_.acceptedRevision();} + juce::var status() const { + auto out=std::make_unique(); + out->setProperty("active",active()); + out->setProperty("epoch",static_cast(epoch_.load())); + out->setProperty("revision",static_cast(publisher_.acceptedRevision())); + out->setProperty("groupChannelId",static_cast(group_.value)); + out->setProperty("mainChannelId",static_cast(main_.value)); + const float fader=groupGain_.load(std::memory_order_acquire); + out->setProperty("gainDb",fader>0.f?20.0*std::log10(fader):-60.0); + if(active()) { + const auto* accepted=publisher_.acceptedRouting(epoch_.load(), + publisher_.acceptedRevision()); + if(accepted) { + if(const auto* bus=accepted->find(group_)) { + out->setProperty("name",juce::String(bus->name)); + out->setProperty("sourceCount",static_cast(bus->sourceCount())); + juce::Array names; + for(const auto id:bus->primarySources) + if(const auto* row=roster_.find(id)) + names.add(juce::String(row->name)); + out->setProperty("sources",juce::var(names)); + } + } + } + out->setProperty("mode","NATIVE_SINGLE_CALLBACK_DRY_GROUP_PILOT"); + return juce::var(out.release()); + } + bool render(std::uint64_t epoch,const float* const* inputs,int inputCount, + float* mainL,float* mainR,int frames,bool muted) noexcept { + const auto noFx=[](ChannelId,float*,float*,int) noexcept {}; + return publisher_.render(epoch,inputs,inputCount,mainL,mainR,frames, + muted,noFx); + } +private: + DynamicChannelRoster roster_{}; + DynamicNativeSessionPublisher publisher_{}; + ChannelId group_{},main_{}; + std::atomic active_{false}; + std::atomic epoch_{0},generation_{0}; + std::atomic inputCount_{-1},actualMainL_{-1},actualMainR_{-1}; + std::atomic groupGain_{1.f}; +}; +} // namespace armix::mixer diff --git a/src/Main.cpp b/src/Main.cpp index c4258b25e..5fa2c986c 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -75,6 +75,10 @@ std::optional assetFor (const juce::String& { data = BinaryData::mixerlayout_js; size = BinaryData::mixerlayout_jsSize; mime = "text/javascript"; } else if (path == "/mixer-layout.css") { data = BinaryData::mixerlayout_css; size = BinaryData::mixerlayout_cssSize; mime = "text/css"; } + else if (path == "/studio-bus.js") + { data = BinaryData::studiobus_js; size = BinaryData::studiobus_jsSize; mime = "text/javascript"; } + else if (path == "/studio-bus.css") + { data = BinaryData::studiobus_css; size = BinaryData::studiobus_cssSize; mime = "text/css"; } else return std::nullopt; juce::WebBrowserComponent::Resource resource; @@ -1327,6 +1331,73 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // M1 RT source switch on an existing physical channel. Unlike // structural routingDryApply, it does not unpatch outputs, rebuild // VST3s, or restart the device; input PCM fades inside one graph. + // M3E genuinely live Dynamic Group. Native command is the ONLY + // structural authority. IDs are assigned by C++, never by the web + // Console; ACK contains revision-scoped native source fan-in. + if(action=="studioBusGain") { + const int requestId=static_cast(args.getProperty("requestId",0)); + const auto ep=args.getProperty("epoch",{}); + const auto rv=args.getProperty("revision",{}); + const auto db=args.getProperty("db",{}); + const bool validNumber=db.isDouble()||db.isInt(); + const double fader=validNumber?static_cast(db):-999.0; + const bool valid=requestId>0&&!ep.isVoid()&&!rv.isVoid()&& + std::isfinite(fader)&&fader>=-60.0&&fader<=10.0; + const float gain=valid?(fader<=-60.0?0.f: + std::pow(10.f,static_cast(fader)/20.f)):0.f; + const bool ok=valid&&engine_.setStudioBusGain( + static_cast(static_cast(ep)), + static_cast(static_cast(rv)),gain); + auto ack=std::make_unique(); + ack->setProperty("requestId",requestId); + ack->setProperty("ok",ok); + ack->setProperty("error",ok?juce::String(): + juce::String("Stale GROUP epoch/revision or invalid fader")); + ack->setProperty("session",engine_.status().getProperty("studioBus",{})); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixStudioBusGainAck",juce::var(ack.release())); + return; + } + if(action=="studioBusCreateForSelected" || action=="studioBusStop") { + const int requestId=static_cast(args.getProperty("requestId",0)); + juce::String error; + armix::mixer::LiveDynamicBusSession::Selection selection; + const auto expectedEpoch=args.getProperty("expectedEpoch",{}); + const auto expectedRevision=args.getProperty("expectedRevision",{}); + if(requestId<=0||nativeShowBusy_||studioBackupBusy_|| + expectedEpoch.isVoid()||expectedRevision.isVoid()|| + static_cast(expectedEpoch)!= + static_cast(engine_.dryRoutingLabEpoch())|| + static_cast(expectedRevision)!= + static_cast(engine_.dryRoutingLabRevision())) + error="Stale native device/route or Show/backup in progress"; + else if(action=="studioBusCreateForSelected") { + const auto values=args.getProperty("channels",{}); + const auto* indices=values.getArray(); + if(!indices||indices->isEmpty()||indices->size()>10) + error="Select 1–10 physical-input channels"; + else { + selection.count=indices->size(); + for(int i=0;i((*indices)[i]); + } + if(error.isEmpty())error=engine_.applyStudioBusForSelected(selection); + } + } else error=engine_.stopStudioBus(); + auto ack=std::make_unique(); + ack->setProperty("requestId",requestId); + ack->setProperty("ok",error.isEmpty()); + ack->setProperty("error",error); + ack->setProperty("session",engine_.status().getProperty("studioBus",{})); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixStudioBusAck",juce::var(ack.release())); + if(error.isNotEmpty())emitNotice(error,true); + return; + } if(action=="routingSourceSwitch"){ const int requestId=static_cast(args.getProperty("requestId",0)); const int channel=static_cast(args.getProperty("channel",-1)); diff --git a/tests/live_routing_ui_contract_test.mjs b/tests/live_routing_ui_contract_test.mjs index 86578f723..241d3ca2a 100644 --- a/tests/live_routing_ui_contract_test.mjs +++ b/tests/live_routing_ui_contract_test.mjs @@ -52,11 +52,17 @@ test("STOP-race is fail closed: all outputs are written to silence without CH1 f const end=engine.indexOf("const bool enabled = monitor_",enter); assert.ok(enter>=0&&end>enter, "live audio callback LAB branch must exist"); const branch=engine.slice(enter,end); - assert.match(branch,/const bool routed=dryRoutingLab_\.process\(/); + // The new M3E GROUP is an EXCLUSIVE producer inside this SAME callback. + // STOP-race must still silence all physical outputs, with no legacy CH1 + // fallback and never summing dynamic + legacy PCM. + assert.match(branch,/bool routed=false/); + assert.match(branch,/if\(studioBus\)\s*\{/); + assert.match(branch,/routed=liveStudioBus_\.render\(/); + assert.match(branch,/\}else\s*\{\s*routed=dryRoutingLab_\.process\(/); assert.match(branch,/if\(!routed\)\s*\{\s*for\(int c=0;c{ const start=lab.indexOf("if(snapshot->graphRevision!=audioRevision_"); diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index 3a17a3611..e3b1078dd 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -521,3 +521,48 @@ test('P0 First Sound separates RAW capture, post-fader PCM and physical output A assert.match(css,/\.arIOAudioPath>\.arIOPathStart/); assert.doesNotMatch(gui,/new AudioContext|AudioWorklet|processBlock|createPluginInstance/); }); + +test('M3E live independent GROUP uses exactly one JUCE producer and native ACKed gain, not borrowed CH10',()=>{ + const engine=read('src/LiveAudioEngine.h'); + const session=read('src/LiveDynamicBusSession.h'); + const js=read('web/studio-bus.js'); + const css=read('web/studio-bus.css'); + const standalone=read('AR-MIX-Live-FX-Host-Standalone-v0.3.html'); + const cm=read('CMakeLists.txt'); + const index=read('web/index.html'); + assert.match(engine,/liveStudioBus_\.createForSelected\(/); + assert.match(engine,/const bool studioBus=liveStudioBus_\.active\(\)/); + assert.match(engine,/routed=liveStudioBus_\.render\(/); + assert.match(engine,/\}else \{\s*routed=dryRoutingLab_\.process\(/); + assert.match(engine,/liveStudioBus_\.invalidate\(\)/); + assert.match(engine,/if\(liveStudioBus_\.active\(\)\)return "M3E live Group active/); + assert.match(engine,/if\(liveStudioBus_\.active\(\)\)return false/); + assert.match(session,/createBusForSelected\(/); + assert.match(session,/ChannelRole::group/); + assert.match(session,/publisher_\.commit\(roster,req/); + assert.match(session,/publisher_\.render\(epoch,inputs,inputCount/); + assert.match(session,/publisher_\.setChannelMix\(epoch,revision,group_,linear,0\.f\)/); + assert.match(session,/\bactualMainL_\.store\(left/); + assert.match(session,/\bactualMainR_\.store\(right/); + assert.match(session,/MONITOR disabled/); + assert.match(session,/0 VST3, AUX and prior Sends/); + assert.match(session,/out->setProperty\("sourceCount"/); + assert.match(main,/action=="studioBusCreateForSelected"/); + assert.match(main,/action=="studioBusGain"/); + assert.match(main,/arMixStudioBusAck/); + assert.match(main,/arMixStudioBusGainAck/); + assert.match(js,/Ctrl\/Shift\+click channel names to select/); + assert.match(js,/arMixStudioBusAck/); + assert.match(js,/arMixStudioBusGainAck/); + assert.match(js,/GROUP LIVE · native prepared PCM ACK/); + assert.doesNotMatch(js,/new AudioContext\(|AudioWorklet|\.createOscillator\(/); + assert.match(index,/studio-bus\.js/); + assert.match(index,/studio-bus\.css/); + assert.match(cm,/web\/studio-bus\.js web\/studio-bus\.css/); + assert.match(cm,/src\/LiveDynamicBusSession\.h/); + const inline=(tag,close)=>standalone.slice( + standalone.indexOf(tag)+tag.length, + standalone.indexOf(close,standalone.indexOf(tag)+tag.length)); + assert.equal(inline(''),js); + assert.equal(inline(''),css); +}); diff --git a/tests/mixer_routing_plan_test.cpp b/tests/mixer_routing_plan_test.cpp index 19517fb1c..a8a23c632 100644 --- a/tests/mixer_routing_plan_test.cpp +++ b/tests/mixer_routing_plan_test.cpp @@ -964,7 +964,76 @@ static void verifyDynamicInPlacePhysicalIOBuffers() { assert(host.acceptedRevision()==1); } +// M3E physical-operator cutover fixture: all TEN native input identities +// exist before a new independent GROUP is created. The two selected source +// lanes are NOT duplicated at MAIN after the exclusive OUT rewrite, and +// the Group fader changes REAL PCM without recompiling/restarting a device. +static void verifyM3ELiveIndependentBusProductionPcm() { + DynamicChannelRoster source; + std::array additions{}; + for(int i=0;i<11;++i) { + auto& op=additions[static_cast(i)]; + op.kind=ChannelEdit::Kind::add; + op.position=static_cast(i); + op.role=i==10?ChannelRole::main:ChannelRole::input; + op.format=i==10?ProcessingFormat::stereo:ProcessingFormat::mono; + op.text=i==10?"MAIN":"CH "+std::to_string(i+1); + } + auto r=source.edit(0,additions); + assert(r.ok() && r.createdIds.size()==11); + const auto mainId=r.createdIds[10]; + std::array links{}; + for(int i=0;i<2;++i){ + links[i].kind=ChannelEdit::Kind::setPrimaryOutput; + links[i].id=r.createdIds[i];links[i].target=mainId; + } + assert(source.edit(1,links).ok()); + DynamicGraphRequest req; + req.physicalInputs=2;req.maxFrames=64; + req.sources={{r.createdIds[0],0,-1,false}, + {r.createdIds[1],1,-1,false}}; + DynamicNativeSessionPublisher live; + constexpr std::uint64_t epoch=491; + assert(live.commit(source,req,0,epoch,epoch,true).ok()); + auto staged=source; + const std::array selected{r.createdIds[0],r.createdIds[1]}; + const auto group=staged.createBusForSelected( + staged.revision(),selected,"VOCAL GROUP",ChannelRole::group); + assert(group.ok()&&group.createdIds.size()==1); + assert(group.createdIds[0].value==12&&staged.size()==12); + const auto out=staged.find(group.createdIds[0]); + assert(out&&out->role==ChannelRole::group); + assert(live.commit(staged,req,1,epoch,epoch,true).ok()); + const auto* view=live.acceptedRouting(epoch,2); + assert(view&&view->find(group.createdIds[0])->sourceCount()==2); + assert(view->find(selected[0])->primaryOutput==group.createdIds[0]); + assert(view->find(selected[1])->primaryOutput==group.createdIds[0]); + assert(view->find(group.createdIds[0])->primaryOutput==mainId); + std::array mic1{},mic2{},outL{},outR{}; + mic1.fill(.2f);mic2.fill(.3f); + const float* inputs[]={mic1.data(),mic2.data()}; + const auto noFx=[](ChannelId,float*,float*,int) noexcept {}; + constexpr float center=.7071067811865475f; + assert(live.render(epoch,inputs,2,outL.data(),outR.data(), + 64,false,noFx)); + assert(close(outL[63],(.2f+.3f)*center)); + assert(close(outR[63],(.2f+.3f)*center)); + assert(live.setChannelMix(epoch,2,group.createdIds[0],.5f,0.f)); + assert(live.render(epoch,inputs,2,outL.data(),outR.data(), + 64,false,noFx)); + assert(close(outL[63],(.2f+.3f)*center*.5f)); + assert(close(outR[63],(.2f+.3f)*center*.5f)); + assert(live.acceptedRevision()==2); + auto failure=live.commit(staged,req,2,epoch,epoch,false); + assert(failure.fault==DynamicNativeSessionPublisher::Fault::outputArmed); + assert(live.acceptedRevision()==2); + assert(!live.render(epoch+1,inputs,2,outL.data(),outR.data(), + 64,false,noFx)); + assert(outL[63]==0.f&&outR[63]==0.f); +} + int main() { + verifyM3ELiveIndependentBusProductionPcm(); verifyDynamicInPlacePhysicalIOBuffers(); verifyDynamicChannelIdLiveControls(); verifyDynamicNativeSessionPublication(); diff --git a/tests/ui_smoke.py b/tests/ui_smoke.py index 70e1f419b..7b68bd244 100644 --- a/tests/ui_smoke.py +++ b/tests/ui_smoke.py @@ -465,7 +465,10 @@ async def passive_hover_is_inert(selector): # L2 workspace: original 17 rail controls plus one purposeful MS5 SEND FADERS toggle. # Its optional AUX selector is not a button; preserve the original operator commands. assert await page.locator('.toolbar-actions .nav button.btn-180').count()==3 - assert await page.locator('.left-rail button.btn-180').count()==18 + # The additional live GROUP button belongs to M3E. Keep the original + # 18 rail commands stable; verify the new real Bus action separately. + assert await page.locator('.left-rail button.btn-180:not(.arStudioBusAction)').count()==18 + assert await page.locator('.left-rail button.arStudioBusAction').count()==1 assert await page.locator('.left-rail [data-sof-toggle]').count()==1 assert await page.locator('.toolbar-actions .fx-nav,.left-rail .fx-nav').count()==0 assert await page.locator('.left-rail .pushable,.left-rail .front,.left-rail .edge,.left-rail .shadow').count()==0 diff --git a/web/index.html b/web/index.html index 4b3852300..8d3a3184a 100644 --- a/web/index.html +++ b/web/index.html @@ -1,5 +1,5 @@ -ArSonMix — Live FX Host GUI Preview +ArSonMix — Live FX Host GUI Preview
@@ -47,5 +47,5 @@
UI PREVIEW · Native audio engine is not connectedFader · PAN · VST3 FXPREVIEWArSonMix · Live VST3 Host
- + diff --git a/web/studio-bus.css b/web/studio-bus.css new file mode 100644 index 000000000..db3d29ae8 --- /dev/null +++ b/web/studio-bus.css @@ -0,0 +1,14 @@ +/* M3E: compact native Group pilot; no blur, filter, box-shadow or heavy card. */ +.arStudioBusControls{box-sizing:border-box;display:grid;gap:5px;padding:8px 8px 7px;margin:4px 3px 5px;border-top:1px solid #3a5766;border-bottom:1px solid #334a55;background:#182932;min-width:0} +.arStudioBusTitle{color:#83c2d3;font:600 10px/1.2 "ArSonMix Inter","Segoe UI",sans-serif;letter-spacing:.35px} +.arStudioBusSelection{font:10px/1.35 "ArSonMix Inter","Segoe UI",sans-serif;color:#bfd1da;overflow-wrap:anywhere} +.arStudioBusControls .arStudioBusAction{height:29px;min-height:29px;font:600 10px "ArSonMix Inter","Segoe UI",sans-serif;white-space:normal} +.arStudioBusControls .arStudioBusAction:disabled{opacity:.48;cursor:not-allowed} +.arStudioBusFeedback,.arStudioBusLive{font:9px/1.4 "ArSonMix Inter","Segoe UI",sans-serif;color:#b4cad4;overflow-wrap:anywhere} +.arStudioBusLive{color:#91dfc8} +#channelList [data-choose].arBusSelected{outline:1px solid #70b6c3;outline-offset:-1px;background:#24414c} +.strip[data-strip].arBusSelected .strip-name{outline:1px solid #78b7c5;outline-offset:-1px} +.arStudioBusFader{display:grid;gap:3px;font:9px/1.3 "ArSonMix Inter","Segoe UI",sans-serif;color:#a6cad5;min-width:0} +.arStudioBusFader[hidden]{display:none!important} +.arStudioBusFader input{width:100%;min-width:0;accent-color:#50bcc7;cursor:ew-resize} +.arStudioBusFader small{color:#b4dfd9;font:10px/1.2 "ArSonMix Inter","Segoe UI",sans-serif;text-align:right} diff --git a/web/studio-bus.js b/web/studio-bus.js new file mode 100644 index 000000000..b88392194 --- /dev/null +++ b/web/studio-bus.js @@ -0,0 +1,163 @@ +// Studio Console M3E: real native ACK-backed independent GROUP pilot. +// This control projection NEVER guesses PCM or invents a CH11 in the browser. +// One existing JUCE callback owns the accepted dynamic ChannelId engine. +(() => { + 'use strict'; + const rail=document.querySelector('#app .left-rail'); + const anchor=document.getElementById('channelList'); + if(!rail||!anchor||document.getElementById('arStudioBusControls'))return; + const native=!!window.__JUCE__?.backend?.emitEvent; + const backend=window.__JUCE__?.backend; + const selected=new Set(); + let last=-1,request=0,serial=0,pending=false,status=null,lastEpoch=''; + const panel=document.createElement('section'); + panel.id='arStudioBusControls'; + panel.className='arStudioBusControls'; + panel.setAttribute('aria-label','Studio native Group Bus'); + const title=document.createElement('div'); + title.className='arStudioBusTitle'; + title.textContent='GROUP BUS'; + const picked=document.createElement('small'); + picked.className='arStudioBusSelection'; + const action=document.createElement('button'); + action.type='button';action.className='btn-180 arStudioBusAction'; + const feedback=document.createElement('div'); + feedback.className='arStudioBusFeedback'; + feedback.setAttribute('role','status'); + const live=document.createElement('div'); + live.className='arStudioBusLive'; + const groupFader=document.createElement('label'); + groupFader.className='arStudioBusFader'; + groupFader.textContent='GROUP FADER'; + const gain=document.createElement('input'); + gain.type='range';gain.min='-60';gain.max='10';gain.step='0.5'; + gain.value='0';gain.setAttribute('aria-label','Native Group Bus fader dB'); + const gainRead=document.createElement('small'); + gainRead.textContent='0.0 dB'; + groupFader.append(gain,gainRead); + panel.append(title,picked,action,feedback,live,groupFader); + anchor.after(panel); + const route=()=>status?.dryRoutingLab||{}; + const accepted=()=>status?.studioBus||{}; + const validSelection=i=>Number.isInteger(i)&&i>=0&&i<10&& + ['MONO','STEREO'].includes( + String(route().acceptedRoute?.channels?.[i]?.mode||'')); + const selectedList=()=>[...selected].filter(validSelection).sort((a,b)=>a-b); + function repaintSelection(){ + anchor.querySelectorAll('[data-choose]').forEach(row=>{ + const i=Number(row.dataset.choose); + const on=selected.has(i); + row.classList.toggle('arBusSelected',on); + row.setAttribute('aria-checked',String(on)); + }); + document.querySelectorAll('.strip[data-strip]').forEach(strip=>{ + strip.classList.toggle('arBusSelected',selected.has(Number(strip.dataset.strip))); + }); + } + function render(){ + const d=route(),b=accepted(),ids=selectedList(); + const liveNow=!!b.active; + picked.textContent=liveNow? + 'NATIVE BUS #'+String(b.groupChannelId||'?')+' · '+String(b.sourceCount||0)+' INPUTS': + ids.length?ids.map(i=>'CH'+String(i+1).padStart(2,'0')).join(' + '): + 'Ctrl/Shift+click channel names to select'; + action.textContent=pending?'APPLYING…':liveNow?'STOP GROUP':'+ BUS FOR SELECTED'; + const canApply=native&&!pending&&!!d.ready&&!!d.hasAcceptedRoute&& + !d.pending&&!status?.monitor&&!status?.secondaryOutputArmed&& + (liveNow||ids.length>0); + action.disabled=!canApply; + action.title=liveNow?'MUTE output and return to legacy 10CH route': + '0FX native Group pilot · MUTE output first · Add new Bus ChannelId and route selected inputs exclusively'; + live.hidden=!liveNow; + groupFader.hidden=!liveNow; + gain.disabled=!liveNow||!native; + if(liveNow){ + live.textContent=String(b.name||'GROUP')+' · '+(b.sources||[]).join(', ')+ + ' → MAIN · NATIVE PCM'; + if(document.activeElement!==gain && Number.isFinite(Number(b.gainDb))) + gain.value=String(Number(b.gainDb)); + gainRead.textContent=Number(gain.value)<=-60?'−∞ dB': + Number(gain.value).toFixed(1)+' dB'; + } + if(!native)feedback.textContent='Web preview only · no hardware audio'; + else if(!feedback.textContent)feedback.textContent= + '0FX pilot · verify native capture, MUTE output, then create Group'; + repaintSelection(); + } + // Extend normal single-focus behavior without replacing app.js and without + // launching an extra routing controller. Ctrl and Shift work like a Console. + document.addEventListener('click',e=>{ + if(!e.ctrlKey&&!e.metaKey&&!e.shiftKey)return; + const el=e.target.closest?.('#channelList [data-choose],.strip [data-editstrip]'); + if(!el)return; + const row=el.closest('[data-choose]'); + const i=Number(row?row.dataset.choose:el.dataset.editstrip); + if(!validSelection(i))return; + if(e.shiftKey&&last>=0){ + const lo=Math.min(last,i),hi=Math.max(last,i); + for(let x=lo;x<=hi;++x)if(validSelection(x))selected.add(x); + }else if(selected.has(i))selected.delete(i); + else selected.add(i); + last=i; + render(); + },true); + let lastGainSent=0; + const sendGain=force=>{ + const b=accepted(),now=performance.now(); + if(!native||!b.active||!Number.isFinite(Number(gain.value)))return; + gainRead.textContent=Number(gain.value)<=-60?'−∞ dB': + Number(gain.value).toFixed(1)+' dB'; + if(!force&&now-lastGainSent<40)return; // bound UI→native control traffic + lastGainSent=now; + backend.emitEvent('arMixAction',{ + action:'studioBusGain',requestId:++serial, + epoch:Number(b.epoch)||0,revision:Number(b.revision)||0, + db:Number(gain.value) + }); + }; + gain.addEventListener('input',()=>sendGain(false)); + gain.addEventListener('change',()=>sendGain(true)); + backend?.addEventListener?.('arMixStudioBusGainAck',ack=>{ + if(ack?.ok!==true)feedback.textContent= + 'GROUP FADER REJECTED · '+String(ack?.error||'Stale graph'); + }); + action.addEventListener('click',()=>{ + if(!native||pending)return; + const d=route(),b=accepted(),stop=!!b.active; + const indices=selectedList(); + if(!stop&&!indices.length)return; + // A user action, never 12Hz telemetry, is allowed to submit one event. + request=++serial; + pending=true; + feedback.textContent=stop?'STOPPING · waiting for native ACK': + 'CREATING · waiting for native graph ACK'; + render(); + backend.emitEvent('arMixAction',{ + action:stop?'studioBusStop':'studioBusCreateForSelected', + requestId:request, + expectedEpoch:Number(d.epoch)||0, + expectedRevision:Number(d.revision)||0, + channels:indices + }); + }); + backend?.addEventListener?.('arMixStudioBusAck',ack=>{ + if(!pending||ack?.requestId!==request)return; + pending=false;request=0; + feedback.textContent=ack?.ok? + (ack.session?.active?'GROUP LIVE · native prepared PCM ACK':'GROUP STOPPED · native ACK'): + 'REJECTED · '+String(ack?.error||'Live graph unchanged'); + if(ack?.ok && status)status.studioBus=ack.session; + render(); + }); + backend?.addEventListener?.('arMixStatus',s=>{ + status=s; + const d=route(),key=String(d.epoch||0); + if(lastEpoch!==key){ + lastEpoch=key;selected.clear();last=-1; + if(pending){pending=false;feedback.textContent='CANCELLED · device epoch changed';} + } + // Cheap state projection: do not redraw strip DOM/meter graphics at 12Hz. + render(); + }); + render(); +})();