diff --git a/engine/core/ConsolePuzzleV8Wire.h b/engine/core/ConsolePuzzleV8Wire.h new file mode 100644 index 000000000..0a7484355 --- /dev/null +++ b/engine/core/ConsolePuzzleV8Wire.h @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include + +// One native wire serializer shared by JUCE control-thread producer and +// deterministic S0 fixture generator. NO DSP or callback ownership here. +// Physical ports and PCM measurements MUST come from actual native status. +namespace armix::console { +struct PuzzleV8Pin final { + int port=-1,callback=-1; + std::string label; + bool hasRawPeak=false; + double rawPeak=0.0; +}; +struct PuzzleV8Snapshot final { + std::string epoch="1",backend,captureDevice,playbackDevice; + std::string graphRevision="0",rosterRevision="0",legacyRoutingRevision="0"; + int sampleRate=0,bufferFrames=0; + bool outputArmed=false,rawCapturePresent=false; + bool mainPcmPresent=false,monitorPcmPresent=false; + double rawCapturePeak=0.0; + bool legacyActive=false,legacyRouteAccepted=false; + std::vector inputs,outputs; + // Installed M4 callback does NOT own a ChannelId graph yet. + bool productionCallbackLive=false; +}; +struct PuzzleV8Ack final { + std::string requestId,status="REJECTED",deviceEpoch="0"; + std::string graphRevision="0",rosterRevision="0"; + std::string errorCode="UNIVERSAL_CALLBACK_NOT_READY"; +}; +class PuzzleV8Wire final { + static std::string quote(const std::string& in) { + std::string out="\""; + static constexpr char hex[]="0123456789abcdef"; + for(const unsigned char c:in) { + switch(c) { + case '"':out+="\\\"";break; + case '\\':out+="\\\\";break; + case '\n':out+="\\n";break; + case '\r':out+="\\r";break; + case '\t':out+="\\t";break; + default: + if(c<32) {out+="\\u00";out+=hex[c>>4];out+=hex[c&15];} + else out+=static_cast(c); + } + } + return out+'"'; + } + static const char* bit(bool b) noexcept{return b?"true":"false";} + static std::string number(double n) { + if(!std::isfinite(n)||n<0.)return "null"; + char buffer[80]{}; + std::snprintf(buffer,sizeof(buffer),"%.9g",n); + return buffer; + } + static std::string pins(const std::vector& list,const char* kind) { + std::string s="["; + for(const auto& p:list) { + if(p.port<0||p.port>255||p.callback<0)continue; + if(s.size()>1)s+=','; + s+="{\"id\":"+quote(std::string(kind)+":"+std::to_string(p.port))+ + ",\"port\":"+std::to_string(p.port)+",\"callback\":"+ + std::to_string(p.callback)+",\"label\":"+ + quote(p.label.empty()?std::string(kind)+" "+std::to_string(p.port+1):p.label)+ + ",\"active\":true"; + if(p.hasRawPeak && std::isfinite(p.rawPeak) && p.rawPeak>=0.) { + s+=",\"rawPeak\":"+number(p.rawPeak)+ + ",\"rawPresent\":"+bit(p.rawPeak>0.0005); + } + s+='}'; + } + return s+"]"; + } + static std::string enabled(const std::vector& list) { + std::string s="["; + for(const auto& p:list){ + if(p.port<0||p.port>255||p.callback<0)continue; + if(s.size()>1)s+=','; + s+=std::to_string(p.port); + } + return s+"]"; + } +public: + static std::string snapshot(const PuzzleV8Snapshot& s) { + // Complete v8 mandatory wire even while callback is not universal. + // ChannelId and revisions are decimal strings; no JSON double. + return "{\"schemaVersion\":6,\"productionCallbackLive\":"+ + std::string(bit(s.productionCallbackLive))+ + ",\"device\":{\"epoch\":"+quote(s.epoch)+ + ",\"backend\":"+quote(s.backend)+ + ",\"captureDevice\":"+quote(s.captureDevice)+ + ",\"playbackDevice\":"+quote(s.playbackDevice)+ + ",\"inputEndpoints\":"+pins(s.inputs,"in")+ + ",\"outputEndpoints\":"+pins(s.outputs,"out")+ + ",\"enabledInputs\":"+enabled(s.inputs)+ + ",\"enabledOutputs\":"+enabled(s.outputs)+ + ",\"sampleRate\":"+(s.sampleRate>0?std::to_string(s.sampleRate):"null")+ + ",\"bufferFrames\":"+(s.bufferFrames>0?std::to_string(s.bufferFrames):"null")+ + ",\"outputArmed\":"+bit(s.outputArmed)+ + "},\"graph\":{\"revision\":"+quote(s.graphRevision)+ + ",\"rosterRevision\":"+quote(s.rosterRevision)+ + ",\"channels\":[],\"destinations\":[],\"capabilities\":{" + "\"callbackOwnsChannelIds\":false,\"fullVendorFxMigration\":false," + "\"showAndOutputParity\":false,\"physicalCaptureMapped\":false," + "\"dynamicChannels\":false,\"groups\":false,\"fxReturns\":false," + "\"monitor\":false,\"sendsOnFaders\":false,\"supportedOps\":[]}}," + "\"telemetry\":{\"rawCapturePresent\":"+bit(s.rawCapturePresent)+ + ",\"rawCapturePeak\":"+number(s.rawCapturePeak)+ + ",\"mainPcmPresent\":"+bit(s.mainPcmPresent)+ + ",\"monitorPcmPresent\":"+bit(s.monitorPcmPresent)+ + ",\"channelMeterRmsPeak\":[]},\"legacyM4\":{\"active\":"+ + bit(s.legacyActive)+",\"routeAccepted\":"+bit(s.legacyRouteAccepted)+ + ",\"routingRevision\":"+quote(s.legacyRoutingRevision)+"}}"; + } + static std::string ack(const PuzzleV8Ack& a) { + return "{\"requestId\":"+quote(a.requestId)+ + ",\"status\":"+quote(a.status)+ + ",\"deviceEpoch\":"+quote(a.deviceEpoch)+ + ",\"graphRevision\":"+quote(a.graphRevision)+ + ",\"rosterRevision\":"+quote(a.rosterRevision)+ + ",\"errorCode\":"+quote(a.errorCode)+"}"; + } + static std::string fixture(const PuzzleV8Snapshot& s,const PuzzleV8Ack& a) { + const auto state=snapshot(s); + const auto command="{\"requestId\":"+quote(a.requestId)+ + ",\"deviceEpoch\":"+quote(s.epoch)+ + ",\"baseGraphRevision\":"+quote(s.graphRevision)+ + ",\"baseRosterRevision\":"+quote(s.rosterRevision)+ + ",\"operation\":\"SET_SOURCE\",\"targetChannelId\":null,\"payload\":{}}"; + return "{\"events\":[{\"event\":\"arMixConsoleSnapshot\",\"payload\":"+ + state+"},{\"event\":\"arMixConsoleIntent\",\"payload\":"+command+ + "},{\"event\":\"arMixConsoleAck\",\"payload\":"+ack(a)+ + "},{\"event\":\"arMixConsoleSnapshot\",\"payload\":"+state+"}]}\n"; + } +}; +} // namespace armix::console diff --git a/engine/core/DynamicAcceptedSession.h b/engine/core/DynamicAcceptedSession.h index 4e841a4c5..ec901f2d3 100644 --- a/engine/core/DynamicAcceptedSession.h +++ b/engine/core/DynamicAcceptedSession.h @@ -51,7 +51,8 @@ class DynamicAcceptedSession final { const DynamicGraphRequest& route, std::uint64_t expectedDeviceEpoch, std::uint64_t activeDeviceEpoch, - bool allOutputsDisarmed) { + bool allOutputsDisarmed, + DynamicNativeSessionPublisher::FxPlan fx={}) { Result result=preflight(expectedRosterRevision,expectedGraphRevision); if(!result.ok())return result; auto candidate=accepted_; // once per batch; ONLY CONTROL @@ -61,7 +62,62 @@ class DynamicAcceptedSession final { } return publish(std::move(candidate),route,expectedGraphRevision, expectedDeviceEpoch,activeDeviceEpoch,allOutputsDisarmed, - std::move(result)); + std::move(result),std::move(fx)); + } + + + // A single native structural operation over accepted ChannelSendRef. + // No JS DSP or independent router: same compiled PCM, routing readback, + // device epoch, revision and FX leases as all other native edit paths. + Result wireTransaction(std::uint64_t expectedRosterRevision, + std::uint64_t expectedGraphRevision, + std::span changes, + const DynamicGraphRequest& route, + std::uint64_t expectedDeviceEpoch, + std::uint64_t activeDeviceEpoch, + bool allOutputsDisarmed, + DynamicNativeSessionPublisher::FxPlan fx={}) { + Result result=preflight(expectedRosterRevision,expectedGraphRevision); + if(!result.ok())return result; + // Validate the hardware generation BEFORE inspecting draft edge IDs. + // A stale request may reference an edge removed by a newer device + // epoch; return the stronger device fault without touching the graph. + if(!expectedDeviceEpoch || expectedDeviceEpoch!=activeDeviceEpoch) { + result.fault=Fault::graphRejected; + result.native.fault=DynamicNativeSessionPublisher::Fault::staleDevice; + result.native.revision=publisher_.acceptedRevision(); + return result; + } + auto candidate=accepted_; + result.edit=candidate.wireTransaction(expectedRosterRevision,changes); + if(!result.edit.ok()) { + result.fault=Fault::editRejected;return result; + } + // Never trust an armed GUI candidate that quietly changes capture + // pins, DSP block capacity or device admission. Only pure internal + // edges can be published while hardware output is armed. + const bool samePhysical= + route.physicalInputs==acceptedRequest_.physicalInputs && + route.maxFrames==acceptedRequest_.maxFrames && + route.maxScratchBytes==acceptedRequest_.maxScratchBytes && + route.mainMonoAfterFx==acceptedRequest_.mainMonoAfterFx && + route.sources.size()==acceptedRequest_.sources.size() && + std::equal(route.sources.begin(),route.sources.end(), + acceptedRequest_.sources.begin(), + [](const DynamicSourcePatch& lhs,const DynamicSourcePatch& rhs) { + return lhs.id==rhs.id && lhs.inputL==rhs.inputL && + lhs.inputR==rhs.inputR && lhs.stereo==rhs.stereo; + }); + if(!allOutputsDisarmed && !samePhysical) { + result.fault=Fault::graphRejected; + result.native.fault=DynamicNativeSessionPublisher::Fault::outputArmed; + result.native.revision=publisher_.acceptedRevision(); + result.edit.createdEdgeIds.clear(); + return result; + } + return publish(std::move(candidate),route,expectedGraphRevision, + expectedDeviceEpoch,activeDeviceEpoch,allOutputsDisarmed, + std::move(result),std::move(fx),samePhysical); } // Studio Pro: one independent Bus ChannelId and automatic assignment of @@ -74,7 +130,8 @@ class DynamicAcceptedSession final { std::uint64_t expectedDeviceEpoch, std::uint64_t activeDeviceEpoch, bool allOutputsDisarmed, - float parallelGain=.25f) { + float parallelGain=.25f, + DynamicNativeSessionPublisher::FxPlan fx={}) { Result result=preflight(expectedRosterRevision,expectedGraphRevision); if(!result.ok())return result; auto candidate=accepted_; @@ -85,7 +142,7 @@ class DynamicAcceptedSession final { } return publish(std::move(candidate),route,expectedGraphRevision, expectedDeviceEpoch,activeDeviceEpoch,allOutputsDisarmed, - std::move(result)); + std::move(result),std::move(fx)); } // Add an empty GROUP or FX Channel, directly OUT -> MAIN, exactly as a @@ -96,7 +153,8 @@ class DynamicAcceptedSession final { const DynamicGraphRequest& route, std::uint64_t expectedDeviceEpoch, std::uint64_t activeDeviceEpoch, - bool allOutputsDisarmed) { + bool allOutputsDisarmed, + DynamicNativeSessionPublisher::FxPlan fx={}) { Result result=preflight(expectedRosterRevision,expectedGraphRevision); if(!result.ok())return result; auto candidate=accepted_; @@ -107,7 +165,7 @@ class DynamicAcceptedSession final { } return publish(std::move(candidate),route,expectedGraphRevision, expectedDeviceEpoch,activeDeviceEpoch,allOutputsDisarmed, - std::move(result)); + std::move(result),std::move(fx)); } // Delete an existing GROUP or FX return, atomically rerouting primary @@ -119,7 +177,8 @@ class DynamicAcceptedSession final { const DynamicGraphRequest& route, std::uint64_t expectedDeviceEpoch, std::uint64_t activeDeviceEpoch, - bool allOutputsDisarmed) { + bool allOutputsDisarmed, + DynamicNativeSessionPublisher::FxPlan fx={}) { Result result=preflight(expectedRosterRevision,expectedGraphRevision); if(!result.ok())return result; auto candidate=accepted_; @@ -130,7 +189,7 @@ class DynamicAcceptedSession final { } return publish(std::move(candidate),route,expectedGraphRevision, expectedDeviceEpoch,activeDeviceEpoch,allOutputsDisarmed, - std::move(result)); + std::move(result),std::move(fx)); } // Live routine controls change ONLY accepted edges/nodes. Persist values @@ -144,6 +203,31 @@ class DynamicAcceptedSession final { return false; return accepted_.rememberLiveMix(id,linear,pan); } + // The accepted physical patch is canonical too: subsequent Group/FX + // graph recompiles must preserve the most recently ACKed live SOURCE. + bool setLivePhysicalSource(std::uint64_t epoch,std::uint64_t graphRevision, + ChannelId id,int inputL,int inputR, + bool stereo) noexcept { + if(!accepted_.find(id))return false; + const auto it=std::find_if(acceptedRequest_.sources.begin(), + acceptedRequest_.sources.end(), + [id](const DynamicSourcePatch& p){return p.id==id;}); + if(it==acceptedRequest_.sources.end() || it->stereo!=stereo || + !publisher_.setPhysicalSource(epoch,graphRevision,id,inputL,inputR,stereo)) + return false; + it->inputL=inputL;it->inputR=inputR; + return true; + } + const DynamicGraphRequest& acceptedPhysicalRequest() const noexcept { + return acceptedRequest_; // CONTROL readback, not browser draft + } + bool setLiveMuteSolo(std::uint64_t epoch,std::uint64_t graphRevision, + ChannelId id,bool mute,bool solo) noexcept { + if(!accepted_.find(id)|| + !publisher_.setChannelMuteSolo(epoch,graphRevision,id,mute,solo)) + return false; + return accepted_.rememberLiveMuteSolo(id,mute,solo); + } bool setLiveParallelSend(std::uint64_t epoch,std::uint64_t graphRevision, ChannelId source,ChannelId destination, bool preFader,float linear) noexcept { @@ -172,7 +256,7 @@ class DynamicAcceptedSession final { return publisher_.render(epoch,inputs,inputCount,mainL,mainR,frames, muted,std::forward(fx),monitorL,monitorR); } - void unpublish() noexcept {publisher_.unpublish();} + void unpublish() noexcept {publisher_.unpublish();hasHostedFx_=false;} void pollRetirement() noexcept {publisher_.pollRetirement();} private: @@ -191,22 +275,75 @@ class DynamicAcceptedSession final { const DynamicGraphRequest& route, std::uint64_t previousGraphRevision, std::uint64_t requestedEpoch,std::uint64_t currentEpoch, - bool outputsDisarmed,Result&& result) { - result.native=publisher_.commit(candidate,route,previousGraphRevision, - requestedEpoch,currentEpoch,outputsDisarmed); + bool outputsDisarmed,Result&& result, + DynamicNativeSessionPublisher::FxPlan fx, + bool verifiedInternalWireOnly=false) { + // Existing SOURCE targets belong to the accepted native session. + // For already-patched ChannelIds with the same input format, ignore + // stale physical pin ordinals supplied by an old GUI draft during + // +GROUP/+FX Return. An explicit format change is structural. + // E2: once an accepted graph has hosted native VST, structural + // +GROUP/+FX Return/reorder must publish the same real instance + // leases at the next revision. Without this check, an omitted FxPlan + // silently drops processing on every already-audible channel. + // Reject while preserving old graph, vendor state and PCM. + if(hasHostedFx_ && !fx.owner) { + result.fault=Fault::graphRejected; + result.native.fault=DynamicNativeSessionPublisher::Fault::invalidCandidate; + result.native.revision=publisher_.acceptedRevision(); + result.edit.createdIds.clear(); + result.edit.createdEdgeIds.clear(); + return result; + } + // A structural OUT/GROUP/Return edit does NOT implicitly change IN. + // The operator's same-format IN gesture is accepted first through + // setLivePhysicalSource(epoch,revision,...), which also updates the + // canonical acceptedRequest_. A stale GUI draft must rebase from that + // accepted SOURCE before asking for a structural ACK. Never silently + // restore old pins and claim the requested new route was accepted. + // Genuine format changes remain structural, with normal graph checks. + for(const auto& source:route.sources) { + const bool valid=DynamicPreparedMixerBlock::validPhysicalPatch( + route.physicalInputs,source.inputL,source.inputR,source.stereo); + const auto prior=std::find_if(acceptedRequest_.sources.begin(), + acceptedRequest_.sources.end(), + [&](const DynamicSourcePatch& p){return p.id==source.id;}); + const bool conflicting=prior!=acceptedRequest_.sources.end() && + source.stereo==prior->stereo && + (source.inputL!=prior->inputL || source.inputR!=prior->inputR); + if(!valid || conflicting) { + result.fault=Fault::graphRejected; + result.native.fault=DynamicNativeSessionPublisher::Fault::invalidGraph; + result.native.graphError={DynamicGraphFault::invalidSource,source.id}; + result.native.revision=publisher_.acceptedRevision(); + result.edit.createdIds.clear(); + result.edit.createdEdgeIds.clear(); + return result; // old audible SOURCE and VST3 leases unchanged + } + } + auto effective=route; // CONTROL-only; preallocated before commit + const bool nextHasFx=static_cast(fx.owner); + result.native=publisher_.commit(candidate,effective,previousGraphRevision, + requestedEpoch,currentEpoch,outputsDisarmed, + std::move(fx),verifiedInternalWireOnly); if(!result.native.ok()) { result.fault=Fault::graphRejected; - result.edit.createdIds.clear(); // NEVER advertise phantom Bus + result.edit.createdIds.clear(); + result.edit.createdEdgeIds.clear(); // NEVER advertise phantom Bus return result; // candidate destroyed; accepted state intact } static_assert(std::is_nothrow_move_assignable_v); accepted_=std::move(candidate); + acceptedRequest_=std::move(effective); + hasHostedFx_=nextHasFx; result.rosterRevision=accepted_.revision(); result.graphRevision=result.native.revision; return result; } DynamicChannelRoster accepted_; + DynamicGraphRequest acceptedRequest_{}; // CONTROL-only accepted physical SSOT DynamicNativeSessionPublisher publisher_; + bool hasHostedFx_=false; // CONTROL only; never an audio callback flag }; } // namespace armix::mixer diff --git a/engine/core/DynamicChannelFxLeaseBank.h b/engine/core/DynamicChannelFxLeaseBank.h new file mode 100644 index 000000000..46c29f4f8 --- /dev/null +++ b/engine/core/DynamicChannelFxLeaseBank.h @@ -0,0 +1,277 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "DynamicChannelRoster.h" +#include "LiveChannelFxGraph.h" +#include +#include +#include +#include +#include +#include +#include + +// M5 universal ChannelId/VST3 ownership bridge. +// +// Unlike the fixed ten-strip index, this immutable CONTROL-PREPARED table +// follows stable ChannelId across +CHANNEL, +GROUP, FX Return and reorder. +// It holds the exact M4 vendor FxInstance owner leases (binary state, +// parameters, bypass envelope, reverb tail). The audio callback traverses +// RAW pointers only: no shared_ptr refcount, heap, lock, VST instantiation, +// string compare or plugin lookup by catalog name. +// +// The bank must be owned by the SAME published/retired native graph snapshot +// as the PCM schedule. Do not discard it while a callback can render from it. +// Never render a former legacy graph concurrently with its migrated instances. +namespace armix::mixer { +class DynamicChannelFxLeaseBank final { +public: + using FxGraph=LiveChannelFxGraph; + using Lease=FxGraph::InstanceLease; + static constexpr int maxInserts=FxGraph::maxInsertsPerStrip; + + struct Assignment final { + ChannelId id{}; + ProcessingFormat format=ProcessingFormat::stereo; + std::vector inserts; // CONTROL only; no creation on callback + }; + + // Occupied CH1 vendor/Orbit owner remains alive with accepted PCM. + // A callback reads only a raw, prevalidated pointer; no refcount/heap. + struct ExternalLease final { + ChannelId id{}; + std::shared_ptr owner; + void* context=nullptr; + void (*render)(void*,float*,float*,int) noexcept=nullptr; + bool populated() const noexcept {return id.value||owner||context||render;} + bool valid() const noexcept { + return id.value && owner && context==owner.get() && render; + } + }; + enum class Fault : std::uint8_t { + none,invalidEpoch,emptyId,duplicateChannel,tooManyInserts, + emptyLease,duplicateInstance,invalidBusLayout,uncompensatedLatency, + missingLegacyIdentity,invalidExternalLease + }; + DynamicChannelFxLeaseBank()=default; + DynamicChannelFxLeaseBank(const DynamicChannelFxLeaseBank&)=delete; + DynamicChannelFxLeaseBank& operator=(const DynamicChannelFxLeaseBank&)=delete; + DynamicChannelFxLeaseBank(DynamicChannelFxLeaseBank&&)=default; + DynamicChannelFxLeaseBank& operator=(DynamicChannelFxLeaseBank&&)=default; + + // Used by message-thread M4->M5 migration. There is no fallback by + // slot position or catalog ID: an actual opaque M4 instance token is + // required, so a Show/reorder cannot accidentally acquire another plugin. + static bool captureLegacy(int lane,ChannelId nativeId, + ProcessingFormat format, + const FxGraph& prior, + Assignment& destination) { + if(lane<0||lane>=FxGraph::fxSlots||!nativeId.value)return false; + Assignment staged; + staged.id=nativeId;staged.format=format; + for(int slot=0;slotinstanceId!=token)return false; + staged.inserts.push_back(std::move(owner)); + } + destination=std::move(staged); + return true; + } + + static Fault prepare(std::uint64_t epoch,std::uint64_t revision, + std::span bindings, + DynamicChannelFxLeaseBank& destination) { + return prepare(epoch,revision,bindings,destination,ExternalLease{}); + } + static Fault prepare(std::uint64_t epoch,std::uint64_t revision, + std::span bindings, + DynamicChannelFxLeaseBank& destination, + ExternalLease external) { + if(external.populated() && !external.valid()) + return Fault::invalidExternalLease; + if(!epoch||!revision)return Fault::invalidEpoch; + DynamicChannelFxLeaseBank candidate; + candidate.epoch_=epoch;candidate.revision_=revision; + candidate.rows_.reserve(bindings.size()); + for(const auto& b:bindings) { + if(!b.id.value)return Fault::emptyId; + if(b.inserts.size()>static_cast(maxInserts)) + return Fault::tooManyInserts; + if(b.format!=ProcessingFormat::mono && + b.format!=ProcessingFormat::stereo)return Fault::invalidBusLayout; + Row row;row.id=b.id;row.format=b.format; + row.count=static_cast(b.inserts.size()); + for(std::size_t i=0;iprocessor)return Fault::emptyLease; + // M4's preparation verifies a stereo processor layout for + // both mono-as-dual and stereo strips. Other plugin layouts + // must be negotiated explicitly before a future PCM cutover. + if(owner->processor->getTotalNumInputChannels()!=2 || + owner->processor->getTotalNumOutputChannels()!=2) + return Fault::invalidBusLayout; + // Global live-mixer architecture (Waves LV1/Ableton): + // parallel PRE/POST paths with unequal VST latency require + // true graph-aware PDC. Until that engine exists, never + // admit a plugin that would produce misaligned MAIN/MONITOR, + // AUX/Group or parallel FX Return PCM. This is a CONTROL-only + // processor inspection, NEVER called from realtime. + if(owner->processor->getLatencySamples()!=0) + return Fault::uncompensatedLatency; + for(const auto& existing:candidate.rows_) + for(std::size_t k=0;kcount!=0)return Fault::invalidExternalLease; + candidate.external_=std::move(external); + } + destination=std::move(candidate); // atomic control-thread acceptance + return Fault::none; + } + + std::uint64_t epoch() const noexcept{return epoch_;} + std::uint64_t revision() const noexcept{return revision_;} + std::size_t lanes() const noexcept{return rows_.size();} + ChannelId externalChannel() const noexcept{return external_.id;} + std::size_t insertCount(ChannelId id) const noexcept { + const auto* p=find(id);return p?p->count:0; + } + const Lease* ownerForControl(ChannelId id,std::size_t slot) const noexcept { + const auto* p=find(id);return p&&slotcount?&p->owners[slot]:nullptr; + } + + // E2: stable ChannelId VST3 control plane. Requests are serialized by + // the native CONTROL writer, never the audio callback. A stale epoch, + // graph or opaque instance token cannot bypass somebody else's plugin. + // FxInstance owns the existing 8-ms realtime wet/dry envelope and vendor + // processBlock. No graph swap, device restart, VST creation or RT heap. + bool setInsertBypass(std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,ChannelId id, + std::size_t slot,const juce::String& instanceToken, + bool bypass) const noexcept { + if(expectedEpoch!=epoch_ || expectedRevision!=revision_ || + !id.value || instanceToken.isEmpty())return false; + const auto* owner=ownerForControl(id,slot); + if(!owner || !*owner || !(*owner)->processor || + (*owner)->instanceId!=instanceToken)return false; + (*owner)->bypassRequested.store(bypass,std::memory_order_release); + return true; + } + // The actual prepared vendor instance is also the native editor owner; + // never synthesize a WebView editor or use a catalog name as identity. + Lease leaseEditor(std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,ChannelId id, + std::size_t slot, + const juce::String& instanceToken) const noexcept { + if(expectedEpoch!=epoch_ || expectedRevision!=revision_ || + !id.value || instanceToken.isEmpty())return {}; + const auto* owner=ownerForControl(id,slot); + return owner && *owner && (*owner)->processor && + (*owner)->instanceId==instanceToken ? *owner : Lease{}; + } + + // CONTROL only: rebind all current vendor leases to a new graph revision. + // The same FxInstance keeps editor/state/tail and the audio callback only + // sees raw prepared pointers. No new plugin or audio pipeline is created. + static Fault reuseRevision(std::uint64_t epoch,std::uint64_t revision, + const DynamicChannelFxLeaseBank& prior, + DynamicChannelFxLeaseBank& destination) { + if(!epoch || epoch!=prior.epoch_ || + revision<=prior.revision_)return Fault::invalidEpoch; + std::vector retained; + retained.reserve(prior.rows_.size()); + for(const auto& row:prior.rows_) { + Assignment item; + item.id=row.id;item.format=row.format; + item.inserts.reserve(row.count); + for(std::size_t slot=0;slotprocessor)return Fault::emptyLease; + if(prior.external_.id==target)return Fault::invalidExternalLease; + std::vector list; + list.reserve(prior.rows_.size()+1); + bool found=false; + for(const auto& row:prior.rows_) { + Assignment a;a.id=row.id;a.format=row.format; + a.inserts.reserve(row.count+(row.id==target?1:0)); + for(std::size_t i=0;i=maxInserts)return Fault::tooManyInserts; + if(row.format!=format)return Fault::invalidBusLayout; + a.inserts.push_back(plugin);found=true; + } + list.push_back(std::move(a)); + } + if(!found) { + Assignment a;a.id=target;a.format=format; + a.inserts.push_back(std::move(plugin)); + list.push_back(std::move(a)); + } + return prepare(epoch,revision,list,destination,prior.external_); + } + + // Process each M4 VST exactly once at its target ChannelId. CPU work is + // proportional to that node's FX rack, not every Channel in the session. + // Call only on the native audio thread after epoch/revision graph admission. + void operator()(ChannelId id,float* left,float* right,int frames) const noexcept { + const Row* row=find(id); + if(!row)return; // a genuinely dry ChannelId or MASTER + if(!left||!right||left==right||frames<=0)return; + if(external_.id==id) { + external_.render(external_.context,left,right,frames); + return; // occupied CH1 is processed exactly once + } + for(std::size_t i=0;icount;++i) + row->raw[i]->render(left,right,frames); + } + +private: + struct Row final { + ChannelId id{}; + ProcessingFormat format=ProcessingFormat::stereo; + std::uint8_t count=0; + std::array owners{}; + std::array raw{}; + }; + const Row* find(ChannelId id) const noexcept { + const auto it=std::lower_bound(rows_.begin(),rows_.end(),id.value, + [](const Row& row,std::uint64_t value){return row.id.valueid==id?&*it:nullptr; + } + std::vector rows_{}; + ExternalLease external_{}; // PCM snapshot retirement occurs off RT + std::uint64_t epoch_=0,revision_=0; +}; +} // namespace armix::mixer diff --git a/engine/core/DynamicChannelRoster.h b/engine/core/DynamicChannelRoster.h index a666b15a1..3b435432d 100644 --- a/engine/core/DynamicChannelRoster.h +++ b/engine/core/DynamicChannelRoster.h @@ -29,6 +29,7 @@ struct ChannelSendRef final { bool preFader=false; float pan=0.f; // send-only balance: PRE mono uses equal-power coefficients bool primaryOutput=false; // OUT selector edge, not a parallel SEND + std::uint64_t edgeId=0; // stable native identity; CONTROL-only assignment }; struct ChannelStripDefinition final { ChannelId id{}; @@ -51,7 +52,8 @@ struct ChannelRosterBudget final { enum class ChannelEditFault : std::uint8_t { none, staleRevision, invalidAction, missingChannel, invalidPosition, - invalidValue, budgetExceeded, linkedDestination, idExhausted + invalidValue, budgetExceeded, linkedDestination, idExhausted, + missingEdge, duplicateSend }; struct ChannelEdit final { enum class Kind : std::uint8_t { @@ -67,6 +69,7 @@ struct ChannelEdit final { bool enabled=false; // mute/solo value (or future enable operation) bool preFader=false; // send tap at construction, no hidden POST default bool primaryOutput=false; // exclusive OUT edge, independent of parallel SEND + bool connectMainOnCreate=false; // WIRE-first native creation; legacy imports unchanged float sendPan=0.f; // independent send PAN, never channel fader PAN std::string text; }; @@ -75,9 +78,18 @@ struct ChannelEditResult final { std::size_t actionIndex=0; std::uint64_t revision=0; std::vector createdIds; + std::vector createdEdgeIds; bool ok() const noexcept {return fault==ChannelEditFault::none;} }; +struct WireChange final { + enum class Kind : std::uint8_t {connect,remove,retarget,routeOnly}; + Kind kind=Kind::connect; + ChannelId from{},to{}; + std::uint64_t edgeId=0; + float gain=1.f; +}; + class DynamicChannelRoster final { public: explicit DynamicChannelRoster(ChannelRosterBudget budget={}) : budget_(budget) {} @@ -85,9 +97,8 @@ class DynamicChannelRoster final { std::size_t size() const noexcept {return channels_.size();} const std::vector& channels() const noexcept {return channels_;} const ChannelStripDefinition* find(ChannelId id) const noexcept { - const auto it=std::find_if(channels_.begin(),channels_.end(), - [id](const auto& c){return c.id==id;}); - return it==channels_.end()?nullptr:&*it; + const auto it=index_.find(id.value); + return it==index_.end()?nullptr:&channels_[it->second]; } // CONTROL THREAD ONLY. A realtime parameter target must survive the @@ -97,23 +108,30 @@ class DynamicChannelRoster final { bool rememberLiveMix(ChannelId id,float gain,float pan) noexcept { if(!id.value || !std::isfinite(gain) || gain<0.f || gain>4.f || !std::isfinite(pan) || pan< -1.f || pan>1.f)return false; - for(auto& row:channels_)if(row.id==id) { - row.faderLinear=gain;row.pan=pan;return true; - } - return false; + const auto it=index_.find(id.value); + if(it==index_.end())return false; + auto& row=channels_[it->second]; + row.faderLinear=gain;row.pan=pan; + return true; + } + bool rememberLiveMuteSolo(ChannelId id,bool mute,bool solo) noexcept { + const auto it=index_.find(id.value); + if(!id.value||it==index_.end())return false; + auto& row=channels_[it->second]; + row.mute=mute;row.solo=solo; + return true; } bool rememberLiveParallelSend(ChannelId id,ChannelId destination, bool preFader,float gain) noexcept { if(!id.value || !destination.value || !std::isfinite(gain) || gain<0.f || gain>4.f)return false; - for(auto& row:channels_)if(row.id==id){ - for(auto& link:row.sends) - if(link.destination==destination && - link.preFader==preFader && !link.primaryOutput) { - link.gain=gain;return true; - } - return false; - } + const auto it=index_.find(id.value); + if(it==index_.end())return false; + for(auto& link:channels_[it->second].sends) + if(link.destination==destination && + link.preFader==preFader && !link.primaryOutput) { + link.gain=gain;return true; + } return false; } @@ -130,6 +148,7 @@ class DynamicChannelRoster final { } auto candidate=channels_; // one copy per BATCH, never in audio callback auto next=nextId_; + std::vector defaultMainOnCreate; const auto seek=[&candidate](ChannelId id){ return std::find_if(candidate.begin(),candidate.end(), [id](const auto& c){return c.id==id;}); @@ -162,6 +181,10 @@ class DynamicChannelRoster final { if(!validName(row.name)) {result.fault=ChannelEditFault::invalidValue;break;} candidate.insert(candidate.begin()+static_cast(op.position),std::move(row)); result.createdIds.push_back(candidate[op.position].id); + if(op.connectMainOnCreate && + candidate[op.position].role!=ChannelRole::main && + candidate[op.position].role!=ChannelRole::monitor) + defaultMainOnCreate.push_back(candidate[op.position].id); } else { auto it=seek(op.id); if(op.id.value==0 || it==candidate.end()) { @@ -220,7 +243,14 @@ class DynamicChannelRoster final { else it->insertCatalogIds.push_back(op.text); break; case ChannelEdit::Kind::addSendReference: - if(op.primaryOutput && std::any_of(it->sends.begin(),it->sends.end(), + // OUT is a single unity, POST-fader serial route. Its + // pan/fader live on the source strip; only SEND may own + // an independent PRE/POST tap, level or pan. Reject a + // malformed primary edge before it can reach PCM/GUI ACK. + if(op.primaryOutput && + (op.preFader || op.value!=1.f || op.sendPan!=0.f)) + result.fault=ChannelEditFault::invalidValue; + else if(op.primaryOutput && std::any_of(it->sends.begin(),it->sends.end(), [](const auto& s){return s.primaryOutput;})) result.fault=ChannelEditFault::invalidValue; else if(op.target.value==0 || op.target==op.id || seek(op.target)==candidate.end()) @@ -238,9 +268,18 @@ class DynamicChannelRoster final { result.fault=ChannelEditFault::invalidValue;break; } auto& edges=it->sends; - edges.erase(std::remove_if(edges.begin(),edges.end(), - [](const auto& x){return x.primaryOutput;}),edges.end()); - if(op.target.value) { + const auto primary=std::find_if(edges.begin(),edges.end(), + [](const auto& edge){return edge.primaryOutput;}); + if(!op.target.value) { + if(primary!=edges.end())edges.erase(primary); + } else if(primary!=edges.end()) { + // Retarget the EXACT original physical cable; preserve + // stable edgeId instead of removing/recreating it. + primary->destination=op.target; + primary->gain=1.f; + primary->preFader=false; + primary->pan=0.f; + } else { if(edges.size()>=budget_.maximumSendsPerChannel) { result.fault=ChannelEditFault::budgetExceeded;break; } @@ -258,14 +297,161 @@ class DynamicChannelRoster final { result.fault=ChannelEditFault::budgetExceeded;break; } } + // WIRE-first channel creation must connect MAIN exactly ONCE in the + // SAME batch/revision, even when MAIN was created later in this batch. + // Existing restored/disconnected channels are never auto-rewired. + if(result.ok() && !defaultMainOnCreate.empty()) { + const auto main=std::find_if(candidate.begin(),candidate.end(), + [](const auto& row){return row.role==ChannelRole::main;}); + if(main==candidate.end() || + std::count_if(candidate.begin(),candidate.end(), + [](const auto& row){return row.role==ChannelRole::main;})!=1) { + result.fault=ChannelEditFault::invalidValue; + } else { + const auto mainId=main->id; + for(const auto id:defaultMainOnCreate){ + auto row=seek(id); + if(row==candidate.end() || + row->sends.size()>=budget_.maximumSendsPerChannel){ + result.fault=ChannelEditFault::budgetExceeded;break; + } + const bool exists=std::any_of(row->sends.begin(),row->sends.end(), + [&](const auto& send){return send.destination==mainId;}); + if(!exists)row->sends.push_back({mainId,1.f,false,0.f,true,0}); + } + } + } if(result.ok() && !withinBudget(candidate))result.fault=ChannelEditFault::budgetExceeded; if(!result.ok()) {result.createdIds.clear();return result;} + // Structural edits are infrequent and prepared entirely on CONTROL. + // Rebuild before acceptance: rejected/failed edits cannot leave the + // active stable-ID map pointing into an old reordered vector. + std::uint64_t stagedNextEdge=nextEdgeId_; + if(!assignMissingEdgeIds(candidate,stagedNextEdge)) { + result.fault=ChannelEditFault::idExhausted; + result.createdIds.clear();return result; + } + auto stagedIndex=buildIndex(candidate); channels_.swap(candidate); + nextEdgeId_=stagedNextEdge; + index_.swap(stagedIndex); nextId_=next; result.revision=++revision_; return result; } + + // This is the only WIRE topology editor. Uses the SAME ChannelSendRef + // inventory as the native PCM compiler and existing source/FX ownership. + // The accepted session later compiles the whole DAG and publishes once. + ChannelEditResult wireTransaction( + std::uint64_t expectedRevision,std::span changes) { + ChannelEditResult result;result.revision=revision_; + if(expectedRevision!=revision_){result.fault=ChannelEditFault::staleRevision;return result;} + if(changes.empty() || revision_==std::numeric_limits::max()){ + result.fault=ChannelEditFault::invalidAction;return result; + } + auto candidate=channels_; // one CONTROL-thread batch copy + const auto main=std::find_if(candidate.begin(),candidate.end(), + [](const auto& ch){return ch.role==ChannelRole::main;}); + if(main==candidate.end()){result.fault=ChannelEditFault::invalidAction;return result;} + const ChannelId mainId=main->id; + std::uint64_t stagedNextEdge=nextEdgeId_; + if(!assignMissingEdgeIds(candidate,stagedNextEdge)){ + result.fault=ChannelEditFault::idExhausted;return result; + } + for(std::size_t i=0;irole==ChannelRole::main || source->role==ChannelRole::monitor){ + result.fault=ChannelEditFault::missingChannel;break; + } + auto& sends=source->sends; + if(op.kind==WireChange::Kind::remove || + op.kind==WireChange::Kind::retarget) { + const auto edge=std::find_if(sends.begin(),sends.end(), + [&](const auto& s){return s.edgeId==op.edgeId;}); + if(!op.edgeId || edge==sends.end()) { + result.fault=ChannelEditFault::missingEdge;break; + } + if(op.kind==WireChange::Kind::remove){sends.erase(edge);continue;} + if(!op.to.value || op.to==op.from || edge->destination==op.to){ + result.fault=ChannelEditFault::invalidValue;break; + } + edge->destination=op.to; // retain exact edgeId, gain and tap + continue; + } + if(op.kind!=WireChange::Kind::connect && + op.kind!=WireChange::Kind::routeOnly) { + result.fault=ChannelEditFault::invalidAction;break; + } + if(!op.to.value || op.to==op.from || !std::isfinite(op.gain) || + op.gain<0.f || op.gain>4.f || + (op.kind==WireChange::Kind::routeOnly && op.to==mainId)){ + result.fault=ChannelEditFault::invalidValue;break; + } + const bool already=std::any_of(sends.begin(),sends.end(), + [&](const auto& s){return s.destination==op.to;}); + if(already && op.kind==WireChange::Kind::connect){ + result.fault=ChannelEditFault::duplicateSend;break; + } + if(op.kind==WireChange::Kind::routeOnly){ + sends.erase(std::remove_if(sends.begin(),sends.end(), + [&](const auto& s){return s.destination==mainId;}), + sends.end()); + if(already)continue; // retain original edgeId/gain + } + if(sends.size()>=budget_.maximumSendsPerChannel){ + result.fault=ChannelEditFault::budgetExceeded;break; + } + const bool hasPrimary=std::any_of(sends.begin(),sends.end(), + [](const auto& s){return s.primaryOutput;}); + const bool primary=!hasPrimary && + (op.to==mainId || op.kind==WireChange::Kind::routeOnly); + sends.push_back({op.to,op.gain,false,0.f,primary,0}); + } + if(result.ok()){ + // Legacy PRE and primary edges share the same accepted graph. + // The PCM compiler also validates complete reachability/cycles. + std::unordered_map indexes; + for(std::size_t i=0;i destinations; + for(const auto& edge:row.sends){ + if(!indexes.count(edge.destination.value) || + row.id==edge.destination || + row.role==ChannelRole::main || row.role==ChannelRole::monitor){ + result.fault=ChannelEditFault::invalidValue;break; + } + if(!destinations.insert(edge.destination.value).second){ + result.fault=ChannelEditFault::duplicateSend;break; + } + } + } + if(result.ok() && !withinBudget(candidate)) + result.fault=ChannelEditFault::budgetExceeded; + } + if(!result.ok())return result; + if(!assignMissingEdgeIds(candidate,stagedNextEdge)){ + result.fault=ChannelEditFault::idExhausted;return result; + } + for(const auto& row:candidate) + for(const auto& edge:row.sends) + if(edge.edgeId>=nextEdgeId_) + result.createdEdgeIds.push_back(edge.edgeId); + auto stagedIndex=buildIndex(candidate); + channels_.swap(candidate); + index_.swap(stagedIndex); + nextEdgeId_=stagedNextEdge; + result.revision=++revision_; + return result; + } + // Studio Console Add Bus / Add FX Channel: allocate a fresh independent // stereo ChannelId, OUT -> MAIN, without borrowing an input or requiring // a selection. CONTROL only; native graph publication is separate. @@ -301,7 +487,18 @@ class DynamicChannelRoster final { if(!withinBudget(candidate)) { result.fault=ChannelEditFault::budgetExceeded;return result; } - channels_.swap(candidate);result.createdIds.push_back({nextId_++}); + // Structural edits are infrequent and prepared entirely on CONTROL. + // Rebuild before acceptance: rejected/failed edits cannot leave the + // active stable-ID map pointing into an old reordered vector. + std::uint64_t stagedNextEdge=nextEdgeId_; + if(!assignMissingEdgeIds(candidate,stagedNextEdge)) { + result.fault=ChannelEditFault::idExhausted; + result.createdIds.clear();return result; + } + auto stagedIndex=buildIndex(candidate); + channels_.swap(candidate); + nextEdgeId_=stagedNextEdge; + index_.swap(stagedIndex);result.createdIds.push_back({nextId_++}); result.revision=++revision_;return result; } @@ -351,7 +548,18 @@ class DynamicChannelRoster final { if(!withinBudget(candidate)) { result.fault=ChannelEditFault::budgetExceeded;return result; } + // Structural edits are infrequent and prepared entirely on CONTROL. + // Rebuild before acceptance: rejected/failed edits cannot leave the + // active stable-ID map pointing into an old reordered vector. + std::uint64_t stagedNextEdge=nextEdgeId_; + if(!assignMissingEdgeIds(candidate,stagedNextEdge)) { + result.fault=ChannelEditFault::idExhausted; + result.createdIds.clear();return result; + } + auto stagedIndex=buildIndex(candidate); channels_.swap(candidate); + nextEdgeId_=stagedNextEdge; + index_.swap(stagedIndex); result.revision=++revision_;return result; } @@ -426,13 +634,50 @@ class DynamicChannelRoster final { if(!withinBudget(candidate)) { result.fault=ChannelEditFault::budgetExceeded;return result; } + // Structural edits are infrequent and prepared entirely on CONTROL. + // Rebuild before acceptance: rejected/failed edits cannot leave the + // active stable-ID map pointing into an old reordered vector. + std::uint64_t stagedNextEdge=nextEdgeId_; + if(!assignMissingEdgeIds(candidate,stagedNextEdge)) { + result.fault=ChannelEditFault::idExhausted; + result.createdIds.clear();return result; + } + auto stagedIndex=buildIndex(candidate); channels_.swap(candidate); + nextEdgeId_=stagedNextEdge; + index_.swap(stagedIndex); ++nextId_;result.revision=++revision_; result.createdIds.push_back(busId); return result; } private: + static bool assignMissingEdgeIds( + std::vector& rows,std::uint64_t& next) { + std::unordered_set used; + for(const auto& row:rows) + for(const auto& edge:row.sends) + if(edge.edgeId && !used.insert(edge.edgeId).second)return false; + for(auto& row:rows) + for(auto& edge:row.sends)if(!edge.edgeId){ + while(used.count(next)) { + if(next==std::numeric_limits::max())return false; + ++next; + } + if(!next || next==std::numeric_limits::max())return false; + edge.edgeId=next; + used.insert(next++); + } + return true; + } + static std::unordered_map buildIndex( + const std::vector& rows) { + std::unordered_map index; + index.reserve(rows.size()); + for(std::size_t i=0;i channels_; - std::uint64_t revision_=0, nextId_=1; + std::unordered_map index_; // CONTROL ONLY + std::uint64_t revision_=0, nextId_=1, nextEdgeId_=1; }; } // namespace armix::mixer diff --git a/engine/core/DynamicConsoleRoutingView.h b/engine/core/DynamicConsoleRoutingView.h index a610abbe3..29cf7b460 100644 --- a/engine/core/DynamicConsoleRoutingView.h +++ b/engine/core/DynamicConsoleRoutingView.h @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -18,6 +19,13 @@ struct ConsoleSendView final { ChannelId destination{}; float gain=1.f,pan=0.f; bool preFader=false; + std::uint64_t edgeId=0; +}; +struct ConsoleEdgeView final { + std::uint64_t edgeId=0; + ChannelId from{},to{}; + float gainLinear=1.f; + bool preFader=false,primaryOutput=false; }; struct ConsoleChannelView final { ChannelId id{}; @@ -40,6 +48,7 @@ class DynamicConsoleRoutingView final { public: std::uint64_t rosterRevision=0; std::vector channels; + std::vector edges; // exact native accepted graph, NOT a second graph ChannelId main{},monitor{}; const ConsoleChannelView* find(ChannelId id) const noexcept { const auto it=std::find_if(channels.begin(),channels.end(), @@ -73,11 +82,15 @@ class DynamicConsoleRoutingView final { next.channels.push_back(std::move(item)); } if(!next.main.value)return false; + std::unordered_set acceptedEdgeIds; for(std::size_t i=0;isecond]; if(link.primaryOutput) { if(sender.primaryOutput.value || link.preFader || @@ -87,7 +100,7 @@ class DynamicConsoleRoutingView final { destination.primarySources.push_back(sender.id); } else { sender.parallelSends.push_back( - {link.destination,link.gain,link.pan,link.preFader}); + {link.destination,link.gain,link.pan,link.preFader,link.edgeId}); // One source shown once in the Bus fan-in even if it has // multiple legal taps to that destination. if(std::find(destination.parallelSendSources.begin(), diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index 65b315d8a..c767600af 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -3,11 +3,13 @@ #include "DynamicPreparedMixerBlock.h" #include "DynamicConsoleRoutingView.h" #include "RealtimeRoutePublisher.h" +#include "RealtimeRenderPermit.h" #include #include #include #include #include +#include #include #include @@ -18,9 +20,25 @@ // Never run both renderers or sum their outputs. No browser-only LIVE status. namespace armix::mixer { class DynamicNativeSessionPublisher final { +public: + // Control-owned native FX lifetime travels IN the same accepted PCM + // snapshot. JUCE types stay outside this portable DSP publisher. + struct FxPlan final { + std::shared_ptr owner; // CONTROL-only copy/destruction + void* context=nullptr; // unchanged owner.get(), RT raw pointer + void (*render)(void*,ChannelId,float*,float*,int) noexcept=nullptr; + std::uint64_t deviceEpoch=0,graphRevision=0; + bool valid() const noexcept { + return (!owner&&!context&&!render&&!deviceEpoch&&!graphRevision) || + (owner&&context==owner.get()&&render&& + deviceEpoch>0&&graphRevision>0); + } + }; +private: struct Prepared final { DynamicPreparedMixerBlock graph; DynamicConsoleRoutingView routing; + FxPlan fx; // SAME lifetime and revision as native PCM graph int physicalInputs=0; bool monitor=false; }; @@ -49,8 +67,14 @@ class DynamicNativeSessionPublisher final { std::uint64_t expectedRevision, std::uint64_t proposedDeviceEpoch, std::uint64_t activeDeviceEpoch, - bool allOutputsDisarmed) { + bool allOutputsDisarmed, + FxPlan fx={},bool verifiedInternalWireOnly=false) { CommitResult report;report.revision=publisher_.lastRevision(); + if(!fx.valid() || + (fx.owner && (fx.deviceEpoch!=proposedDeviceEpoch || + fx.graphRevision!=expectedRevision+1))) { + report.fault=Fault::invalidCandidate;return report; + } if(proposedDeviceEpoch==0 || proposedDeviceEpoch!=activeDeviceEpoch) { report.fault=Fault::staleDevice;return report; @@ -59,7 +83,9 @@ class DynamicNativeSessionPublisher final { expectedRevision==std::numeric_limits::max()) { report.fault=Fault::staleRevision;return report; } - if(!allOutputsDisarmed) { + // Only the canonical native WIRE owner may attest unchanged + // physical patch / device epoch. Other structural edits disarm. + if(!allOutputsDisarmed && !verifiedInternalWireOnly) { report.fault=Fault::outputArmed;return report; } auto next=std::make_unique(); @@ -76,6 +102,7 @@ class DynamicNativeSessionPublisher final { report.fault=Fault::invalidGraph;return report; } prepared->physicalInputs=request.physicalInputs; + prepared->fx=std::move(fx); // one accepted control-plane publication prepared->monitor=std::any_of(roster.channels().begin(), roster.channels().end(),[](const ChannelStripDefinition& row) { return row.role==ChannelRole::monitor; @@ -106,7 +133,9 @@ class DynamicNativeSessionPublisher final { bool render(std::uint64_t deviceEpoch,const float* const* physical, int physicalCount,float* mainL,float* mainR,int frames, bool outputMuted,Fx&& effect, - float* monitorL=nullptr,float* monitorR=nullptr) noexcept { + float* monitorL=nullptr,float* monitorR=nullptr, + std::span channelPeaksL={}, + std::span channelPeaksR={}) noexcept { static_assert(std::is_nothrow_invocable_v, "Realtime VST dispatch must be noexcept"); const auto clearOutputs=[&]() noexcept { @@ -140,13 +169,23 @@ class DynamicNativeSessionPublisher final { } // A single callback producer owns the prepared scratch. In case a // broken backend calls simultaneously, fail closed rather than race. - if(rendering_.test_and_set(std::memory_order_acquire)) { + armix::rt::RealtimeRenderPermit exclusive{rendering_}; + if(!exclusive) { clearOutputs();return false; } + // Prepared FX takes precedence over the legacy external callback. + // NEVER invoke both: that would double-compress or double-reverb. + // Snapshot ownership pins the M4 instance throughout this callback; + // only control-thread retirement releases the shared owner. + const auto dispatch=[&](ChannelId id,float* l,float* r,int n) noexcept { + const auto& acceptedFx=snap->prepared->fx; + if(acceptedFx.render) + acceptedFx.render(acceptedFx.context,id,l,r,n); + else effect(id,l,r,n); + }; const bool ok=snap->prepared->graph.process( physical,physicalCount,mainL,mainR,frames, - std::forward(effect),monitorL,monitorR); - rendering_.clear(std::memory_order_release); + dispatch,monitorL,monitorR,channelPeaksL,channelPeaksR); if(!ok)clearOutputs(); return ok; } @@ -163,6 +202,13 @@ class DynamicNativeSessionPublisher final { // M3C realtime parameters on the accepted ChannelId graph ONLY. // Caller must propagate the real device epoch and native ACK revision. // Rejected/stale edits leave the last accepted PCM unchanged. + bool setPhysicalSource(std::uint64_t epoch,std::uint64_t revision, + ChannelId id,int inputL,int inputR,bool stereo) noexcept { + return publisher_.updateActiveControl(epoch,revision, + [&](Prepared& active) noexcept { + return active.graph.setPhysicalSource(id,inputL,inputR,stereo); + }); + } bool setChannelMix(std::uint64_t epoch,std::uint64_t revision, ChannelId id,float gain,float pan) noexcept { return publisher_.updateActiveControl(epoch,revision, @@ -170,6 +216,13 @@ class DynamicNativeSessionPublisher final { return active.graph.setChannelMix(id,gain,pan); }); } + bool setChannelMuteSolo(std::uint64_t epoch,std::uint64_t revision, + ChannelId id,bool mute,bool solo) noexcept { + return publisher_.updateActiveControl(epoch,revision, + [&](Prepared& active) noexcept { + return active.graph.setChannelMuteSolo(id,mute,solo); + }); + } bool setParallelSendGain(std::uint64_t epoch,std::uint64_t revision, ChannelId source,ChannelId destination, bool preFader,float gain) noexcept { diff --git a/engine/core/DynamicPreparedMixerBlock.h b/engine/core/DynamicPreparedMixerBlock.h index 9f02c9834..e9365f83a 100644 --- a/engine/core/DynamicPreparedMixerBlock.h +++ b/engine/core/DynamicPreparedMixerBlock.h @@ -1,9 +1,10 @@ // SPDX-License-Identifier: AGPL-3.0-only #pragma once #include "DynamicChannelRoster.h" +#include "RealtimeSlew64.h" +#include "RealtimeStereoControlWord.h" #include #include -#include #include #include #include @@ -58,6 +59,7 @@ class DynamicPreparedMixerBlock final { ChannelRole role=ChannelRole::input; int inputL=-1,inputR=-1; bool inputStereo=false,enabled=false; + bool monoPan=false; // mono source/processing, independent of VST rack width float gainL=1.f,gainR=1.f; std::size_t first=0,last=0,slot=0; }; @@ -67,26 +69,45 @@ class DynamicPreparedMixerBlock final { // between separate L and R loads. A torn stereo target can cause a // transient image/level jump even with sample ramps. 64-bit atomics are // required lock-free: callback must never invoke a hidden mutex. - struct StereoGainPair final { - float left=1.f,right=1.f; + using Word=armix::dsp::RealtimeStereoControlWord; + struct StereoGainPair final {float left=1.f,right=1.f;}; + // True microphone mono uses equal-power PAN even when a stereo VST rack + // processes its duplicated L/R PCM. A stereo physical source uses + // balance PAN unless explicitly folded to mono processing. Computing + // the coefficient is CONTROL-only; the callback reads one atomic pair. + static StereoGainPair coefficients(bool monoPan,float gain,float pan) noexcept { + if(monoPan) + return {gain*std::sqrt(.5f*(1.f-pan)), + gain*std::sqrt(.5f*(1.f+pan))}; + return {gain*(pan>0.f?1.f-pan:1.f), + gain*(pan<0.f?1.f+pan:1.f)}; + } + struct ChannelTarget final { + std::atomic state{Word::encode(1.f,1.f,false,false)}; + armix::dsp::RealtimeSlew64 appliedL{},appliedR{},gate{}; // AUDIO only }; - static constexpr std::uint64_t packGainPair(float left,float right) noexcept { - return (static_cast(std::bit_cast(right))<<32) | - std::bit_cast(left); + // CONTROL only packs already verified callback-ordinal physical pin pairs. + // 0xFFFF means missing right input for mono, never an active physical pin. + static constexpr std::uint32_t packPhysical(int left,int right) noexcept { + return static_cast(left) | + (static_cast(right<0?0xffff:right)<<16); } - static constexpr StereoGainPair unpackGainPair(std::uint64_t both) noexcept { - return {std::bit_cast(static_cast(both)), - std::bit_cast(static_cast(both>>32))}; + static constexpr int physicalLeft(std::uint32_t word) noexcept { + return static_cast(word&0xffffu); } - struct ChannelTarget final { - static_assert(std::atomic::is_always_lock_free, - "Realtime stereo mixer requires lock-free 64-bit atomic targets"); - std::atomic both{packGainPair(1.f,1.f)}; - float appliedL=1.f,appliedR=1.f; // audio thread only + static constexpr int physicalRight(std::uint32_t word) noexcept { + const auto right=static_cast((word>>16)&0xffffu); + return right==0xffff?-1:right; + } + struct SourceFade final { + std::uint32_t current=0,next=0; + int remaining=0; // AUDIO only; pending CONTROL target is one atomic }; struct SendTarget final { + static_assert(std::atomic::is_always_lock_free, + "Realtime SEND must never enter a hidden blocking atomic path"); std::atomic gain{1.f}; - float applied=1.f; + armix::dsp::RealtimeSlew64 applied{}; }; static constexpr std::size_t notScheduled=std::numeric_limits::max(); public: @@ -105,17 +126,58 @@ class DynamicPreparedMixerBlock final { bool setChannelMix(ChannelId id,float gain,float pan) noexcept { if(!id.value || !std::isfinite(gain) || gain<0.f || gain>4.f || !std::isfinite(pan) || pan< -1.f || pan>1.f)return false; - for(std::size_t i=0;i0.f?1.f-pan:1.f); - const float right=mono?gain*std::sqrt(.5f*(1.f+pan)): - gain*(pan<0.f?1.f+pan:1.f); - channelTargets_[i].both.store( - packGainPair(left,right),std::memory_order_release); - return true; - } - return false; + // Reuse the already-built ChannelId lookup; no O(N) scan on every + // rapid GUI fader tick, no callback hash lookup and no new allocation. + const auto found=controlIndex_.find(id.value); + if(found==controlIndex_.end())return false; + const auto i=found->second; + const auto gains=coefficients(lanes_[i].monoPan,gain,pan); + auto& target=channelTargets_[i]; + const auto old=Word::decode(target.state.load(std::memory_order_relaxed)); + // Serialized native CONTROL writer: keep mute/solo atomically paired + // with this fader/PAN target, never four separately loaded controls. + target.state.store(Word::encode(gains.left,gains.right,old.mute,old.solo), + std::memory_order_release); + return true; + } + // Canonical physical-pin validation shared by structural preflight and + // accepted realtime SOURCE changes. Never normalize an invalid draft + // into an apparently successful ACK by replacing it with old pins. + static bool validPhysicalPatch(int physicalInputs,int inputL,int inputR, + bool stereo) noexcept { + return physicalInputs>=0 && physicalInputs<=256 && + inputL>=0 && inputL=0 && inputRsecond]; + if(lane.role!=ChannelRole::input || lane.inputL<0 || + lane.inputStereo!=stereo)return false; // format requires APPLY + sourceTargets_[it->second].store(packPhysical(inputL,inputR), + std::memory_order_release); + return true; + } + bool setChannelMuteSolo(ChannelId id,bool mute,bool solo) noexcept { + if(!id.value)return false; + const auto it=controlIndex_.find(id.value); + if(it==controlIndex_.end())return false; + auto& target=channelTargets_[it->second]; + const auto old=Word::decode(target.state.load(std::memory_order_relaxed)); + target.state.store(Word::encode(old.left,old.right,mute,solo), + std::memory_order_release); + return true; } // Change gain ONLY on an existing parallel send (PRE or POST). // Exclusive primary OUT and source/destination edits stay structural. @@ -123,22 +185,24 @@ class DynamicPreparedMixerBlock final { bool preFader,float gain) noexcept { if(!source.value || !destination.value || !std::isfinite(gain) || gain<0.f || gain>4.f)return false; - for(const auto& lane:lanes_)if(lane.id==source) { - for(std::size_t e=lane.first;esecond]; + // Only that source's prepared CSR outgoing edges are examined. + // The public GUI can address arbitrary stable ChannelIds regardless + // of visual bank, strip position or hidden channels. + for(std::size_t e=lane.first;e byId; @@ -188,14 +253,8 @@ class DynamicPreparedMixerBlock final { } Lane lane; lane.id=row.id;lane.format=row.format;lane.role=row.role; - lane.enabled=!row.mute; - if(row.format==ProcessingFormat::mono) { - lane.gainL=row.faderLinear*std::sqrt(0.5f*(1.f-row.pan)); - lane.gainR=row.faderLinear*std::sqrt(0.5f*(1.f+row.pan)); - }else{ - lane.gainL=row.faderLinear*(row.pan>0.f?1.f-row.pan:1.f); - lane.gainR=row.faderLinear*(row.pan<0.f?1.f+row.pan:1.f); - } + lane.enabled=true; // keep prepared FX/tail alive across MUTE/SOLO + lane.monoPan=row.format==ProcessingFormat::mono; next.lanes_.push_back(lane); } if(main==notScheduled){error.fault=DynamicGraphFault::noMaster;return false;} @@ -207,14 +266,21 @@ class DynamicPreparedMixerBlock final { if(it==byId.end()){error={DynamicGraphFault::missingSource,patch.id};return false;} auto& lane=next.lanes_[it->second]; if(lane.role!=ChannelRole::input || lane.inputL!=-1 || - patch.inputL<0 || patch.inputL>=req.physicalInputs || - (patch.stereo && (patch.inputR<0 || - patch.inputR>=req.physicalInputs || patch.inputL==patch.inputR)) || - (!patch.stereo && patch.inputR!=-1)) { + !validPhysicalPatch(req.physicalInputs,patch.inputL, + patch.inputR,patch.stereo)) { error={DynamicGraphFault::invalidSource,patch.id};return false; } lane.inputL=patch.inputL;lane.inputR=patch.inputR; lane.inputStereo=patch.stereo; + // The channel SOURCE and the INSERT PROCESSING FORMAT are + // independent. Mono mic -> stereo VST still retains mono PAN. + if(!patch.stereo)lane.monoPan=true; + } + for(std::size_t i=0;i(solos[i]||forward[i]); } + next.initialAudible_.resize(rows.size()); for(std::size_t i=0;i( + !rows[i].mute && (!anySolo||solos[i]!=0)); + next.topologicalOrder_=order; // control-prepared, never RT sorted // One immutable render schedule serves BOTH logical output sinks. // Active monitor-only channels must not vanish merely because they @@ -352,20 +420,38 @@ class DynamicPreparedMixerBlock final { std::size_t slot=0; for(auto i:next.renderOrder_)next.lanes_[i].slot=slot++; next.scratch_.assign(active*2*frame,0.f); + next.sourceTargets_=std::make_unique[]>(rows.size()); + next.sourceFades_=std::make_unique(rows.size()); + for(std::size_t i=0;i(rows.size()); + next.blockTargets_.resize(rows.size()); + next.soloAncestors_.assign(rows.size(),0); + next.soloDescendants_.assign(rows.size(),0); for(std::size_t i=0;i(next.edges_.size()); for(std::size_t e=0;e bool process(const float* const* physical,int physicalCount, float* outputL,float* outputR,int frames,Fx&& processFx, - float* monitorL=nullptr,float* monitorR=nullptr) noexcept { + float* monitorL=nullptr,float* monitorR=nullptr, + std::span channelPeaksL={}, + std::span channelPeaksR={}) noexcept { if(frames<=0 || !outputL || !outputR)return false; + // The physical 10CH/4AUX callback requests only the stable + // legacy prefix of an expanded ChannelId roster. Dynamic extra + // GROUP/FX RETURN lanes still process PCM, but need no JS meter + // until a native meter UI consumer is explicitly subscribed. + // Never allocate proportional-to-roster arrays on AUDIO. + if(channelPeaksL.size()!=channelPeaksR.size()) + return false; + if(!channelPeaksL.empty()) { + std::fill_n(channelPeaksL.data(),channelPeaksL.size(),0.f); + std::fill_n(channelPeaksR.data(),channelPeaksR.size(),0.f); + } if(outputL==outputR || (monitorL==nullptr)!=(monitorR==nullptr) || (monitor_!=notScheduled && !monitorL) || @@ -395,6 +494,35 @@ class DynamicPreparedMixerBlock final { return false; } const auto block=static_cast(capacity_); + // One canonical 64-bit target per logical channel, read once/block. + // Realtime SOLO closure reuses CONTROL-prepared order and CSR edges. + // No allocation, mutex, VST3 lease/reference, sorting or worker on RT. + bool anySolo=false; + for(std::size_t i=0;i(state.solo&&!state.mute); + soloAncestors_[i]=root;soloDescendants_[i]=root; + anySolo|=root!=0; + } + if(anySolo) { + for(auto it=topologicalOrder_.rbegin();it!=topologicalOrder_.rend();++it){ + const auto i=*it; + for(std::size_t e=lanes_[i].first;e=0 && physical && lane.inputL=0 && physical) { + auto& fade=sourceFades_[i]; + const auto desired=sourceTargets_[i].load(std::memory_order_acquire); + if(fade.remaining==0 && desired!=fade.current) { + fade.next=desired;fade.remaining=armix::dsp::RealtimeSlew64::samples; + } + // Resolve each verified physical pair ONCE per block; the + // inner sample loop only blends already-addressed PCM. + const auto resolve=[&](std::uint32_t pair,int side) noexcept + ->const float* { + const int a=physicalLeft(pair),b=physicalRight(pair); + if(a<0||a>=physicalCount||!physical[a])return nullptr; + if(lane.inputStereo){ + if(b<0||b>=physicalCount||!physical[b])return nullptr; + return side==0?physical[a]:physical[b]; + } + return physical[a]; + }; + const float* oldL=resolve(fade.current,0); + const float* oldR=resolve(fade.current,1); + const float* newL=fade.remaining?resolve(fade.next,0):oldL; + const float* newR=fade.remaining?resolve(fade.next,1):oldR; + if(fade.remaining==0) { + if(oldL&&oldR) + for(int f=0;f(fade.remaining-1)* + (1.f/static_cast(armix::dsp::RealtimeSlew64::samples)); + const float beforeL=oldL?oldL[f]:0.f; + const float beforeR=oldR?oldR[f]:0.f; + const float afterL=newL?newL[f]:0.f; + const float afterR=newR?newR[f]:0.f; + l[f]+=beforeL+(afterL-beforeL)*alpha; + r[f]+=beforeR+(afterR-beforeR)*alpha; + --fade.remaining; + if(fade.remaining==0){ + fade.current=fade.next; + // New CONTROL requests are consumed next block; + // never change the source mid-sample. + oldL=newL;oldR=newR; + for(int k=f+1;k(ramp); - float applied=target.applied; + // Coalesced, callback-continuous 64 SAMPLE slew. A 4-frame + // ASIO callback advances only 4/64 of the requested change. + target.applied.retarget(goal); for(int f=0;f(ramp); - const float stepR=(goalR-controls.appliedR)/static_cast(ramp); - float currentL=controls.appliedL,currentR=controls.appliedR; + // Left and right use ONE atomically read stereo goal. Ramp state + // survives variable hardware callback sizes and gesture reversals. + controls.appliedL.retarget(goalL); + controls.appliedR.retarget(goalR); + float observedL=0.f,observedR=0.f; for(int f=0;f(ramp); - float applied=target.applied; + // Coalesced, callback-continuous 64 SAMPLE slew. A 4-frame + // ASIO callback advances only 4/64 of the requested change. + target.applied.retarget(goal); for(int f=0;f lanes_; + std::unordered_map controlIndex_; // CONTROL only std::vector edges_; - std::vector renderOrder_; + std::vector renderOrder_,topologicalOrder_; + std::vector initialAudible_,soloAncestors_,soloDescendants_; + std::vector blockTargets_; // all allocated before RT std::vector scratch_; std::unique_ptr channelTargets_; + std::unique_ptr[]> sourceTargets_; + std::unique_ptr sourceFades_; std::unique_ptr sendTargets_; std::size_t main_=notScheduled,monitor_=notScheduled; bool mainMonoAfterFx_=false; - int capacity_=0; + int capacity_=0,physicalInputs_=0; }; } // namespace armix::mixer diff --git a/engine/core/LegacyLiveGraphMigration.h b/engine/core/LegacyLiveGraphMigration.h index 2358e6724..54a06c3cc 100644 --- a/engine/core/LegacyLiveGraphMigration.h +++ b/engine/core/LegacyLiveGraphMigration.h @@ -44,6 +44,9 @@ struct LegacyMigratedGraph final { 32u*1024u*1024u,8u,static_cast(maxChannelSends+maxAuxSends+2)}}; DynamicPreparedMixerBlock pcm{}; LegacyChannelIds ids{}; + // Exact verified physical SOURCE request, preserved for a single native + // admission. Never reconstruct callback port ordinals from a GUI draft. + DynamicGraphRequest request{}; std::uint64_t revision=0; }; @@ -187,6 +190,7 @@ class LegacyGraphMigration final { next.pcm,error.dynamic)){ error.fault=LegacyMigrationFault::invalidDynamicGraph;return false; } + next.request=std::move(request); next.revision=next.roster.revision(); destination=std::move(next); // publish only after caller's native MUTE/epoch ACK return true; diff --git a/engine/core/LiveChannelFxGraph.h b/engine/core/LiveChannelFxGraph.h index fff61df01..281b172f9 100644 --- a/engine/core/LiveChannelFxGraph.h +++ b/engine/core/LiveChannelFxGraph.h @@ -159,12 +159,24 @@ class LiveChannelFxGraph final { for(float v:gains)if(!std::isfinite(v)||v<0.f||v>1.f)return false; monitorLeft_=left;monitorRight_=right; monitorGains_=gains;monitorEnabled_=true; + for(int i=0;iprepareMonitorGains(gains); // unpublished graph/control only return true; } bool monitorEnabled() const noexcept{return monitorEnabled_;} int monitorOutputLeft() const noexcept{return monitorLeft_;} int monitorOutputRight() const noexcept{return monitorRight_;} const std::array& monitorGains() const noexcept{return monitorGains_;} + // Existing verified independent MONITOR source lane. Only the scalar + // changes; MAIN stays untouched, no graph rebuild or vendor lifecycle. + bool setMonitorSendGain(int lane,float gain) noexcept { + if(!monitorEnabled_||lane<0||lane>=fxSlots|| + !std::isfinite(gain)||gain<0.f||gain>1.f)return false; + monitorGainTargets_[lane].store(gain,std::memory_order_release); + monitorGains_[lane]=gain; // CONTROL-only Show/status readback + return true; + } bool switchPhysicalSource(int strip,SourceMode mode,int left,int right) noexcept { return block_&&block_->setPhysicalSource(strip,mode,left,right); } @@ -173,9 +185,11 @@ class LiveChannelFxGraph final { bool setAuxBusGain(int bus,float gain) noexcept { return block_&&block_->setAuxBusGain(bus,gain); } + bool setAuxSendGain(int source,int bus,SendTap tap,float gain) noexcept { + return block_ && block_->setAuxSendGain(source,bus,tap,gain); + } bool setAuxSendGain(int source,int bus,float gain) noexcept { - return block_ && block_->setAuxSendGain( - source,bus,SendTap::postFader,gain); + return setAuxSendGain(source,bus,SendTap::postFader,gain); } int activeInserts() const noexcept{return activeInserts_;} bool setStripControl(int channel,float gain,float pan, @@ -292,7 +306,8 @@ class LiveChannelFxGraph final { if(monitorEnabled_ && (!monitorL||!monitorR))return false; return block_->process(physical,inputs,left,right,frames,channelFx,levels, &controls_,monitorEnabled_?&monitorGains_:nullptr, - monitorL,monitorR); + monitorL,monitorR, + monitorEnabled_?&monitorGainTargets_:nullptr); } private: @@ -305,6 +320,7 @@ class LiveChannelFxGraph final { int mainOutputLeft_=0,mainOutputRight_=1; int monitorLeft_=-1,monitorRight_=-1; bool monitorEnabled_=false; - std::array monitorGains_{}; + std::array monitorGains_{}; // control-only accepted readback + std::array,fxSlots> monitorGainTargets_{}; // RT read }; } // namespace armix::mixer diff --git a/engine/core/NativeRenderAuthority.h b/engine/core/NativeRenderAuthority.h new file mode 100644 index 000000000..03d81b64b --- /dev/null +++ b/engine/core/NativeRenderAuthority.h @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include + +// Production render ownership, never an audio engine or a second callback. +// The approved GUI can project ONE native engine. Until the full ChannelId +// VST/editor/Show cutover is admitted, only the existing M4 route owns PCM. +// The legacy stereo path is diagnostic-only, never a hidden fallback. +namespace armix::mixer { +enum class NativeRenderOwner : std::uint8_t { + failSilentUnpatched, + acceptedM4Session, + isolatedDiagnostic +}; + +struct NativeRenderAuthority final { + static constexpr NativeRenderOwner select( + bool normalAudio, bool m4SessionActive) noexcept { + // A verified accepted M4 route always owns the callback: a diagnostic + // mode must never start processing a second stereo FX chain over it. + if(m4SessionActive)return NativeRenderOwner::acceptedM4Session; + if(normalAudio)return NativeRenderOwner::failSilentUnpatched; + return NativeRenderOwner::isolatedDiagnostic; + } + static constexpr bool isProduction(NativeRenderOwner owner) noexcept { + return owner==NativeRenderOwner::acceptedM4Session; + } + static constexpr bool mayRunDiagnostic(NativeRenderOwner owner) noexcept { + return owner==NativeRenderOwner::isolatedDiagnostic; + } +}; +static_assert(NativeRenderAuthority::select(true,false)== + NativeRenderOwner::failSilentUnpatched); +static_assert(NativeRenderAuthority::select(true,true)== + NativeRenderOwner::acceptedM4Session); +static_assert(NativeRenderAuthority::select(false,true)== + NativeRenderOwner::acceptedM4Session); +static_assert(NativeRenderAuthority::select(false,false)== + NativeRenderOwner::isolatedDiagnostic); +} // namespace armix::mixer diff --git a/engine/core/PreparedMixerBlock.h b/engine/core/PreparedMixerBlock.h index 7d58a411f..7f887810b 100644 --- a/engine/core/PreparedMixerBlock.h +++ b/engine/core/PreparedMixerBlock.h @@ -2,6 +2,8 @@ #pragma once #include "ChannelSendPlan.h" #include "AuxBusPlan.h" +#include "RealtimeSlew64.h" +#include "RealtimeStereoControlWord.h" #include #include #include @@ -124,12 +126,25 @@ struct PreparedRenderGraph final { // once per block and interpolates into fixed strip scratch buffers. The // immutable topology (DAG/physical ports/FX ownership) is never rebuilt for // ordinary fader, pan, MUTE, or SOLO changes. +// One packed uint64 captures both stereo coefficients AND MUTE/SOLO in one +// coherent block-boundary atomic load. A WebView gesture can never publish +// the left level from edit N and right/mute/solo from edit N+1. +// Two 31-bit fixed-point gains cover 0..4 with better-than-float readback +// precision and leave 2 bits for MUTE/SOLO. All quantization is CONTROL-only. class RealtimeStripControls final { public: - struct Target { - std::atomic left{1.f},right{1.f}; - std::atomic mute{false},solo{false}; - }; + using Word=armix::dsp::RealtimeStereoControlWord; + static constexpr std::uint64_t gainMask=Word::gainMask; + static constexpr std::uint64_t mutedBit=Word::mutedBit; + static constexpr std::uint64_t soloBit=Word::soloBit; + static constexpr std::uint64_t unity=Word::unity; + using Snapshot=Word::Snapshot; + struct Target final {std::atomic state{unity|(unity<<31)};}; + static std::uint64_t quantize(float v) noexcept {return Word::quantize(v);} + static std::uint64_t encode(float l,float r,bool mute,bool solo) noexcept { + return Word::encode(l,r,mute,solo); + } + static Snapshot decode(std::uint64_t v) noexcept {return Word::decode(v);} bool set(int strip,float gain,float pan,bool mono,bool mute,bool solo) noexcept { if(strip<0||strip>=stripCount||!std::isfinite(gain)||gain<0.f||gain>4.f|| !std::isfinite(pan)||pan< -1.f||pan>1.f)return false; @@ -137,18 +152,22 @@ class RealtimeStripControls final { gain*(pan>0.f?1.f-pan:1.f); const float right=mono?gain*std::sqrt(0.5f*(1.f+pan)): gain*(pan<0.f?1.f+pan:1.f); - auto& c=targets_[strip]; - c.left.store(left,std::memory_order_relaxed); - c.right.store(right,std::memory_order_relaxed); - c.mute.store(mute,std::memory_order_relaxed); - c.solo.store(solo,std::memory_order_relaxed); + targets_[strip].state.store(encode(left,right,mute,solo), + std::memory_order_release); return true; } + // Called on the unpublished graph's CONTROL constructor. Preserve flags + // for safe reuse, but ship a single coherent stereo snapshot. void setPreparedCoefficients(int strip,float left,float right) noexcept { - targets_[strip].left.store(left,std::memory_order_relaxed); - targets_[strip].right.store(right,std::memory_order_relaxed); + if(strip<0||strip>=stripCount)return; + const auto old=targets_[strip].state.load(std::memory_order_relaxed); + targets_[strip].state.store( + encode(left,right,(old&mutedBit)!=0,(old&soloBit)!=0), + std::memory_order_relaxed); + } + Snapshot read(int strip) const noexcept { + return decode(targets_[strip].state.load(std::memory_order_acquire)); } - const Target& at(int strip) const noexcept{return targets_[strip];} private: std::array targets_{}; }; @@ -190,11 +209,14 @@ class PreparedMixerBlock final { const float v=plan_.aux.edges[e].initialGain; auxTarget_[e].store(v,std::memory_order_relaxed); auxApplied_[e]=v; + auxGoal_[e]=v; + auxRampRemaining_[e]=0; } for(int b=0;b=stripCount||bus<0||bus>=auxBusCount|| - tap!=SendTap::postFader||!std::isfinite(gain)||gain<0.f||gain>1.f) + (tap!=SendTap::preFader&&tap!=SendTap::postFader)|| + !std::isfinite(gain)||gain<0.f||gain>1.f) return false; for(int e=plan_.aux.offset[source];e4.f)return false; auxBusTarget_[bus].store(gain,std::memory_order_release); + auxBusAutomationActive_.store(true,std::memory_order_release); return true; } float auxBusGain(int bus) const noexcept { @@ -271,6 +298,18 @@ class PreparedMixerBlock final { return -1.f; } + // CONTROL only, before publishing a MONITOR-enabled prepared graph. + // Initial send levels start at their approved values, not an audible + // ramp from zero when a device first arms its independent MONITOR bus. + void prepareMonitorGains( + const std::array& gains) noexcept { + for(int i=0;i* monitorGains=nullptr, - float* monitorL=nullptr,float* monitorR=nullptr) noexcept { + float* monitorL=nullptr,float* monitorR=nullptr, + const std::array,stripCount+auxBusCount>* + liveMonitorGains=nullptr) noexcept { static_assert(std::is_nothrow_invocable_v, "DSP hook must be noexcept and realtime bounded"); if (observed) *observed={}; @@ -302,6 +343,19 @@ class PreparedMixerBlock final { if(monitorR && monitorR!=monitorL)std::fill_n(monitorR,frames,0.f); return false; } + // Also support direct PreparedMixerBlock users (no JUCE FxGraph + // wrapper): the first real MONITOR render starts at its approved + // levels, never with a fake 64-frame fade from an unpatched zero. + if(monitorL && !monitorPrimed_) { + for(int i=0;i currentControls{}; bool anySolo=false; - if(live)for(int strip=0;stripat(strip).solo.load(std::memory_order_relaxed) && - !live->at(strip).mute.load(std::memory_order_relaxed); + if(live)for(int strip=0;stripread(strip); + anySolo |= state.solo && !state.mute; + } for(int k=0;kat(strip); - routeAudible=!target.mute.load(std::memory_order_relaxed); + const auto& target=currentControls[strip]; + routeAudible=!target.mute; if(routeAudible&&anySolo) { routeAudible=false; for(int j=0;jat(j); - if(s.solo.load(std::memory_order_relaxed) && - !s.mute.load(std::memory_order_relaxed) && + const auto& s=currentControls[j]; + if(s.solo && !s.mute && (j==strip||graph.sends.upstreamOf(strip,j)|| graph.sends.upstreamOf(j,strip))) { routeAudible=true;break; } } } - gl=target.left.load(std::memory_order_relaxed); - gr=target.right.load(std::memory_order_relaxed); + gl=target.left; + gr=target.right; // A MUTE or SOLO transition must also silence PRE sends. // Smooth the pre-send source gate over <=64 samples; it does // not create/restart FX, drivers, nodes or send topology. const float targetGate=routeAudible?1.f:0.f; if(!rampPrimed_[strip]) { - preGate_[strip]=targetGate; - lastGainL_[strip]=gl; - lastGainR_[strip]=gr; + preSlew_[strip].reset(targetGate); + gainSlewL_[strip].reset(gl); + gainSlewR_[strip].reset(gr); rampPrimed_[strip]=true; } - const int ramp=std::min(frames,64); - const float dGate=(targetGate-preGate_[strip])/ramp; - float gate=preGate_[strip]; + // Same canonical 64-SAMPLE slew as ChannelId. No division in + // the actual audio-sample loop, even at 4-frame ASIO quantum. + auto& gate=preSlew_[strip]; + gate.retarget(targetGate); for(int f=0;f0.f) { - monitorBusL[f]+=l[f]*monitorGain; - monitorBusR[f]+=r[f]*monitorGain; + l[f]*=slewL.next(); + r[f]*=slewR.next(); + if(monitorBusL) { + const float gain=nextMonitorGain(strip); + monitorBusL[f]+=l[f]*gain; + monitorBusR[f]+=r[f]*gain; } const float sampleL=std::abs(l[f]), sampleR=std::abs(r[f]); peakL=std::max(peakL,sampleL); @@ -453,13 +527,13 @@ class PreparedMixerBlock final { masterL_[f]+=l[f];masterR_[f]+=r[f]; } } - lastGainL_[strip]=gl;lastGainR_[strip]=gr; }else for(int f=0;f0.f) { - monitorBusL[f]+=l[f]*monitorGain; - monitorBusR[f]+=r[f]*monitorGain; + if(monitorBusL) { + const float gain=nextMonitorGain(strip); + monitorBusL[f]+=l[f]*gain; + monitorBusR[f]+=r[f]*gain; } const float sampleL=std::abs(l[f]), sampleR=std::abs(r[f]); peakL=std::max(peakL,sampleL); @@ -477,7 +551,13 @@ class PreparedMixerBlock final { } graph.sends.dispatch(strip,SendTap::postFader,l,r, left_.data(),right_.data(),frames); - if(live)dispatchLiveAux(strip,SendTap::postFader,l,r,frames); + // Before operator automation, preserve the original + // precompiled immutable AUX dispatch (fast path, no atomics). + // Once the message thread publishes a changed send target, + // the SAME callback switches to one live PRE/POST processor + // which follows 64-sample gains across varying block sizes. + if(auxAutomationActive_.load(std::memory_order_acquire)) + dispatchLiveAux(strip,SendTap::postFader,l,r,frames); else graph.aux.dispatch(strip,SendTap::postFader,l,r, auxLeft_.data(),auxRight_.data(),frames); } @@ -490,19 +570,46 @@ class PreparedMixerBlock final { float* const l=auxLeft_[b],* const r=auxRight_[b]; processFx(stripCount+b,l,r,frames); float peak=0.f; - const float monitorGain=monitorL?(*monitorGains)[stripCount+b]:0.f; - const float target=live + const int monitorLane=stripCount+b; + if(monitorBusL) { + const float next=liveMonitorGains + ?(*liveMonitorGains)[monitorLane].load(std::memory_order_acquire) + :(*monitorGains)[monitorLane]; + if(next!=monitorGoal_[monitorLane]) { + monitorGoal_[monitorLane]=next; + monitorRemaining_[monitorLane]=64; + } + } + // Original zero-automation fast path remains one scalar + // multiplication; only a real operator AUX fader edit enables + // the sample-continuous 64-frame de-zipper across 4/8/16-frame + // callbacks. The fader scales the return AFTER hosted AUX VST3 + // for both MAIN and independent MONITOR, not source dry PCM. + // AUX automation is independent of channel fader/MUTE control. + // A caller may automate AUX sends/returns without supplying a + // RealtimeStripControls bank; keep one canonical DSP target plane. + const bool automated=auxBusAutomationActive_.load( + std::memory_order_acquire); + const float target=automated ?auxBusTarget_[b].load(std::memory_order_acquire):bus.gain; - const float start=live?auxBusApplied_[b]:bus.gain; - const int ramp=std::min(frames,64); - const float step=(target-start)/static_cast(ramp); - float current=start; + if(automated && target!=auxBusGoal_[b]) { + auxBusGoal_[b]=target; + auxBusRemaining_[b]=64; + } + float current=automated?auxBusApplied_[b]:bus.gain; + int remaining=automated?auxBusRemaining_[b]:0; for(int f=0;f0) { + current+=(target-current)/static_cast(remaining); + --remaining; + } else current=target; const float vl=l[f]*current,vr=r[f]*current; - if(!bus.mute && monitorGain>0.f) { - monitorBusL[f]+=vl*monitorGain; - monitorBusR[f]+=vr*monitorGain; + if(monitorBusL) { + const float gain=nextMonitorGain(monitorLane); + if(!bus.mute) { + monitorBusL[f]+=vl*gain; + monitorBusR[f]+=vr*gain; + } } peak=std::max(peak,std::max(std::abs(vl),std::abs(vr))); if(bus.toMaster && !bus.mute){ @@ -510,7 +617,10 @@ class PreparedMixerBlock final { masterR_[f]+=vr; } } - if(live)auxBusApplied_[b]=target; + if(automated) { + auxBusApplied_[b]=remaining==0?target:current; + auxBusRemaining_[b]=remaining; + } if(observed)observed->auxPeak[b]=peak; } processFx(-1,masterL_,masterR_,frames); @@ -532,6 +642,18 @@ class PreparedMixerBlock final { return true; } private: + // Callback exclusive: monitor gain follows 64 sample steps regardless of + // 4/16/32/512-frame hardware buffers; no second effect render. + float nextMonitorGain(int lane) noexcept { + auto& applied=monitorApplied_[lane]; + auto& remaining=monitorRemaining_[lane]; + const float target=monitorGoal_[lane]; + if(remaining>0) { + applied+=(target-applied)/static_cast(remaining); + --remaining; + } else applied=target; + return applied; + } static constexpr std::uint32_t invalidSourcePair=0xffffffffu; static constexpr std::uint32_t packSourcePair(int left,int right) noexcept { return static_cast(left)| @@ -552,22 +674,31 @@ class PreparedMixerBlock final { if(edge.tap!=tap)continue; float* dl=auxLeft_[edge.bus],* dr=auxRight_[edge.bus]; if(!dl||!dr)continue; + // Preserve a 64-SAMPLE de-zipper across arbitrarily small / + // variable callbacks. PRE and POST use the same ramp; no + // frame-size-dependent jump, heap, lock, or graph recompilation. const float target=auxTarget_[e].load(std::memory_order_acquire); - const float start=auxApplied_[e]; - const int ramp=std::min(frames,64); - if(std::abs(target-start)<1.e-7f){ + if(target!=auxGoal_[e]) { + auxGoal_[e]=target; + auxRampRemaining_[e]=64; + } + float current=auxApplied_[e]; + int remaining=auxRampRemaining_[e]; + if(remaining==0) { const float gl=target*edge.leftPan,gr=target*edge.rightPan; for(int f=0;f(ramp); - float current=start; - for(int f=0;f0) { + current+=(target-current)/static_cast(remaining); + --remaining; + }else current=target; dl[f]+=l[f]*current*edge.leftPan; dr[f]+=r[f]*current*edge.rightPan; } } - auxApplied_[e]=target; + auxApplied_[e]=remaining==0?target:current; + auxRampRemaining_[e]=remaining; } } static bool validCapacity(int f) noexcept {return f>0 && f<=hardFrameLimit;} @@ -577,13 +708,24 @@ class PreparedMixerBlock final { std::array left_{}; std::array right_{}; std::array auxLeft_{},auxRight_{}; - std::array preGate_{},lastGainL_{},lastGainR_{}; + std::array preSlew_{}, + gainSlewL_{},gainSlewR_{}; // audio callback only, no heap std::array,stripCount> physicalTarget_{}; std::array physicalBlend_{}; + // OFF until any native SET_SEND_LEVEL. Audio callback reads only; + // control-thread publication is monotonic for this prepared graph. + std::atomic auxAutomationActive_{false}; std::array,maxAuxSends> auxTarget_{}; - std::array auxApplied_{}; // callback thread exclusive + std::array auxApplied_{},auxGoal_{}; // callback exclusive + std::array auxRampRemaining_{}; + std::array monitorApplied_{},monitorGoal_{}; + std::array monitorRemaining_{}; + bool monitorPrimed_=false; // sole audio producer except prepublish seeding std::array,auxBusCount> auxBusTarget_{}; - std::array auxBusApplied_{}; // callback thread exclusive + std::array auxBusApplied_{},auxBusGoal_{}; + std::array auxBusRemaining_{}; + std::atomic auxBusAutomationActive_{false}; + // State exclusively advanced in the single JUCE audio callback. std::array rampPrimed_{}; float* masterL_=nullptr; float* masterR_=nullptr; diff --git a/engine/core/RealtimeRenderPermit.h b/engine/core/RealtimeRenderPermit.h new file mode 100644 index 000000000..9eb141a1b --- /dev/null +++ b/engine/core/RealtimeRenderPermit.h @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include + +// One gate across the real installed M4 renderer and the future ChannelId +// publisher. If a misbehaving device/backend overlaps callbacks, do not +// concurrently write prepared scratch or process the same VST3 instance. +// Nonblocking: failed acquisition is SILENCE, never a spin, mutex or wait. +// RAII releases on every fail-closed return after entering the DSP block. +namespace armix::rt { +class RealtimeRenderPermit final { +public: + explicit RealtimeRenderPermit(std::atomic_flag& gate) noexcept + : gate_(gate), + entered_(!gate_.test_and_set(std::memory_order_acquire)) {} + RealtimeRenderPermit(const RealtimeRenderPermit&)=delete; + RealtimeRenderPermit& operator=(const RealtimeRenderPermit&)=delete; + ~RealtimeRenderPermit() noexcept { + if(entered_)gate_.clear(std::memory_order_release); + } + explicit operator bool() const noexcept {return entered_;} +private: + std::atomic_flag& gate_; + bool entered_; +}; +} // namespace armix::rt diff --git a/engine/core/RealtimeSlew64.h b/engine/core/RealtimeSlew64.h new file mode 100644 index 000000000..3e4e6fc2a --- /dev/null +++ b/engine/core/RealtimeSlew64.h @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +// One reusable fixed-duration DSP ramp for fader, pan and PRE/POST SEND. +// CONTROL coalesces to one latest atomic goal per callback; AUDIO owns +// current/remaining. No heap, lock, division or time API in the sample loop. +// A new gesture during a ramp starts at the *audibly applied* coefficient. +namespace armix::dsp { +struct RealtimeSlew64 final { + static constexpr int samples=64; + float current=1.f; + float goal=1.f; + float delta=0.f; + int remaining=0; + + void reset(float initial) noexcept { + current=goal=initial; + delta=0.f; + remaining=0; + } + void retarget(float requested) noexcept { + if(requested==goal)return; + goal=requested; + remaining=samples; + delta=(goal-current)*(1.f/static_cast(samples)); + } + float next() noexcept { + if(remaining>0) { + --remaining; + if(remaining==0)current=goal; // exact steady-state endpoint + else current+=delta; + } + return current; + } +}; +} // namespace armix::dsp diff --git a/engine/core/RealtimeStereoControlWord.h b/engine/core/RealtimeStereoControlWord.h new file mode 100644 index 000000000..a9b170166 --- /dev/null +++ b/engine/core/RealtimeStereoControlWord.h @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +// One canonical packed stereo gain / MUTE / SOLO word for M4 and ChannelId. +// Only serialized CONTROL encodes; AUDIO loads once/block. 31+31-bit gains +// and 2 bits of gating state; 64-bit lock-free atomics prevent torn decisions. +namespace armix::dsp { +struct RealtimeStereoControlWord final { + static constexpr std::uint64_t gainMask=(std::uint64_t{1}<<31)-1; + static constexpr std::uint64_t mutedBit=std::uint64_t{1}<<62; + static constexpr std::uint64_t soloBit=std::uint64_t{1}<<63; + static constexpr std::uint64_t unity=536870912ULL; + static_assert(std::atomic::is_always_lock_free, + "Realtime 64-bit control must never lock"); + struct Snapshot final { + float left=1.f,right=1.f; + bool mute=false,solo=false; + }; + static std::uint64_t quantize(float value) noexcept { + return static_cast( + static_cast(value)*(static_cast(gainMask)/4.)+.5); + } + static std::uint64_t encode(float left,float right,bool mute,bool solo) noexcept { + return quantize(left)|(quantize(right)<<31)| + (mute?mutedBit:0ULL)|(solo?soloBit:0ULL); + } + static Snapshot decode(std::uint64_t state) noexcept { + constexpr double scale=4./static_cast(gainMask); + return {static_cast(static_cast(state&gainMask)*scale), + static_cast(static_cast((state>>31)&gainMask)*scale), + (state&mutedBit)!=0,(state&soloBit)!=0}; + } +}; +} // namespace armix::dsp diff --git a/engine/core/UnifiedLegacyProductionAdmission.h b/engine/core/UnifiedLegacyProductionAdmission.h new file mode 100644 index 000000000..37d431806 --- /dev/null +++ b/engine/core/UnifiedLegacyProductionAdmission.h @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "LegacyLiveGraphMigration.h" +#include "DynamicChannelFxLeaseBank.h" +#include "DynamicNativeSessionPublisher.h" +#include +#include +#include +#include +#include +#include + +// M-U1: full M4 10CH + 4 AUX + MONITOR PCM and real VST leases are admitted +// as ONE identity-preserving dynamic session. No extra audio callback. +// This is CONTROL-only preparation; the physical callback cutover is a +// separate safety transaction and must select only ONE renderer. +// Occupied CH1 external/Orbit may be admitted ONLY with its original +// processor/editor owner and validated ChannelId; never silently drop VST. +namespace armix::mixer { +struct VerifiedNativeOutputs final { + int activeOutputChannels=0; // EXACT current enabled callback output count + int mainL=-1,mainR=-1,monitorL=-1,monitorR=-1; + bool monitorEnabled=false; + bool valid() const noexcept { + if(activeOutputChannels<2||activeOutputChannels>256 || + mainL<0||mainR<0||mainL>=activeOutputChannels|| + mainR>=activeOutputChannels||mainL==mainR)return false; + if(!monitorEnabled)return monitorL==-1&&monitorR==-1; + return monitorL>=0&&monitorR>=0&& + monitorL fxOwners{}; + VerifiedNativeOutputs hardware{}; + std::uint64_t deviceEpoch=0,pcmRevision=0; + + // E2 native GUI seam: bind a VST3 gesture to the CURRENT accepted PCM + // publisher, never just a retained old FX lease. Old editor handles may + // stay alive while a graph is retired, but stale controls cannot mutate + // a processor now referenced by a newer admitted graph. CONTROL only. + bool matches(const DynamicNativeSessionPublisher& publisher, + std::uint64_t epoch,std::uint64_t revision) const noexcept { + return epoch!=0 && revision!=0 && epoch==deviceEpoch && + revision==pcmRevision && fxOwners && + fxOwners->epoch()==epoch && fxOwners->revision()==revision && + publisher.acceptedRevision()==revision && + publisher.acceptedRouting(epoch,revision)!=nullptr; + } + bool setFxBypass(const DynamicNativeSessionPublisher& publisher, + std::uint64_t epoch,std::uint64_t revision, + ChannelId id,std::size_t slot, + const juce::String& instanceId,bool bypass) const noexcept { + return matches(publisher,epoch,revision) && + fxOwners->setInsertBypass(epoch,revision,id,slot, + instanceId,bypass); + } + DynamicChannelFxLeaseBank::Lease leaseFxEditor( + const DynamicNativeSessionPublisher& publisher, + std::uint64_t epoch,std::uint64_t revision,ChannelId id, + std::size_t slot,const juce::String& instanceId) const noexcept { + if(!matches(publisher,epoch,revision))return {}; + return fxOwners->leaseEditor(epoch,revision,id,slot,instanceId); + } +}; +class UnifiedLegacyProductionAdmission final { +public: + enum class Fault : std::uint8_t { + none,invalidOutputPins,staleHardware,outputArmed, + legacyCh1ExternalFx,staleFxGraph,legacyGraphInvalid, + fxLeaseInvalid,nativeRejected + }; + struct Report final { + Fault fault=Fault::none; + LegacyMigrationError migration{}; + DynamicChannelFxLeaseBank::Fault fx=DynamicChannelFxLeaseBank::Fault::none; + DynamicNativeSessionPublisher::CommitResult native{}; + bool ok() const noexcept {return fault==Fault::none;} + }; + + // Must be invoked on the SAME serialized M4 native control executor as + // hardware APPLY, Show capture and editor state. Prior accepted graph, + // leases and user outputs stay intact on any rejection. + static Report compileAndCommit( + const ChannelRoutingConfig& channels, + std::span callbackOrderedPhysicalPorts, + const SendRequest& sends,const AuxBusRequest& aux, + const std::array& monitorGains, + const LiveChannelFxGraph& acceptedM4Fx, + bool legacyExternalCh1FxActive, + const VerifiedNativeOutputs& hardware, + int maxFrames,std::size_t scratchBudget, + std::uint64_t expectedPcmRevision, + std::uint64_t deviceEpoch,std::uint64_t currentHardwareEpoch, + bool allOutputsDisarmed, + DynamicNativeSessionPublisher& publisher, + UnifiedLegacyAccepted& accepted, + DynamicChannelFxLeaseBank::ExternalLease externalCh1={}) { + Report result; + if(!hardware.valid() || + hardware.monitorEnabled!=acceptedM4Fx.monitorEnabled() || + hardware.mainL!=acceptedM4Fx.mainOutputLeft() || + hardware.mainR!=acceptedM4Fx.mainOutputRight() || + (hardware.monitorEnabled && + (hardware.monitorL!=acceptedM4Fx.monitorOutputLeft()|| + hardware.monitorR!=acceptedM4Fx.monitorOutputRight()))) { + result.fault=Fault::invalidOutputPins;return result; + } + if(!deviceEpoch || deviceEpoch!=currentHardwareEpoch) { + result.fault=Fault::staleHardware;return result; + } + if(!allOutputsDisarmed) { + result.fault=Fault::outputArmed;return result; + } + // A real legacy CH1 Graph owner may have no ChannelId until the + // accepted sparse-port topology has been compiled. Validate its + // lifetime/function now; bind its exact id from the compiled graph, + // not from a guessed strip index or WebView ordinal. + if(legacyExternalCh1FxActive!=externalCh1.populated() || + (legacyExternalCh1FxActive && + (!externalCh1.owner || externalCh1.context!=externalCh1.owner.get() || + !externalCh1.render))) { + result.fault=Fault::legacyCh1ExternalFx;return result; + } + // FxInstance owns one already-prepared stereo block. Do not let the + // dynamic callback deliver a larger quantum and silently bypass it. + if(maxFrames<1||maxFrames>acceptedM4Fx.capacity()|| + maxFrames>acceptedM4Fx.maxFramesPerPlugin()) { + result.fault=Fault::staleFxGraph;return result; + } + if(expectedPcmRevision!=publisher.acceptedRevision()) { + result.fault=Fault::nativeRejected; + result.native.fault=DynamicNativeSessionPublisher::Fault::staleRevision; + return result; + } + LegacyMigratedGraph candidate; + if(!LegacyGraphMigration::compile( + channels,callbackOrderedPhysicalPorts,sends,aux, + hardware.monitorEnabled,monitorGains,maxFrames,scratchBudget, + candidate,result.migration)) { + result.fault=Fault::legacyGraphInvalid;return result; + } + using Bank=DynamicChannelFxLeaseBank; + if(externalCh1.populated()) { + if((externalCh1.id.value && + externalCh1.id!=candidate.ids.inputs[0]) || + acceptedM4Fx.insertsOn(0)!=0) { + result.fault=Fault::legacyCh1ExternalFx;return result; + } + // The native compiler is the ONLY authority for stable ids. + // The original CH1 owner can never become an arbitrary bus. + externalCh1.id=candidate.ids.inputs[0]; + } + std::array lanes{}; + for(int i=0;iformat, + acceptedM4Fx,lanes[i])) { + result.fault=Fault::fxLeaseInvalid; + result.fx=Bank::Fault::missingLegacyIdentity; + return result; + } + } + Bank bank; + result.fx=Bank::prepare(deviceEpoch,expectedPcmRevision+1,lanes,bank, + std::move(externalCh1)); + if(result.fx!=Bank::Fault::none) { + result.fault=Fault::fxLeaseInvalid;return result; + } + auto owner=std::make_shared(std::move(bank)); + DynamicNativeSessionPublisher::FxPlan plan; + plan.owner=std::static_pointer_cast(owner); + plan.context=owner.get(); + plan.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(ctx))(id,l,r,n); + }; + plan.deviceEpoch=deviceEpoch;plan.graphRevision=expectedPcmRevision+1; + result.native=publisher.commit(candidate.roster,candidate.request, + expectedPcmRevision,deviceEpoch,currentHardwareEpoch, + allOutputsDisarmed,std::move(plan)); + if(!result.native.ok()) { + result.fault=Fault::nativeRejected;return result; + } + UnifiedLegacyAccepted next; + next.graph=std::move(candidate); + next.fxOwners=std::move(owner); + next.hardware=hardware; + next.deviceEpoch=deviceEpoch; + next.pcmRevision=result.native.revision; + accepted=std::move(next); + return result; + } +}; +} // namespace armix::mixer diff --git a/src/ApprovedNativeV8Projection.h b/src/ApprovedNativeV8Projection.h new file mode 100644 index 000000000..ab95387fd --- /dev/null +++ b/src/ApprovedNativeV8Projection.h @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include +#include +#include + +// Single JUCE CONTROL-thread adapter: installed PCM/ChannelId readback -> +// approved /preview/ public schema v8. No new renderer, callback or DSP. +namespace armix::console { +inline bool nativeV8Decimal(const juce::var& value) { + if(!value.isString())return false; + const auto s=value.toString().toStdString(); + if(s.empty()||s.size()>20||(s.size()>1&&s[0]=='0'))return false; + std::uint64_t n=0; + for(char c:s) { + if(c<'0'||c>'9')return false; + auto d=static_cast(c-'0'); + if(n>(std::numeric_limits::max()-d)/10)return false; + n=n*10+d; + } + return n!=0; +} +inline bool nativeV8Number(const juce::var& value,double& n) { + if(!value.isInt()&&!value.isInt64()&&!value.isDouble())return false; + n=static_cast(value); + return std::isfinite(n); +} +inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus) { + const auto rawRows=bus.getProperty("channels",{}),rawEdges=bus.getProperty("edges",{}); + const auto* rows=rawRows.getArray();const auto* edges=rawEdges.getArray(); + const auto rev=bus.getProperty("graphRevision",{}),roster=bus.getProperty("rosterRevision",{}); + if(!rows||rows->isEmpty()||!edges||!nativeV8Decimal(rev)|| + !nativeV8Decimal(roster))return false; + juce::Array channels,wires,destinations; + std::unordered_set ids,edgeIds; + auto meters=std::make_unique(); + juce::String mainId; + for(const auto& row:*rows) { + const auto id=row.getProperty("id",{}),name=row.getProperty("name",{}); + const auto role=row.getProperty("role","").toString(); + const auto format=row.getProperty("format","").toString(); + const auto out=row.getProperty("primaryOutput",{}); + const auto fader=row.getProperty("fader",{}),pan=row.getProperty("pan",{}); + const auto mute=row.getProperty("mute",{}),solo=row.getProperty("solo",{}); + const auto inserts=row.getProperty("inserts",{}); + double linear=0.,p=0.; + if(!nativeV8Decimal(id)||!ids.insert(id.toString().toStdString()).second || + !name.isString()||name.toString().isEmpty()|| + (role!="INPUT"&&role!="GROUP"&&role!="FX_RETURN"&&role!="MAIN"&&role!="MONITOR")|| + (format!="MONO"&&format!="STEREO")|| + !out.isString()||!nativeV8Number(fader,linear)|| + !nativeV8Number(pan,p)||linear<0.||linear>4.||p< -1.||p>1.|| + !mute.isBool()||!solo.isBool()||!inserts.isArray())return false; + if(role=="MAIN"){if(mainId.isNotEmpty())return false;mainId=id.toString();} + auto ch=std::make_unique(); + ch->setProperty("id",id);ch->setProperty("name",name); + ch->setProperty("role",role);ch->setProperty("processingFormat",format); + if(out.toString()!="0") { + if(!nativeV8Decimal(out)||out.toString()==id.toString())return false; + ch->setProperty("primaryOutId",out); + } + const auto source=row.getProperty("source",{}); + if(source.isObject())ch->setProperty("source",source); + auto controls=std::make_unique(); + const double db=linear>0.?20.*std::log10(linear):-60.; + controls->setProperty("faderDb",juce::jlimit(-60.,12.,db)); + controls->setProperty("pan",p); + controls->setProperty("mute",mute);controls->setProperty("solo",solo); + ch->setProperty("controls",juce::var(controls.release())); + juce::Array fx; + for(const auto& item:*inserts.getArray()){ + const auto token=item.getProperty("instanceId",{}),label=item.getProperty("name",{}); + const auto bypass=item.getProperty("bypassed",{}); + if(!token.isString()||!label.isString()||!bypass.isBool())return false; + auto insert=std::make_unique(); + insert->setProperty("id",token);insert->setProperty("name",label); + insert->setProperty("bypassed",bypass); + fx.add(juce::var(insert.release())); + } + ch->setProperty("inserts",juce::var(fx)); + ch->setProperty("sends",juce::var(juce::Array{})); + if(role!="INPUT"){ + auto dst=std::make_unique(); + dst->setProperty("id",id);dst->setProperty("name",name); + dst->setProperty("role",role); + destinations.add(juce::var(dst.release())); + } + double left=0.,right=0.; + if(nativeV8Number(row.getProperty("peakL",{}),left) && + nativeV8Number(row.getProperty("peakR",{}),right) && + left>=0.&&right>=0.){ + auto peak=std::make_unique(); + peak->setProperty("peakL",left);peak->setProperty("peakR",right); + meters->setProperty(juce::Identifier(id.toString()),juce::var(peak.release())); + } + channels.add(juce::var(ch.release())); + } + if(mainId.isEmpty())return false; + for(const auto& channel:channels) { + const auto out=channel.getProperty("primaryOutId",{}); + if(out.isString()&&!ids.count(out.toString().toStdString()))return false; + } + for(const auto& edge:*edges) { + const auto id=edge.getProperty("edgeId",{}),from=edge.getProperty("from",{}), + to=edge.getProperty("to",{}),gain=edge.getProperty("gainLinear",{}); + const auto tap=edge.getProperty("tap","").toString(); + const auto primary=edge.getProperty("primaryOutput",{}); + double linear=0.; + if(!nativeV8Decimal(id)||!nativeV8Decimal(from)||!nativeV8Decimal(to)|| + from.toString()==to.toString()|| + !edgeIds.insert(id.toString().toStdString()).second|| + !ids.count(from.toString().toStdString())|| + !ids.count(to.toString().toStdString())|| + from.toString()==mainId||(tap!="PRE_FADER"&&tap!="POST_FADER")|| + !nativeV8Number(gain,linear)||linear<0.||linear>4.|| + !primary.isBool())return false; + auto w=std::make_unique(); + w->setProperty("edgeId",id);w->setProperty("from",from);w->setProperty("to",to); + w->setProperty("tap",tap);w->setProperty("gainLinear",linear); + w->setProperty("primaryOutput",primary); + w->setProperty("enabled",true);w->setProperty("signalKind","AUDIO"); + wires.add(juce::var(w.release())); + if(!static_cast(primary))for(auto& channel:channels) { + if(channel.getProperty("id","").toString()!=from.toString())continue; + auto send=std::make_unique(); + send->setProperty("id",id);send->setProperty("targetId",to); + send->setProperty("tap",tap);send->setProperty("gainLinear",linear); + const auto list=channel.getProperty("sends",{}); + if(auto* a=list.getArray())a->add(juce::var(send.release())); + break; + } + } + const auto graph=snapshot.getProperty("graph",{}); + const auto telemetry=snapshot.getProperty("telemetry",{}); + auto* g=graph.getDynamicObject();auto* t=telemetry.getDynamicObject(); + if(!g||!t)return false; + // All validation completed before anything becomes authoritative. + g->setProperty("revision",rev);g->setProperty("rosterRevision",roster); + g->setProperty("mainChannelId",mainId); + g->setProperty("channels",juce::var(channels)); + g->setProperty("destinations",juce::var(destinations)); + g->setProperty("edges",juce::var(wires)); + if(auto* caps=graph.getProperty("capabilities",{}).getDynamicObject()){ + caps->setProperty("callbackOwnsChannelIds",true); + juce::Array ops;ops.add("APPLY_WIRE_TRANSACTION"); + caps->setProperty("supportedOps",juce::var(ops)); + } + t->setProperty("channelMeterRmsPeak",juce::var(meters.release())); + // productionCallbackLive deliberately stays FALSE until full FAT. + return true; +} +} // namespace armix::console diff --git a/src/ConsoleLiveBridgeV6.h b/src/ConsoleLiveBridgeV6.h new file mode 100644 index 000000000..a30991611 --- /dev/null +++ b/src/ConsoleLiveBridgeV6.h @@ -0,0 +1,994 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include "../integration/ConsoleNativeContractV6.h" +#include "../engine/core/ConsolePuzzleV8Wire.h" +#include "ApprovedNativeV8Projection.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Native Console v6 adapter, exclusively on the JUCE MESSAGE/CONTROL thread. +// This projects the real M4 callback/device readback WITHOUT promoting its +// fixed strip indexes to fictitious ChannelIds. The production ChannelId +// migration must replace this deliberately fail-closed G0 capability gate. +// It never owns PCM, clones VST3, or calls the audio device from the browser. +// Legacy G0 fixture compatibility is confined to the TEST-only bridge. +// The shipping WebView2 uses integration/ApprovedNative* instead. These two +// pure validation functions retain the old fixture's strict uint64/replay +// contract without importing the obsolete integration/ConsoleNativeContractV6 +// into the production control boundary. +namespace armix::integration { +inline bool validConsoleRequestId(std::string_view id) noexcept { + if(id.empty() || id.size()>128)return false; + return std::all_of(id.begin(),id.end(),[](unsigned char ch) noexcept { + return ch>=0x21 && ch<=0x7e; + }); +} +inline bool parseNativeChannelId(std::string_view token,ChannelId& out) noexcept { + if(token.empty() || (token.size()>1 && token.front()=='0'))return false; + std::uint64_t value=0; + for(const char ch:token) { + if(ch<'0'||ch>'9')return false; + const auto digit=static_cast(ch-'0'); + if(value>(std::numeric_limits::max()-digit)/10u) + return false; + value=value*10u+digit; + } + if(value==0)return false; // Zero is the explicit unconnected OUT sentinel. + out=ChannelId{value};return true; +} +} // namespace armix::integration + +namespace armix::console { +class LiveConsoleBridgeV6 final { +public: + static constexpr int schemaVersion=6; + + // Source: LiveAudioEngine::status() with its real JUCE callback telemetry, + // driver active masks and epoch. No browser invented physical pins. + static juce::var snapshot(const juce::var& live) { + // Single actual native producer for both JUCE WebView and S0 + // fixture. No JSON shape authored by the JS/GUI. + PuzzleV8Snapshot w; + const auto route=live.getProperty("dryRoutingLab",juce::var()); + // The control session has an epoch even before a driver is opened. + // 1 is the UNREADY session generation, NOT a fabricated physical + // source; any later verified device epoch supersedes this token. + auto actualEpoch=decimalFromNative(route.getProperty("epoch",juce::var())); + if(actualEpoch=="0")actualEpoch="1"; + w.epoch=actualEpoch.toStdString(); + w.legacyRoutingRevision=decimalFromNative( + route.getProperty("revision",juce::var())).toStdString(); + // The accepted fixed-M4 revision stays under legacyM4 only. + // A ChannelId revision is never copied from an ordinal M4 graph. + w.legacyActive=static_cast(route.getProperty("active",false)); + w.legacyRouteAccepted=static_cast(route.getProperty("ready",false)) && + static_cast(route.getProperty("hasAcceptedRoute",false)); + w.backend=live.getProperty("driver","").toString().toStdString(); + w.captureDevice=live.getProperty("inputDevice","").toString().toStdString(); + w.playbackDevice=live.getProperty("outputDevice","").toString().toStdString(); + const double rate=static_cast(live.getProperty("rate",0.)); + if(std::isfinite(rate) && rate>0. && rate<=384000.) + w.sampleRate=static_cast(rate); + const int frames=static_cast(live.getProperty("buffer",0)); + if(frames>0)w.bufferFrames=frames; + const bool connected=static_cast(live.getProperty("connected",false)); + w.outputArmed=connected && w.legacyRouteAccepted && + static_cast(live.getProperty("monitor",false)) && + static_cast(live.getProperty("directRouteAuthorized",false)); + const auto peak=static_cast(live.getProperty("inputPeak",0.)); + if(std::isfinite(peak) && peak>=0.)w.rawCapturePeak=peak; + w.rawCapturePresent=connected && + static_cast(live.getProperty("callbackCount",0.))>0. && + static_cast(live.getProperty("callbackInputChannels",0))>0 && + w.rawCapturePeak>0.0005; + w.mainPcmPresent=w.outputArmed && + static_cast(live.getProperty("peak",0.))>0.0002; + w.monitorPcmPresent=w.outputArmed && + static_cast(route.getProperty("monitorPeakL",0.))>0.0002; + const auto pins=route.getProperty("ports",juce::var()); + const auto peaks=live.getProperty("captureCallbackPeaks",juce::var()); + const auto* readings=peaks.getArray(); + if(const auto* physical=pins.getArray()) + for(const auto& p:*physical) { + const auto number=p.getProperty("port",juce::var()); + const auto ordinal=p.getProperty("callback",juce::var()); + if(!number.isInt()||!ordinal.isInt())continue; + PuzzleV8Pin pin; + pin.port=static_cast(number); + pin.callback=static_cast(ordinal); + if(pin.port<0 || pin.callback<0)continue; + pin.label=p.getProperty("label","").toString().toStdString(); + if(readings && pin.callbacksize()) { + const auto value=readings->getReference(pin.callback); + if(value.isInt()||value.isDouble()) { + const auto peakValue=static_cast(value); + if(std::isfinite(peakValue)&&peakValue>=0.) { + pin.hasRawPeak=true;pin.rawPeak=peakValue; + } + } + } + w.inputs.push_back(std::move(pin)); + } + const auto outputs=route.getProperty("outputPorts",juce::var()); + if(const auto* ports=outputs.getArray()) + for(int ordinal=0;ordinalsize();++ordinal) { + const auto value=ports->getReference(ordinal); + if(!value.isInt())continue; + const int physical=static_cast(value); + if(physical<0)continue; + w.outputs.push_back({physical,ordinal,{},{},0.}); + } + // The installed ABI is still M4 ordinals, but the single JUCE + // callback may now select the real native ChannelId PCM renderer + // with original CH1/Orbit lease after accepted admission. Neither + // physical mode implies universal CH11/GROUP/WIRE ownership. + w.productionCallbackLive=false; + const auto bytes=PuzzleV8Wire::snapshot(w); + auto actual=juce::JSON::parse(juce::String::fromUTF8(bytes.c_str())); + // Optional diagnosed M4 accepted controls are sourced from the + // installed JUCE control thread, not stale immutable routing faders. + // UNREADY fixture stays byte-identical; these are NOT ChannelIds. + const auto legacy=actual.getProperty("legacyM4",{}); + if(auto* object=legacy.getDynamicObject()) { + // Current native M4 (not a fake ChannelId roster): exactly the + // signal that is audible in this physical device callback. + const auto controls=route.getProperty("channelControls",juce::var()); + const auto peaksL=route.getProperty("channelPeaksL",juce::var()); + const auto peaksR=route.getProperty("channelPeaksR",juce::var()); + const auto inserts=route.getProperty("fxInstances",juce::var()); + if(controls.isArray())object->setProperty("channelControls",controls); + if(peaksL.isArray())object->setProperty("channelPeaksL",peaksL); + if(peaksR.isArray())object->setProperty("channelPeaksR",peaksR); + if(inserts.isArray())object->setProperty("fxInstances",inserts); + // The prepared/unpatched native M4 graph is a real silent route. + // It allows direct IN gesture to activate the FIRST source. + // This does not set productionCallbackLive or fake PCM. + const auto configured=route.getProperty("acceptedRoute",juce::var()); + const auto prepared=route.getProperty("preparedM4Route",juce::var()); + const auto topo=configured.isObject()?configured:prepared; + if(topo.isObject()) { + const auto sends=topo.getProperty("sends",juce::var()); + const auto returns=topo.getProperty("auxes",juce::var()); + if(sends.isArray())object->setProperty("acceptedSends",sends); + if(returns.isArray())object->setProperty("auxReturns",returns); + // Legacy M4 physical inputs/output membership are CONTROL + // readbacks from the actually admitted 10-strip route. Never + // infer them from presentation order or a UI draft. + const auto channels=topo.getProperty("channels",juce::var()); + if(connected && w.legacyActive && + (w.legacyRouteAccepted || + (static_cast(route.getProperty("ready",false)) && + prepared.isObject())) && + !static_cast(route.getProperty("topologyFault",false)) && + channels.isArray() && + channels.getArray()->size()==armix::mixer::stripCount) { + object->setProperty("acceptedChannels",channels); + object->setProperty("controlPlane","LEGACY_M4_ORDINAL"); + // Real accepted PCM provenance for FAT/GUI diagnostics. + // Read from LiveAudioEngine's installed callback, not + // guessed browser roles. This does NOT enable universal + // supportedOps, ChannelIds, or graph revision. + const bool native=static_cast(route.getProperty( + "nativeChannelIdPcmActive",false)); + object->setProperty("pcmRenderer",native + ?"CHANNEL_ID_10CH4AUX":"M4_COMPAT"); + object->setProperty("originalCh1GraphLeased", + native && static_cast(route.getProperty( + "originalCh1GraphLeased",false))); + // Separate scoped native bus transport, not universal + // v8 graph capabilities or synthetic M4 strip ordinals. + const auto bus=route.getProperty("nativeBus",juce::var()); + if(native && bus.isObject()) { + object->setProperty("nativeBus",bus); + // Native PCM is the only source of exact ChannelIds, + // EdgeIds and accepted revision for the v8 projection. + const auto channels=bus.getProperty("channels",{}); + const auto edges=bus.getProperty("edges",{}); + const auto rev=bus.getProperty("graphRevision",{}); + const auto roster=bus.getProperty("rosterRevision",{}); + const auto nativeOps=bus.getProperty("supportedOps",{}); + std::uint64_t graphId=0,rosterId=0; + const auto* ops=nativeOps.getArray(); + // Project REAL native PCM state to the public v8 ABI. + // Raw nativeBus fields must not be published verbatim: + // fader is linear, format/primaryOutput are internal, + // and native edges lack enabled/signalKind. + if(channels.isArray() && edges.isArray() && ops && + ops->contains(juce::var(juce::String( + "NATIVE_APPLY_WIRE_TRANSACTION"))) && + decodeDecimal(rev,graphId) && graphId && + decodeDecimal(roster,rosterId) && rosterId) + (void)projectApprovedNativeV8(actual,bus); + // Full product-LIVE remains gated on VST3/Show/monitor + // parity and measured hardware FAT (#15). + } + // Separate namespace: these operations mutate the one + // INSTALLED M4 JUCE PCM graph. They are NEVER universal + // graph.capabilities.supportedOps or ChannelIds. + juce::Array allowed; + for(const char* op: {"SET_SOURCE","SET_PROCESSING_FORMAT", + "SET_PRIMARY_OUT","SET_FADER","SET_PAN","SET_MUTE","SET_SOLO"}) + allowed.add(juce::var(juce::String(op))); + if(returns.isArray())allowed.add(juce::var("SET_AUX_FADER")); + if(sends.isArray()&&!sends.getArray()->isEmpty()) + allowed.add(juce::var("SET_SEND_LEVEL")); + if(inserts.isArray()) { + bool hasNativeFx=false; + for(const auto& rack:*inserts.getArray()) + if(rack.isArray()&&!rack.getArray()->isEmpty()) { + hasNativeFx=true;break; + } + if(hasNativeFx) { + allowed.add(juce::var("SET_INSERT_BYPASS")); + allowed.add(juce::var("OPEN_INSERT_EDITOR")); + } + } + object->setProperty("supportedOps",juce::var(allowed)); + } + } + const auto monitorSends=route.getProperty("monitorSends",juce::var()); + if(monitorSends.isArray()) + object->setProperty("monitorSends",monitorSends); + const auto main=route.getProperty("mainOutputs",juce::var()); + if(main.isArray())object->setProperty("mainOutputs",main); + const auto monitor=route.getProperty("monitorOutputs",juce::var()); + if(monitor.isArray()) { + object->setProperty("monitorOutputs",monitor); + if(object->hasProperty("supportedOps") && + monitor.getArray()->size()==2) { + auto operations=object->getProperty("supportedOps"); + if(auto* list=operations.getArray()) { + list->add(juce::var("SET_MONITOR_LEVEL")); + object->setProperty("supportedOps",operations); + } + } + } + } + return actual; + } + + // Exact native wire: opaque, unique-per-editor requestId and uint64 + // canonical DECIMAL STRINGS, never a lossy double / JS Number cast. + // This G0 adapter has no supported mutating operation: an invalid/stale + // request or unsupported role must preserve the currently audible M4. + juce::var rejectUnsupportedIntent(const juce::var& intent, + const juce::var& acceptedSnapshot) { + const auto request=intent.getProperty("requestId",juce::var()); + const auto id=request.isString()?request.toString():juce::String{}; + const auto requestBytes=id.toStdString(); + const auto device=acceptedSnapshot.getProperty("device",{}); + const auto graph=acceptedSnapshot.getProperty("graph",{}); + const auto epoch=device.getProperty("epoch","0").toString(); + juce::String fault="UNIVERSAL_CALLBACK_NOT_READY"; + if(!armix::integration::validConsoleRequestId(requestBytes)) + fault="INVALID_REQUEST_ID"; + else if(completed_.find(requestBytes)!=completed_.end()) + fault="DUPLICATE_REQUEST_ID"; + else { + if(recentIds_.size()==maxRecentIds) { + completed_.erase(recentIds_.front()); + recentIds_.pop_front(); + } + recentIds_.push_back(requestBytes); + completed_.insert(requestBytes); + // G0 is fail closed by design. Distinguish malformed/stale wire + // from a legitimate mutation that requires the M4->M5 cutover. + std::uint64_t asked=0,baseGraph=0,baseRoster=0; + const bool wellFormed=decodeDecimal(intent.getProperty("deviceEpoch",{}),asked) && + decodeDecimal(intent.getProperty("baseGraphRevision",{}),baseGraph) && + decodeDecimal(intent.getProperty("baseRosterRevision",{}),baseRoster) && + intent.getProperty("operation",{}).isString(); + if(!wellFormed)fault="INVALID_DECIMAL_WIRE"; + else if(intent.getProperty("deviceEpoch",{}).toString()!=epoch) + fault="STALE_DEVICE_EPOCH"; + else if(intent.getProperty("baseGraphRevision",{}).toString()!= + graph.getProperty("revision","0").toString() || + intent.getProperty("baseRosterRevision",{}).toString()!= + graph.getProperty("rosterRevision","0").toString()) + fault="STALE_GRAPH_REVISION"; + else { + const auto target=intent.getProperty("targetChannelId",juce::var()); + armix::mixer::ChannelId channel{}; + if(!target.isVoid() && + (!target.isString() || + !armix::integration::parseNativeChannelId( + target.toString().toStdString(),channel))) + fault="INVALID_CHANNEL_ID"; + } + } + PuzzleV8Ack ack; + ack.requestId=requestBytes; + ack.status="REJECTED"; + ack.deviceEpoch=epoch.toStdString(); + ack.graphRevision=graph.getProperty("revision","0").toString().toStdString(); + ack.rosterRevision=graph.getProperty("rosterRevision","0").toString().toStdString(); + ack.errorCode=fault.toStdString(); + const auto bytes=PuzzleV8Wire::ack(ack); + return juce::JSON::parse(juce::String::fromUTF8(bytes.c_str())); + } + + + // S1 production bridge: operate the ACTUALLY INSTALLED M4 graph through + // LiveAudioEngine. A Legacy M4 lane is addressed by decimal "1".."10" + // only for this explicit internal migration transport. This does NOT + // claim that callbackOwnsChannelIds, CH11, GROUP or FX_RETURN exist. + // The same native audio owner, plugin editor and Show remain installed. + template + juce::var processProductionIntent(const juce::var& intent, + const juce::var& acceptedSnapshot, + Engine& engine,OpenEditor&& openEditor) { + const auto request=intent.getProperty("requestId",{}); + const auto requestId=request.isString()?request.toString():juce::String{}; + const auto bytes=requestId.toStdString(); + const auto device=acceptedSnapshot.getProperty("device",{}); + const auto graph=acceptedSnapshot.getProperty("graph",{}); + const auto epoch=device.getProperty("epoch","0").toString(); + const auto oldRev=graph.getProperty("revision","0").toString(); + const auto oldRoster=graph.getProperty("rosterRevision","0").toString(); + const auto legacyRev=acceptedSnapshot.getProperty("legacyM4",{}) + .getProperty("routingRevision","0").toString(); + juce::String error; + bool accepted=false; + if(!armix::integration::validConsoleRequestId(bytes))error="INVALID_REQUEST_ID"; + else if(completed_.find(bytes)!=completed_.end())error="DUPLICATE_REQUEST_ID"; + else { + if(recentIds_.size()==maxRecentIds) { + completed_.erase(recentIds_.front()); + recentIds_.pop_front(); + } + recentIds_.push_back(bytes); + completed_.insert(bytes); + std::uint64_t ep=0,rev=0,roster=0,channelId=0,m4Revision=0; + const auto target=intent.getProperty("targetChannelId",{}); + const auto payload=intent.getProperty("payload",{}); + const auto operation=intent.getProperty("operation",{}).toString(); + if(!decodeDecimal(intent.getProperty("deviceEpoch",{}),ep) || + !decodeDecimal(intent.getProperty("baseGraphRevision",{}),rev) || + !decodeDecimal(intent.getProperty("baseRosterRevision",{}),roster)) + error="INVALID_DECIMAL_WIRE"; + else if(intent.getProperty("deviceEpoch",{}).toString()!=epoch) + error="STALE_DEVICE_EPOCH"; + else if(intent.getProperty("baseGraphRevision",{}).toString()!=oldRev || + intent.getProperty("baseRosterRevision",{}).toString()!=oldRoster) + error="STALE_GRAPH_REVISION"; + // M4's presentation ordinals are NOT universal ChannelIds. + // A legacy-console intent requires an explicit independent + // revision fence. Without it, reject rather than silently + // alias the ChannelId graph's revision 0 to an M4 revision. + else if(!decodeDecimal(intent.getProperty("legacyRoutingRevision",{}), + m4Revision) || + intent.getProperty("legacyRoutingRevision","").toString()!=legacyRev) + error="STALE_LEGACY_ROUTING_REVISION"; + else if(!target.isString() || !decodeDecimal(target,channelId) || + channelId<1 || + (channelId>10 && + !((operation=="SET_MONITOR_LEVEL"|| + operation=="SET_AUX_FADER")&&channelId<=14))) + error="INVALID_LEGACY_CHANNEL_ID"; + // Never trust a guessed M4 ordinal or synthetic editor status. + // Native accepted hardware, actual route rows and the current + // topology-fault bit must have produced an explicit M4 authority + // envelope in this very same status snapshot. + else if(acceptedSnapshot.getProperty("legacyM4",{}) + .getProperty("controlPlane","").toString()!="LEGACY_M4_ORDINAL" || + !engine.dryRoutingLabActive() || + engine.dryRoutingLabEpoch()!=ep || + engine.dryRoutingLabRevision()!=m4Revision) + error="PRODUCTION_GRAPH_NOT_ADMITTED"; + else if(!payload.isObject())error="INVALID_PAYLOAD"; + else { + const int lane=static_cast(channelId-1); + if(operation=="SET_SOURCE") { + const auto id=payload.getProperty("portId",{}).toString(); + int left=-1; + if(parsePortId(id,"in:",left)) { + const auto rightId=payload.getProperty("rightPortId",{}).toString(); + int right=-1; + const auto format=payload.getProperty("sourceFormat","MONO").toString(); + if(format=="STEREO" && !parsePortId(rightId,"in:",right)) + error="INVALID_STEREO_RIGHT_PIN"; + else if(format!="MONO"&&format!="STEREO") + error="INVALID_SOURCE_FORMAT"; + else error=engine.switchDryRoutingLabSource( + lane,ep,m4Revision,format,left,right); + } else error="INVALID_PHYSICAL_INPUT_PORT"; + accepted=error.isEmpty(); + } else if(operation=="SET_FADER"||operation=="SET_PAN"|| + operation=="SET_MUTE"||operation=="SET_SOLO") { + const bool binary=operation=="SET_MUTE"||operation=="SET_SOLO"; + const auto value=payload.getProperty(binary?"value":"valueDb",{}); + juce::String key; + float control=0.f; + if(binary) { + const auto b=payload.getProperty("value",{}); + const auto on=payload.getProperty("enabled",b); + if(!on.isBool())error="INVALID_BOOLEAN_CONTROL"; + else control=static_cast(on)?1.f:0.f; + } else { + const auto number=payload.getProperty( + operation=="SET_FADER"?"valueDb":"value",{}); + if(!number.isInt()&&!number.isDouble()) + error="INVALID_NUMERIC_CONTROL"; + else { + const double v=static_cast(number); + if(!std::isfinite(v))error="NON_FINITE_CONTROL"; + else control=static_cast(v); + } + } + if(error.isEmpty()) { + if(operation=="SET_FADER")key="faderDb"; + else if(operation=="SET_PAN")key="pan"; + else if(operation=="SET_MUTE")key="mute"; + else key="solo"; + accepted=engine.setDryRoutingLabParameter( + lane,ep,m4Revision,key,control); + if(!accepted)error="NATIVE_CONTROL_REJECTED"; + } + } else if(operation=="CONNECT_AUX_SEND") { + const auto bus=payload.getProperty("auxIndex",{}); + const auto tapName=payload.getProperty("tap","POST").toString(); + const auto gain=payload.getProperty("value",{}); + const auto pan=payload.getProperty("pan",juce::var(0.0)); + if(!bus.isInt()||static_cast(bus)<0|| + static_cast(bus)>=armix::mixer::auxBusCount) + error="INVALID_AUX_RETURN"; + else if(tapName!="PRE"&&tapName!="POST") + error="INVALID_SEND_TAP"; + else if((!gain.isInt()&&!gain.isDouble())|| + (!pan.isInt()&&!pan.isDouble())) + error="INVALID_SEND_GAIN_OR_PAN"; + else { + const double level=static_cast(gain); + const double balance=static_cast(pan); + if(!std::isfinite(level)||level<0.||level>1.|| + !std::isfinite(balance)||balance< -1.||balance>1.) + error="INVALID_SEND_GAIN_OR_PAN"; + else { + error=engine.connectDryRoutingLabAuxSend( + lane,static_cast(bus),ep,m4Revision, + tapName=="PRE"?armix::mixer::SendTap::preFader: + armix::mixer::SendTap::postFader, + static_cast(level),static_cast(balance)); + accepted=error.isEmpty(); + } + } + } else if(operation=="SET_AUX_FADER") { + // Native AUX return fader AFTER its real VST3 rack. + // 11..14 are explicit legacy M4 auxiliary ordinals; + // never pretend these are stable universal ChannelIds. + if(channelId<11||channelId>14) + error="INVALID_LEGACY_AUX_CHANNEL"; + else { + const auto raw=payload.getProperty("value",{}); + if(!raw.isInt()&&!raw.isDouble()) + error="INVALID_AUX_FADER"; + else { + const double gain=static_cast(raw); + if(!std::isfinite(gain)||gain<0.||gain>4.) + error="INVALID_AUX_FADER"; + else { + accepted=engine.setDryRoutingLabAuxBusGain( + static_cast(channelId-11),ep, + m4Revision,static_cast(gain)); + if(!accepted)error="AUX_RETURN_NOT_ADMITTED"; + } + } + } + } else if(operation=="SET_MONITOR_LEVEL") { + const auto raw=payload.getProperty("value",{}); + if(!raw.isInt()&&!raw.isDouble()) + error="INVALID_MONITOR_LEVEL"; + else { + const double gain=static_cast(raw); + if(!std::isfinite(gain)||gain<0.||gain>1.) + error="INVALID_MONITOR_LEVEL"; + else { + accepted=engine.setDryRoutingLabMonitorSendGain( + lane,ep,m4Revision,static_cast(gain)); + if(!accepted)error="MONITOR_BUS_NOT_ADMITTED"; + } + } + } else if(operation=="SET_SEND_LEVEL") { + // A SEND level is native realtime PCM, NOT a new graph + // edge. Existing AUX1..4 are independent FX return buses. + const auto aux=payload.getProperty("auxIndex",{}); + const auto tapName=payload.getProperty("tap","POST").toString(); + const auto raw=payload.getProperty("value",{}); + if(!aux.isInt()||static_cast(aux)<0|| + static_cast(aux)>=armix::mixer::auxBusCount) + error="INVALID_AUX_RETURN"; + else if(tapName!="PRE"&&tapName!="POST") + error="INVALID_SEND_TAP"; + else if(!raw.isInt()&&!raw.isDouble()) + error="INVALID_SEND_LEVEL"; + else { + const double value=static_cast(raw); + if(!std::isfinite(value)||value<0.||value>1.) + error="INVALID_SEND_LEVEL"; + else { + const auto tap=tapName=="PRE"? + armix::mixer::SendTap::preFader: + armix::mixer::SendTap::postFader; + accepted=engine.setDryRoutingLabAuxSendGain( + lane,static_cast(aux),ep,m4Revision, + static_cast(value),tap); + if(!accepted)error="NATIVE_SEND_NOT_ADMITTED"; + } + } + } else if(operation=="SET_PROCESSING_FORMAT"|| + operation=="SET_PRIMARY_OUT") { + const auto nativeValue=payload.getProperty( + operation=="SET_PRIMARY_OUT"?"destinationId":"format",{}) + .toString(); + error=engine.repatchDryRoutingLabChannel( + lane,ep,m4Revision,operation,nativeValue); + accepted=error.isEmpty(); + } else if(operation=="SET_INSERT_BYPASS"|| + operation=="OPEN_INSERT_EDITOR") { + // The token must match an actually prepared vendor + // AudioPluginInstance in the current accepted M4 graph. + // Never invent a GUI insert, instantiate, clone or scan + // VST3 while changing BYPASS / opening an editor. + const auto token=payload.getProperty("insertId","").toString(); + const auto statuses=engine.status().getProperty("dryRoutingLab",{}); + const auto fx=statuses.getProperty("fxInstances",{}); + const auto* lanes=fx.getArray(); + int foundSlot=-1; + if(token.isNotEmpty() && lanes && lanesize()) { + const auto bank=lanes->getReference(lane); + if(const auto* slots=bank.getArray()) + for(int k=0;ksize();++k) + if(slots->getReference(k).getProperty("instanceId","") + .toString()==token) { + if(foundSlot>=0){foundSlot=-1;break;} + foundSlot=k; + } + } + if(foundSlot<0)error="UNKNOWN_NATIVE_INSERT_INSTANCE"; + else if(operation=="SET_INSERT_BYPASS") { + const auto value=payload.getProperty("bypassed",{}); + if(!value.isBool())error="INVALID_BYPASS_VALUE"; + else { + accepted=engine.setDryRoutingLabFxBypass( + lane,foundSlot,ep,m4Revision,token,static_cast(value)); + if(!accepted)error="NATIVE_INSERT_BYPASS_REJECTED"; + } + } else { + error=openEditor(lane,foundSlot,ep,m4Revision,token); + accepted=error.isEmpty(); + } + } else error="UNSUPPORTED_UNIVERSAL_OPERATION"; + } + } + const auto after=armix::console::LiveConsoleBridgeV6::snapshot(engine.status()); + const auto afterGraph=after.getProperty("graph",{}); + PuzzleV8Ack ack; + ack.requestId=bytes; + ack.status=accepted?"ACCEPTED":"REJECTED"; + ack.deviceEpoch=after.getProperty("device",{}).getProperty("epoch",epoch).toString().toStdString(); + ack.graphRevision=afterGraph.getProperty("revision",oldRev).toString().toStdString(); + ack.rosterRevision=afterGraph.getProperty("rosterRevision",oldRoster).toString().toStdString(); + ack.errorCode=error.toStdString(); + const auto json=PuzzleV8Wire::ack(ack); + return juce::JSON::parse(juce::String::fromUTF8(json.c_str())); + } + + + // E3 scoped native bus control transport. The installed callback already + // owns this stable ChannelId graph; output is DISARMED for structural + // changes, and readback comes from the newly accepted PCM publisher. + // This is deliberately a SEPARATE legacyM4.nativeBus namespace rather + // than claiming that universal CH11/WIRE/SHOW is available. + template + juce::var processNativeBusIntent(const juce::var& intent, + const juce::var& snapshot, + Engine& engine,bool ioBusy, + NativeFxAction&& onNativeFx) { + const auto req=intent.getProperty("requestId",juce::var()); + const auto request=req.isString()?req.toString():juce::String(); + const auto key=request.toStdString(); + const bool v8Wire=intent.getProperty("operation","").toString()== + "APPLY_WIRE_TRANSACTION"; + const auto device=snapshot.getProperty("device",juce::var()); + const auto graph=snapshot.getProperty("graph",juce::var()); + const auto legacy=snapshot.getProperty("legacyM4",juce::var()); + const auto bus=legacy.getProperty("nativeBus",juce::var()); + const auto epoch=device.getProperty("epoch","0").toString(); + juce::String error; + bool applied=false; + std::uint64_t nativeRev=0,rosterRev=0,requestedEpoch=0,legacyRevision=0; + armix::mixer::ChannelId created{}; + if(!armix::integration::validConsoleRequestId(key)) + error="INVALID_REQUEST_ID"; + else if(completed_.find(key)!=completed_.end()) + error="DUPLICATE_REQUEST_ID"; + else { + if(recentIds_.size()==maxRecentIds) { + completed_.erase(recentIds_.front());recentIds_.pop_front(); + } + recentIds_.push_back(key);completed_.insert(key); + const auto operation=intent.getProperty("operation","").toString(); + const auto payload=intent.getProperty("payload",juce::var()); + // One existing decoder, one native candidate, one PCM publisher. + const auto baseGraph=v8Wire?intent.getProperty("baseGraphRevision",{}) + :intent.getProperty("nativeGraphRevision",{}); + const auto baseRoster=v8Wire?intent.getProperty("baseRosterRevision",{}) + :intent.getProperty("nativeRosterRevision",{}); + const auto legacyBase=v8Wire?legacy.getProperty("routingRevision",{}) + :intent.getProperty("legacyRoutingRevision",{}); + if(ioBusy)error="NATIVE_SHOW_OR_BACKUP_BUSY"; + else if(!decodeDecimal(intent.getProperty("deviceEpoch",{}),requestedEpoch) || + !decodeDecimal(legacyBase,legacyRevision) || + !decodeDecimal(baseGraph,nativeRev) || + !decodeDecimal(baseRoster,rosterRev) || + intent.getProperty("deviceEpoch","").toString()!=epoch || + legacyBase.toString()!=legacy.getProperty("routingRevision","").toString()) + error="STALE_NATIVE_BUS_DEVICE_OR_ROUTE"; + else if(!bus.isObject() || + bus.getProperty("graphRevision","").toString()!=baseGraph.toString() || + bus.getProperty("rosterRevision","").toString()!=baseRoster.toString() || + legacy.getProperty("controlPlane","").toString()!="LEGACY_M4_ORDINAL") + error="NATIVE_BUS_GRAPH_NOT_ADMITTED"; + else if(v8Wire && + (graph.getProperty("revision","").toString()!=baseGraph.toString() || + graph.getProperty("rosterRevision","").toString()!=baseRoster.toString())) + error="STALE_GRAPH_REVISION"; + else if(v8Wire) { + const auto caps=graph.getProperty("capabilities",{}); + const auto ops=caps.getProperty("supportedOps",{}); + const auto* allowed=ops.getArray(); + const auto rows=graph.getProperty("channels",{}); + const auto focus=intent.getProperty("targetChannelId",{}); + armix::mixer::ChannelId parsed{}; + const bool valid=focus.isString() && + armix::integration::parseNativeChannelId( + focus.toString().toStdString(),parsed); + bool admitted=false; + if(valid)if(const auto* channels=rows.getArray()) + for(const auto& row:*channels) + if(row.getProperty("id","").toString()==focus.toString()) + {admitted=true;break;} + if(!admitted || !graph.getProperty("edges",{}).isArray() || + !static_cast(caps.getProperty("callbackOwnsChannelIds",false)) || + !allowed || !allowed->contains(juce::var(juce::String( + "APPLY_WIRE_TRANSACTION")))) + error="UNIVERSAL_WIRE_NOT_ADMITTED"; + } + if(error.isEmpty() && !payload.isObject()) + error="INVALID_NATIVE_BUS_PAYLOAD"; + if(error.isNotEmpty()) { + // Do not touch installed native audio on stale requests. + } else if(operation=="NATIVE_CREATE_CHANNEL" || + operation=="NATIVE_PATCH_CHANNEL") { + if(operation=="NATIVE_CREATE_CHANNEL") { + const auto name=payload.getProperty("name","").toString(); + const auto format=payload.getProperty("format","MONO").toString(); + if(name.isEmpty()||name.length()>64|| + (format!="MONO"&&format!="STEREO")) + error="INVALID_NATIVE_CHANNEL_REQUEST"; + else { + const auto out=engine.createNativeInputChannel( + requestedEpoch,nativeRev,rosterRev,name.toStdString(), + format=="STEREO"?armix::mixer::ProcessingFormat::stereo: + armix::mixer::ProcessingFormat::mono); + applied=out.accepted; + if(!applied)error=out.error; + else {created=out.created;nativeRev=out.pcmRevision; + rosterRev=out.rosterRevision;} + } + }else{ + std::uint64_t id=0; + const auto left=payload.getProperty("physicalLeft",juce::var()); + const auto right=payload.getProperty("physicalRight",juce::var(-1)); + const auto width=payload.getProperty("sourceFormat","MONO").toString(); + if(!decodeDecimal(intent.getProperty("targetChannelId",{}),id)|| + id==0||!left.isInt()||!right.isInt()|| + (width!="MONO"&&width!="STEREO")) + error="INVALID_NATIVE_SOURCE_REQUEST"; + else { + const auto out=engine.patchNativeInputSource( + requestedEpoch,nativeRev,rosterRev, + armix::mixer::ChannelId{id},static_cast(left), + static_cast(right),width=="STEREO"); + applied=out.accepted; + if(!applied)error=out.error; + else {nativeRev=out.pcmRevision; + rosterRev=out.rosterRevision;} + } + } + } + else if(operation=="NATIVE_LOAD_INSERT" || + operation=="NATIVE_SET_INSERT_BYPASS" || + operation=="NATIVE_OPEN_INSERT_EDITOR") { + std::uint64_t target=0; + if(!decodeDecimal(intent.getProperty("targetChannelId",{}),target) || + !target)error="INVALID_NATIVE_VST3_TARGET_ID"; + else { + // Native catalog ownership and VST3 instance preparation + // happen exclusively on the JUCE control thread. + const auto response=onNativeFx( + operation,armix::mixer::ChannelId{target},payload, + requestedEpoch,nativeRev,rosterRev); + applied=response.accepted; + if(!applied)error=response.error; + else {nativeRev=response.pcmRevision; + rosterRev=response.rosterRevision;} + } + } + else if(operation=="NATIVE_SET_CHANNEL_MIX"|| + operation=="NATIVE_SET_CHANNEL_MUTE_SOLO"){ + std::uint64_t id=0; + if(!decodeDecimal(intent.getProperty("targetChannelId",{}),id)||!id) + error="INVALID_DYNAMIC_INPUT_ID"; + else if(operation=="NATIVE_SET_CHANNEL_MIX"){ + const auto g=payload.getProperty("gain",juce::var()); + const auto p=payload.getProperty("pan",juce::var()); + if(!(g.isDouble()||g.isInt())|| + !(p.isDouble()||p.isInt())) + error="INVALID_DYNAMIC_MIX_VALUE"; + else { + const auto gain=static_cast(g); + const auto pan=static_cast(p); + if(!std::isfinite(gain)||gain<0.||gain>4.|| + !std::isfinite(pan)||pan< -1.||pan>1.) + error="INVALID_DYNAMIC_MIX_VALUE"; + else { + applied=engine.setNativeInputMix( + requestedEpoch,nativeRev, + armix::mixer::ChannelId{id}, + static_cast(gain),static_cast(pan)); + if(!applied)error="DYNAMIC_INPUT_MIX_REJECTED"; + } + } + }else{ + const auto m=payload.getProperty("mute",juce::var()); + const auto s=payload.getProperty("solo",juce::var()); + if(!m.isBool()||!s.isBool()) + error="INVALID_DYNAMIC_MUTE_SOLO"; + else { + applied=engine.setNativeInputMuteSolo( + requestedEpoch,nativeRev, + armix::mixer::ChannelId{id}, + static_cast(m),static_cast(s)); + if(!applied)error="DYNAMIC_INPUT_MUTE_SOLO_REJECTED"; + } + } + } + else if(operation=="NATIVE_SET_PRIMARY_OUT") { + std::uint64_t source=0,dest=0; + if(!decodeDecimal(intent.getProperty("targetChannelId",{}),source)|| + !source||!decodeDecimal(payload.getProperty("destinationId",{}),dest)) + error="INVALID_NATIVE_WIRE_ENDPOINT"; + else { + const auto response=engine.setNativePrimaryOutput( + requestedEpoch,nativeRev,rosterRev, + armix::mixer::ChannelId{source}, + armix::mixer::ChannelId{dest}); + applied=response.accepted; + if(!applied)error=response.error; + else {nativeRev=response.pcmRevision; + rosterRev=response.rosterRevision;} + } + } + else if(operation=="NATIVE_APPLY_WIRE_TRANSACTION" || v8Wire) { + using namespace armix::mixer; + const auto raw=payload.getProperty("changes",juce::var()); + const auto* list=raw.getArray(); + if(!list || list->isEmpty() || list->size()>256) + error="INVALID_NATIVE_WIRE_BATCH"; + else { + std::vector changes; + changes.reserve(static_cast(list->size())); + for(const auto& item:*list) { + if(!item.isObject()) { + error="INVALID_NATIVE_WIRE_CHANGE";break; + } + WireChange change; + const auto action=item.getProperty("op","").toString(); + if(action=="CONNECT")change.kind=WireChange::Kind::connect; + else if(action=="REMOVE")change.kind=WireChange::Kind::remove; + else if(action=="RETARGET")change.kind=WireChange::Kind::retarget; + else if(action=="ROUTE_ONLY")change.kind=WireChange::Kind::routeOnly; + else {error="INVALID_NATIVE_WIRE_ACTION";break;} + std::uint64_t source=0,dest=0,edge=0; + if(!decodeDecimal(item.getProperty("from",{}),source) || + source==0) { + error="INVALID_NATIVE_WIRE_SOURCE";break; + } + change.from={source}; + // MAIN focus cannot disconnect someone else's edge. + if(v8Wire && item.getProperty("from",{}).toString()!= + intent.getProperty("targetChannelId",{}).toString()) { + error="UNIVERSAL_WIRE_UNFOCUSED_SOURCE";break; + } + if(change.kind!=WireChange::Kind::remove) { + if(!decodeDecimal(item.getProperty("to",{}),dest) || + dest==0) { + error="INVALID_NATIVE_WIRE_DESTINATION";break; + } + change.to={dest}; + } + if(change.kind==WireChange::Kind::remove || + change.kind==WireChange::Kind::retarget) { + if(!decodeDecimal(item.getProperty("edgeId",{}),edge)|| + edge==0) { + error="INVALID_NATIVE_WIRE_EDGE_ID";break; + } + change.edgeId=edge; + } else { + const auto tap=item.getProperty("tap","POST_FADER").toString(); + const auto gain=item.getProperty("gainLinear",juce::var(1.)); + if(tap!="POST_FADER" || + !(gain.isDouble()||gain.isInt()) || + !std::isfinite(static_cast(gain)) || + static_cast(gain)<0. || + static_cast(gain)>4.) { + error="INVALID_NATIVE_WIRE_GAIN_OR_TAP";break; + } + change.gain=static_cast(static_cast(gain)); + } + changes.push_back(change); + } + if(error.isEmpty()) { + const auto response=engine.applyNativeWireTransaction( + requestedEpoch,nativeRev,rosterRev, + std::span(changes)); + applied=response.accepted; + if(!applied)error=response.error; + else {nativeRev=response.pcmRevision; + rosterRev=response.rosterRevision;} + } + } + } + else if(operation=="NATIVE_SET_BUS_MIX") { + std::uint64_t target=0; + const auto rawGain=payload.getProperty("gain",juce::var()); + const auto rawPan=payload.getProperty("pan",juce::var()); + if(!decodeDecimal(intent.getProperty("targetChannelId",{}),target) || + target==0 || + !(rawGain.isInt()||rawGain.isDouble()) || + !(rawPan.isInt()||rawPan.isDouble())) + error="INVALID_NATIVE_BUS_MIX"; + else { + const auto gain=static_cast(rawGain); + const auto pan=static_cast(rawPan); + if(!std::isfinite(gain)||gain<0.||gain>4. || + !std::isfinite(pan)||pan< -1.||pan>1.) + error="INVALID_NATIVE_BUS_MIX"; + else { + applied=engine.setNativeBusMix( + requestedEpoch,nativeRev, + armix::mixer::ChannelId{target}, + static_cast(gain),static_cast(pan)); + if(!applied)error="NATIVE_BUS_MIX_REJECTED"; + } + } + } + else if(operation!="NATIVE_CREATE_GROUP_SELECTED" && + operation!="NATIVE_CREATE_FX_RETURN_SELECTED" && + operation!="NATIVE_REMOVE_BUS") + error="UNSUPPORTED_NATIVE_BUS_OPERATION"; + else { + using namespace armix::mixer; + std::vector selected; + ChannelId remove{}; + auto role=ChannelRole::group; + juce::String name; + float gain=.25f; + if(operation=="NATIVE_REMOVE_BUS") { + std::uint64_t id=0; + if(!decodeDecimal(intent.getProperty("targetChannelId",{}),id) || + id==0)error="INVALID_NATIVE_BUS_ID"; + else remove={id}; + } else { + role=operation=="NATIVE_CREATE_GROUP_SELECTED" + ?ChannelRole::group:ChannelRole::fxReturn; + name=payload.getProperty("name","").toString(); + const auto raw=payload.getProperty("selectedChannelIds",juce::var()); + const auto* ids=raw.getArray(); + const auto g=payload.getProperty("sendGain",juce::var(.25)); + const double value=static_cast(g); + if(name.isEmpty()||name.length()>64 || + !ids||ids->isEmpty()||ids->size()>64 || + !(g.isDouble()||g.isInt()) || + !std::isfinite(value)||value<0.||value>4.) { + error="INVALID_NATIVE_BUS_SELECTION"; + } else { + gain=static_cast(value); + selected.reserve(static_cast(ids->size())); + for(const auto& item:*ids) { + std::uint64_t id=0; + if(!decodeDecimal(item,id)||id==0) { + error="INVALID_NATIVE_BUS_SOURCE_ID";break; + } + selected.push_back({id}); + } + } + } + if(error.isEmpty()) { + auto result=engine.editNativeBus( + requestedEpoch,nativeRev,rosterRev,role, + std::span(selected),name.toStdString(), + gain,remove); + applied=result.accepted; + if(!applied)error=result.error; + else { + created=result.created; + nativeRev=result.pcmRevision; + rosterRev=result.rosterRevision; + } + } + } + } + // Preserve universal revision 0. Provide native namespace revision + // and created stable ID ONLY after the actual hardware PCM ACK. + PuzzleV8Ack ack; + ack.requestId=key; + ack.status=applied?"ACCEPTED":"REJECTED"; + ack.deviceEpoch=epoch.toStdString(); + ack.graphRevision=v8Wire && applied?std::to_string(nativeRev): + graph.getProperty("revision","0").toString().toStdString(); + ack.rosterRevision=v8Wire && applied?std::to_string(rosterRev): + graph.getProperty("rosterRevision","0").toString().toStdString(); + ack.errorCode=error.toStdString(); + const auto json=PuzzleV8Wire::ack(ack); + auto wire=juce::JSON::parse(juce::String::fromUTF8(json.c_str())); + if(applied)if(auto* object=wire.getDynamicObject()) { + object->setProperty("nativeGraphRevision", + juce::String(std::to_string(nativeRev))); + object->setProperty("nativeRosterRevision", + juce::String(std::to_string(rosterRev))); + object->setProperty("createdChannelId", + juce::String(std::to_string(created.value))); + } + return wire; + } + + static bool parsePortId(const juce::String& wire,const char* prefix,int& physical) { + if(!wire.startsWith(prefix))return false; + const auto text=wire.substring(static_cast(std::char_traits::length(prefix))); + std::uint64_t value=0; + if(!decodeDecimal(juce::var(text),value)||value>255)return false; + physical=static_cast(value); + return true; + } + + static bool decodeDecimal(const juce::var& raw,std::uint64_t& result) noexcept { + if(!raw.isString())return false; + const auto str=raw.toString(); + if(str.isEmpty()||str.length()>20 || + (str.length()>1 && str[0]=='0'))return false; + std::uint64_t n=0; + for(int i=0;i'9')return false; + const auto digit=static_cast(c-'0'); + if(n>(std::numeric_limits::max()-digit)/10)return false; + n=n*10+digit; + } + result=n;return true; + } + +private: + static juce::String decimalFromNative(const juce::var& value) { + if(!(value.isInt()||value.isInt64()))return "0"; + const auto n=static_cast(value); + return n>=0?juce::String(n):juce::String("0"); + } + static constexpr std::size_t maxRecentIds=256; + // Bounded completed IDs on the serialized message thread, never the + // native RT callback. Replayed old requests remain nonmutating in G0. + std::unordered_set completed_; + std::deque recentIds_; +}; +} // namespace armix::console diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index a80004bf0..20bc4039e 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -12,6 +12,7 @@ #include "../engine/device/JuceIndependentClockDevice.h" #include "../engine/device/LiveSecondaryOutputDevice.h" #include "../engine/core/LiveOutputRouteGate.h" +#include "../engine/core/NativeRenderAuthority.h" #include "../engine/device/AsioPriorityDeviceManager.h" #include "../engine/device/AsioRegistryIdentityProbe.h" #include "../engine/device/DirectRouteFence.h" @@ -69,6 +70,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback struct Graph { + // This same Graph owns the original CH1 vendor rack, its bypass + // envelopes and transition scratch, for BOTH M4 and the admitted + // ChannelId external lease. All memory is allocated on CONTROL; + // the audio callback only dereferences the leased Graph*. + Graph() { dryScratch.setSize(2,maxFrames,false,true,false); } + juce::AudioBuffer dryScratch; // Eight 4-bit physical slot indices in one x64 lock-free word. // Moving an insert publishes one complete order for the NEXT audio // block; the processor objects and their binary states never move. @@ -99,8 +106,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { formats_.addFormat (std::make_unique()); scratch_.setSize (2, maxFrames, false, true, false); - // One reusable preallocated stereo dry snapshot for transient FX bypass. - dryScratch_.setSize (2, maxFrames, false, true, false); + // CH1 bypass scratch now belongs to its shared Graph lifetime so + // a ChannelId PCM snapshot can retain the SAME original FX state. handoff_.initialize (graphOwned_.get()); } @@ -633,6 +640,18 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback totalLatency_.store(graphOwned_->latency,std::memory_order_release); handoff_.completeRetirement(); completedSwaps_.fetch_add (1, std::memory_order_relaxed); + // Only after the original host graph is the new accepted owner, + // safely migrate its exact original CH1 VSTs/Orbit and all M4 lanes. + // No plugin is recreated; retain M4 if the hardware is armed, + // stale or PDC disallows this graph. CONTROL/timer thread only. + if(allOutputsDisarmed() && dryRoutingLab_.hasExplicitRoute() && + directFence_.permitted() && !independent_.active()) { + if(auto* device=deviceManager_.getCurrentAudioDevice()) + (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count, + juce::jmax(32,device->getCurrentBufferSizeSamples()), + true,currentOriginalCh1Lease()); + } return true; } @@ -704,6 +723,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { // All checks precede staging: a rejected edit must not alter the // currently audible graph or any accepted route revision. + // An extra native GROUP/FX RETURN has no equivalent M4 fallback. + // Do not silently reroute its sources during an original CH1 + // structural FX edit; remove native BUSes or replace the patch first. + if(dryRoutingLab_.nativeBusTopologyLive())return false; if(!next || !attached_ || !device || independent_.active() || !directFence_.permitted() || handoff_.busy() || fxMovePhase_.load(std::memory_order_acquire)!=0 || @@ -715,6 +738,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return false; prepareFxEditEnvelope(*next,device->getCurrentSampleRate()); stagedOwner_=std::move(next); + // CHANGE of original CH1 ownership must finish on the existing + // M4 buffer-boundary handoff first. Revoke the old native lease; + // once the staged Graph is accepted, re-admit its identical plugin + // state/editor/order into ChannelId without double processing. + dryRoutingLab_.revokeChannelIdPcm(); if(!handoff_.stage(stagedOwner_.get())) { stagedOwner_.reset(); @@ -920,6 +948,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback staged->slots[i].latency); if (!staged->slots[i].bypass) staged->latency += staged->slots[i].latency; } + // Show recall can replace original CH1 owner and all its binary + // plugin state. Revoke ChannelId PCM BEFORE staging the pointer: + // the original handoff then owns the next audible vendor graph. + dryRoutingLab_.revokeChannelIdPcm(); stagedOwner_ = std::move (staged); if (!handoff_.stage (stagedOwner_.get())) { @@ -1028,6 +1060,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const juce::var& command, const LiveDryRoutingLab::FxSelections& fx, const LiveDryRoutingLab::FxRestores* restored=nullptr) { + if (dryRoutingLab_.nativeBusTopologyLive()) + return "REMOVE native GROUP/FX RETURN buses before applying an M4 route"; 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)) @@ -1046,11 +1080,18 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback for(int i=0;icount;++i) if(graphOwned_->slots[i].latency!=0) return "CH1 rack contains a latent VST3: zero-latency settings are required for native multi-channel sends"; - return dryRoutingLab_.apply(command,directFence_.permitted(), - independent_.active(),graphOwned_->count,fx,formats_, - device->getCurrentSampleRate(), - juce::jmax(32,device->getCurrentBufferSizeSamples()), - true,restored); + const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + const auto result=dryRoutingLab_.apply( + command,directFence_.permitted(),independent_.active(), + graphOwned_->count,fx,formats_,device->getCurrentSampleRate(), + frames,true,restored); + // Same original PCM callback/hardware gate; a failed ChannelId + // admission retains the last accepted M4 with original Orbit/Show. + if(result.isEmpty()) + (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count,frames,allOutputsDisarmed(), + currentOriginalCh1Lease()); + return result; } void disableDryRoutingLab() noexcept { setOutputMuted(true); // never expose CH1 unexpectedly on STOP @@ -1058,14 +1099,68 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } juce::String switchDryRoutingLabSource(int strip,std::uint64_t epoch, std::uint64_t revision,const juce::String& mode, - int left,int right) noexcept { + int left,int right) { if(independent_.active()||routeReconfiguring_.load(std::memory_order_acquire)|| handoff_.busy()||!directFence_.permitted()|| diagnosticRoute_.load(std::memory_order_acquire) !=armix::diagnostics::Route::normal|| savedDirectSetup_||savedLiveSetup_) return "SOURCE SWITCH: live DIRECT device or graph unavailable"; - return dryRoutingLab_.switchPhysicalSource(strip,epoch,revision,mode,left,right); + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device)return "SOURCE: active DIRECT audio device unavailable"; + // True first-input SOURCE selection is a control-prepared native graph + // transaction, not a browser-side APPLY or alternate callback. A + // single verified mono capture pin is a supported source. + try { + const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + const auto oldRevision=dryRoutingLab_.revision(); + const auto changed=dryRoutingLab_.repatchPhysicalSource( + strip,epoch,revision,mode,left,right, + directFence_.permitted(),independent_.active(), + graphOwned_->count,formats_,device->getCurrentSampleRate(),frames); + // Same-format SOURCE is an atomic live parameter on BOTH kernels: + // do not rebuild VST3/PCM or interrupt the 64-sample crossfade. + if(changed.isEmpty() && allOutputsDisarmed() && + oldRevision!=dryRoutingLab_.revision()) + (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count,frames,true, + currentOriginalCh1Lease()); + return changed; + } catch(const std::exception& ex) { + return "SOURCE: native prepare failed; prior audio kept: " + juce::String(ex.what()); + } catch(...) { + return "SOURCE: native prepare failed; prior audio kept"; + } + } + // Direct compact OUT / MONO-STEREO operator edits. One existing M4 + // prepared graph is republished; original VST3 instances/Orbit remain + // owned by the same native callback. Never touched on RT. + juce::String repatchDryRoutingLabChannel(int strip,std::uint64_t epoch, + std::uint64_t revision,const juce::String& operation, + const juce::String& value) { + if(independent_.active()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + handoff_.busy()||!directFence_.permitted()|| + diagnosticRoute_.load(std::memory_order_acquire) + !=armix::diagnostics::Route::normal|| + savedDirectSetup_||savedLiveSetup_) + return "CHANNEL PATCH: DIRECT device or VST3 handoff unavailable"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device)return "CHANNEL PATCH: no active native audio interface"; + try { + const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + const auto changed=dryRoutingLab_.repatchChannelStructure( + strip,epoch,revision,operation,value, + directFence_.permitted(),independent_.active(), + graphOwned_->count,formats_,device->getCurrentSampleRate(),frames); + if(changed.isEmpty() && allOutputsDisarmed()) + (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count,frames,true, + currentOriginalCh1Lease()); + return changed; + } catch(...) { + return "CHANNEL PATCH: native preparation failed; previous mix preserved"; + } } bool setDryRoutingLabParameter(int strip,std::uint64_t epoch, std::uint64_t revision,const juce::String& parameter, @@ -1082,13 +1177,49 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return dryRoutingLab_.setAuxBusGain(bus,epoch,revision,gain); } bool setDryRoutingLabAuxSendGain(int source,int bus,std::uint64_t epoch, + std::uint64_t revision,float gain, + armix::mixer::SendTap tap=armix::mixer::SendTap::postFader) noexcept { + if(independent_.active()||routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire) + !=armix::diagnostics::Route::normal|| + !directFence_.permitted()||savedDirectSetup_||savedLiveSetup_) + return false; + return dryRoutingLab_.setAuxSendGain(source,bus,epoch,revision,gain,tap); + } + juce::String connectDryRoutingLabAuxSend(int source,int bus, + std::uint64_t epoch,std::uint64_t revision, + armix::mixer::SendTap tap,float gain,float pan) { + if(independent_.active()||routeReconfiguring_.load(std::memory_order_acquire)|| + handoff_.busy()||!directFence_.permitted()|| + diagnosticRoute_.load(std::memory_order_acquire) + !=armix::diagnostics::Route::normal|| + savedDirectSetup_||savedLiveSetup_) + return "AUX CONNECT: DIRECT device or VST graph handoff unavailable"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device)return "AUX CONNECT: no verified audio interface"; + try { + const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + const auto changed=dryRoutingLab_.connectPreparedAuxSend( + source,bus,epoch,revision,tap,gain,pan, + directFence_.permitted(),independent_.active(),graphOwned_->count, + formats_,device->getCurrentSampleRate(),frames); + if(changed.isEmpty() && allOutputsDisarmed()) + (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count,frames,true, + currentOriginalCh1Lease()); + return changed; + } catch(...) { + return "AUX CONNECT: failed native preparation; previous route retained"; + } + } + bool setDryRoutingLabMonitorSendGain(int source,std::uint64_t epoch, std::uint64_t revision,float gain) noexcept { if(independent_.active()||routeReconfiguring_.load(std::memory_order_acquire)|| diagnosticRoute_.load(std::memory_order_acquire) !=armix::diagnostics::Route::normal|| !directFence_.permitted()||savedDirectSetup_||savedLiveSetup_) return false; - return dryRoutingLab_.setAuxSendGain(source,bus,epoch,revision,gain); + return dryRoutingLab_.setMonitorSendGain(source,epoch,revision,gain); } bool setDryRoutingLabFxBypass(int lane,int slot,std::uint64_t epoch, std::uint64_t revision,const juce::String& instanceId, @@ -1118,6 +1249,190 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } std::uint64_t dryRoutingLabEpoch() const noexcept {return dryRoutingLab_.epoch();} std::uint64_t dryRoutingLabRevision() const noexcept {return dryRoutingLab_.revision();} + // One native ChannelId bus transaction on the installed DIRECT device. + // The GUI only obtains accepted state after successful native publisher + // commit; no speculative UI role or second audio engine. + LiveDryRoutingLab::NativeBusResult editNativeBus( + std::uint64_t epoch,std::uint64_t pcmRevision, + std::uint64_t rosterRevision, + armix::mixer::ChannelRole role, + std::span selected, + const std::string& name,float gain, + armix::mixer::ChannelId remove={}) { + LiveDryRoutingLab::NativeBusResult rejected; + rejected.error="HARDWARE_NOT_DISARMED"; + if(independent_.active() || !attached_ || + !directFence_.permitted() || + routeReconfiguring_.load(std::memory_order_acquire) || + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal || + !allOutputsDisarmed() || handoff_.busy() || + fxMovePhase_.load(std::memory_order_acquire)!=0) + return rejected; + return dryRoutingLab_.editNativeBus( + epoch,pcmRevision,rosterRevision,role,selected, + name,gain,remove,true); + } + // User-owned VST3 on a true dynamic ChannelId. Instantiation/scan/layout + // work is CONTROL only; the callback receives an immutable fx lease. + LiveDryRoutingLab::NativeBusResult installNativeVst3( + std::uint64_t ep,std::uint64_t pcmRevision, + std::uint64_t rosterRevision,armix::mixer::ChannelId id, + const juce::String& path,int uid,const juce::String& catalogId) { + LiveDryRoutingLab::NativeBusResult fail{}; + fail.error="NATIVE_VST3_HOST_UNAVAILABLE"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(independent_.active()||!attached_||!device|| + !directFence_.permitted()||!allOutputsDisarmed()|| + handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return fail; + if(ep!=deviceStartCount_.load(std::memory_order_acquire)) + {fail.error="NATIVE_VST3_DEVICE_CHANGED";return fail;} + const auto rate=device->getCurrentSampleRate(); + const int frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + if(!(rate>0.)||frames>LiveDryRoutingLab::Block::hardFrameLimit) + {fail.error="NATIVE_VST3_UNSUPPORTED_DEVICE_QUANTUM";return fail;} + auto* fmt=formats_.getFormat(0); + if(!fmt||!fmt->fileMightContainThisPluginType(path)) + {fail.error="NATIVE_VST3_MODULE_NOT_FOUND";return fail;} + try { + juce::OwnedArray descriptions; + fmt->findAllTypesForFile(descriptions,path); + juce::PluginDescription* chosen=nullptr; + for(auto* item:descriptions) + if(item&&item->uniqueId==uid&&!item->isInstrument) + {chosen=item;break;} + if(!chosen){fail.error="NATIVE_VST3_IDENTITY_NOT_FOUND";return fail;} + juce::String pluginError; + auto instance=formats_.createPluginInstance(*chosen,rate, + frames,pluginError); + if(!instance){fail.error="NATIVE_VST3_CREATE_FAILED";return fail;} + const auto layout=armix::vst::prepareStereoEffectLayout(*instance); + if(layout.isNotEmpty()){ + fail.error="NATIVE_VST3_INCOMPATIBLE_STEREO_LAYOUT";return fail; + } + instance->prepareToPlay(rate,frames); + if(instance->getLatencySamples()!=0) { + fail.error="NATIVE_VST3_REQUIRES_PDC";return fail; + } + auto lease=std::make_shared< + armix::mixer::LiveChannelFxGraph::FxInstance>( + std::move(instance),catalogId,chosen->name, + LiveDryRoutingLab::Block::hardFrameLimit); + return dryRoutingLab_.attachNativeInsert(ep,pcmRevision, + rosterRevision,id,catalogId,std::move(lease),true); + } catch(...) { + fail.error="NATIVE_VST3_VENDOR_PREPARE_FAILED";return fail; + } + } + bool bypassNativeVst3(std::uint64_t epoch,std::uint64_t revision, + armix::mixer::ChannelId id,std::size_t slot, + const juce::String& token,bool bypass) noexcept { + return dryRoutingLab_.bypassNativeInsert(epoch,revision,id,slot, + token,bypass); + } + armix::mixer::LiveChannelFxGraph::InstanceLease leaseNativeVst3Editor( + std::uint64_t epoch,std::uint64_t revision, + armix::mixer::ChannelId id,std::size_t slot, + const juce::String& token) const noexcept { + return dryRoutingLab_.leaseNativeInsertEditor( + epoch,revision,id,slot,token); + } + + LiveDryRoutingLab::NativeBusResult createNativeInputChannel( + std::uint64_t epoch,std::uint64_t pcmRevision, + std::uint64_t rosterRevision,const std::string& name, + armix::mixer::ProcessingFormat format) { + LiveDryRoutingLab::NativeBusResult fail; + fail.error="HARDWARE_NOT_DISARMED"; + if(independent_.active()||!attached_||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal || + !allOutputsDisarmed()||handoff_.busy()|| + fxMovePhase_.load(std::memory_order_acquire)!=0) + return fail; + return dryRoutingLab_.createNativeInputChannel( + epoch,pcmRevision,rosterRevision,name,format,true); + } + LiveDryRoutingLab::NativeBusResult patchNativeInputSource( + std::uint64_t epoch,std::uint64_t pcmRevision, + std::uint64_t rosterRevision,armix::mixer::ChannelId channel, + int left,int right,bool stereo) { + LiveDryRoutingLab::NativeBusResult fail; + fail.error="HARDWARE_NOT_DISARMED"; + if(independent_.active()||!attached_||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal || + !allOutputsDisarmed()||handoff_.busy()|| + fxMovePhase_.load(std::memory_order_acquire)!=0) + return fail; + return dryRoutingLab_.patchNativeInputSource( + epoch,pcmRevision,rosterRevision,channel,left,right,stereo,true); + } + LiveDryRoutingLab::NativeBusResult setNativePrimaryOutput( + std::uint64_t ep,std::uint64_t pcmRev,std::uint64_t rosterRev, + armix::mixer::ChannelId src,armix::mixer::ChannelId dst) { + LiveDryRoutingLab::NativeBusResult fail; + fail.error="HARDWARE_NOT_DISARMED"; + if(independent_.active()||!attached_||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal|| + !allOutputsDisarmed()||handoff_.busy()|| + fxMovePhase_.load(std::memory_order_acquire)!=0)return fail; + return dryRoutingLab_.setNativePrimaryOutput( + ep,pcmRev,rosterRev,src,dst,true); + } + // JUCE control-thread gateway to the already installed ChannelId renderer. + // No callback detach or alternate route ownership. Preserve device, + // original vendor VST3 leases and physical output-arm safety gates. + LiveDryRoutingLab::NativeBusResult applyNativeWireTransaction( + std::uint64_t ep,std::uint64_t pcmRev,std::uint64_t rosterRev, + std::span changes) { + LiveDryRoutingLab::NativeBusResult fail; + fail.error="NATIVE_WIRE_DEVICE_NOT_READY"; + if(independent_.active()||!attached_||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal|| + handoff_.busy()|| + fxMovePhase_.load(std::memory_order_acquire)!=0) + return fail; + return dryRoutingLab_.applyNativeWireTransaction( + ep,pcmRev,rosterRev,changes); + } + bool setNativeInputMix(std::uint64_t epoch,std::uint64_t rev, + armix::mixer::ChannelId id,float gain,float pan) noexcept { + if(independent_.active()||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.setNativeInputMix(epoch,rev,id,gain,pan); + } + bool setNativeInputMuteSolo(std::uint64_t epoch,std::uint64_t rev, + armix::mixer::ChannelId id,bool mute,bool solo) noexcept { + if(independent_.active()||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.setNativeInputMuteSolo(epoch,rev,id,mute,solo); + } + bool nativeBusTopologyLive() const noexcept { + return dryRoutingLab_.nativeBusTopologyLive(); + } + bool setNativeBusMix(std::uint64_t epoch, + std::uint64_t revision, + armix::mixer::ChannelId id,float gain,float pan) noexcept { + if(independent_.active()||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire) || + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.setNativeBusMix(epoch,revision,id,gain,pan); + } bool dryRoutingLabActive() const noexcept {return dryRoutingLab_.active();} void pollDryRoutingLab() noexcept {dryRoutingLab_.poll();} @@ -1436,8 +1751,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback armix::device::LiveSecondaryOutputDevice secondaryOutput_; std::optional savedDirectSetup_; juce::AudioPluginFormatManager formats_; - std::unique_ptr graphOwned_ {std::make_unique()}; - std::unique_ptr stagedOwner_; + // Strong ownership stays on CONTROL. The admitted native ChannelId + // snapshot may retain exactly this Graph while the vendor plugin, Show + // state and editor remain alive through an in-flight callback. + // Handoff still publishes Graph* atomically; no shared_ptr on AUDIO. + std::shared_ptr graphOwned_ {std::make_shared()}; + std::shared_ptr stagedOwner_; armix::rt::LiveGraphHandoff handoff_; // 0 idle, 1 fade-out, 2 fade-in. One controller producer, one RT reader. // No allocation, plugin re-instantiation or extra processing pass. @@ -1445,7 +1764,6 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback std::atomic fxMovePendingOrder_ {Graph::canonicalOrder}; bool attached_ = false; juce::AudioBuffer scratch_; - juce::AudioBuffer dryScratch_; armix::dsp::NativeMasterLoudness masterLoudness_; armix::diagnostics::DiagnosticTone diagnosticTone_; LiveDryRoutingLab dryRoutingLab_; @@ -1599,36 +1917,30 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback outputPeak_.store (0.f); } - // R0 bridge: existing CH1 multi-insert vendor state/Orbit stays owned by - // the live FX handoff. The audio callback holds its Cycle lease throughout - // this render pass, so an old plugin graph cannot retire in mid-block. - // This is a temporary ownership adapter until all inserts are represented - // by the same native multi-lane graph; not a second rendering engine. - struct LegacyChannelOneLease final { LiveAudioEngine* host; Graph* graph; }; - static void processLegacyChannelOne(void* token,int lane,float* left, - float* right,int frames) noexcept + // ONE original CH1 rack processor for M4 compatibility and the native + // ChannelId external lease. Graph lifetime is owned by CONTROL and the + // accepted publisher, never acquired or released inside audio callback. + static void renderOriginalChannelOneGraph(Graph& graph,float* left, + float* right,int frames) noexcept { - if(lane!=0 || !token || !left || !right || frames<=0 || frames>maxFrames)return; - const auto& lease=*static_cast(token); - auto* const host=lease.host; - auto* const graph=lease.graph; - if(!host || !graph || graph->count<=0)return; + if(!left||!right||left==right||frames<=0||frames>maxFrames|| + graph.count<=0)return; float* channels[]{left,right}; juce::AudioBuffer buffer(channels,2,frames); juce::MidiBuffer midi; - const auto order=graph->orderPacked.load(std::memory_order_acquire); - for(int logical=0;logicalcount;++logical) + const auto order=graph.orderPacked.load(std::memory_order_acquire); + for(int logical=0;logicalslots[physical]; + auto& slot=graph.slots[physical]; if(!slot.processor)continue; - auto& bypass=graph->bypassEnvelope[physical]; - bypass.request(graph->bypassFlags[physical].load(std::memory_order_acquire)); + auto& bypass=graph.bypassEnvelope[physical]; + bypass.request(graph.bypassFlags[physical].load(std::memory_order_acquire)); const bool blend=bypass.transitioning(); if(blend) { - juce::FloatVectorOperations::copy(host->dryScratch_.getWritePointer(0),left,frames); - juce::FloatVectorOperations::copy(host->dryScratch_.getWritePointer(1),right,frames); + juce::FloatVectorOperations::copy(graph.dryScratch.getWritePointer(0),left,frames); + juce::FloatVectorOperations::copy(graph.dryScratch.getWritePointer(1),right,frames); } if(bypass.shouldProcessWet()) { @@ -1642,8 +1954,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } if(blend) { - const float* dryL=host->dryScratch_.getReadPointer(0); - const float* dryR=host->dryScratch_.getReadPointer(1); + const float* dryL=graph.dryScratch.getReadPointer(0); + const float* dryR=graph.dryScratch.getReadPointer(1); for(int i=0;i(token)->graph; + if(graph)renderOriginalChannelOneGraph(*graph,left,right,frames); + } + + // Native external FX is a raw callback on the EXACT shared Graph owner + // bound by UnifiedLegacyProductionAdmission. The snapshot owns the + // strong reference and validates context==owner.get() off realtime. + static void processOwnedChannelOne(void* token,float* left, + float* right,int frames) noexcept + { + if(token)renderOriginalChannelOneGraph( + *static_cast(token),left,right,frames); + } + armix::mixer::DynamicChannelFxLeaseBank::ExternalLease + currentOriginalCh1Lease() const noexcept { + armix::mixer::DynamicChannelFxLeaseBank::ExternalLease fx; + if(!graphOwned_||graphOwned_->count<=0)return fx; + // Native PRE/POST/AUX cannot accept the original external rack + // with latent inserts until graph-wide PDC exists. A missing lease + // keeps the original M4 callback audible without false admission. + for(int i=0;icount;++i) + if(graphOwned_->slots[i].latency!=0)return fx; + fx.owner=std::static_pointer_cast(graphOwned_); // CONTROL + fx.context=graphOwned_.get(); + fx.render=&processOwnedChannelOne; + // id is bound from the compiled native ChannelId roster, NEVER a + // guessed display index/port; no native owner can be misdirected. + return fx; + } + void audioDeviceIOCallbackWithContext ( const float* const* inputs, int inputChannels, float* const* outputs, int outputChannels, int samples, const juce::AudioIODeviceCallbackContext&) override @@ -1680,6 +2029,13 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback std::memory_order_relaxed); return; } + // ONE explicit owner for the whole device callback. The GUI cannot + // select an experimental ChannelId renderer or revive stereo CH1. + // Cutover to universal will replace this authority transaction only + // after the full VST3/Show/epoch proof, never add a parallel callback. + const auto renderOwner=armix::mixer::NativeRenderAuthority::select( + activeDiagnosticRoute==armix::diagnostics::Route::normal, + dryRoutingLab_.active()); const auto cycle = handoff_.beginCycle(); // R0B B3: production NORMAL audio has a single native routing owner. // Until a device-epoch-validated 10CH/4AUX route is published, output @@ -1690,8 +2046,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Keep the existing FX graph handoff progressing even when unpatched: // a staged ADD/REMOVE must ACK and retire on the callback thread. // Only atomic reads and deterministic output writes; no RT heap or I/O. - if (activeDiagnosticRoute == armix::diagnostics::Route::normal - && !dryRoutingLab_.active()) + if (renderOwner == + armix::mixer::NativeRenderOwner::failSilentUnpatched) { // P0: SILENT output must not mean blind capture diagnostics. // A verified ASIO/WASAPI callback can carry PCM before any @@ -1746,7 +2102,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // action, with an immutable preallocated P1D graph. Its own zero-VST // callback path NEVER falls through to CH1 on stale/hotplug routes. // DirectFence was already checked above; no output to unknown device. - if (dryRoutingLab_.active()) + if (renderOwner == + armix::mixer::NativeRenderOwner::acceptedM4Session) { const auto outputGate=armix::mixer::LiveOutputRouteGate::evaluate( dryRoutingLab_.active(), @@ -1767,7 +2124,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Both native 10CH routing and the existing CH1 vendor FX chain // execute in ONE stereo output render pass. Never mix a parallel // CH1 output on top or copy vendor processors into another graph. - LegacyChannelOneLease ch1Lease{this,cycle.graph}; + LegacyChannelOneLease ch1Lease{cycle.graph}; std::array nativeMainPair{{-1,-1}}; std::array nativeMonitorPair{{-1,-1}}; const bool routed=dryRoutingLab_.process(inputs,inputChannels,outputs, @@ -1867,13 +2224,16 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::FloatVectorOperations::clear(outputs[channel],samples); return; } + // The only remaining stereo renderer is DIAGNOSTIC. It may emit + // a bounded test tone or test capture but never host channel VST3 + // or become a fallback production mixer. + jassert(armix::mixer::NativeRenderAuthority::mayRunDiagnostic( + renderOwner)); const bool enabled = monitor_.load (std::memory_order_relaxed) && !routeReconfiguring_.load (std::memory_order_acquire); const auto route = diagnosticRoute_.load (std::memory_order_relaxed); const bool toneTest = route == armix::diagnostics::Route::outputOnlyTone; const bool captureTest = route == armix::diagnostics::Route::captureOnly; - const bool dry = dryTest_.load (std::memory_order_relaxed) - || route != armix::diagnostics::Route::normal; if (toneTest && outputChannels > 0) testOutputFrames_.fetch_add (static_cast (samples), std::memory_order_relaxed); if (captureTest && inputChannels > 0) @@ -1903,10 +2263,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { const int frames = juce::jmin (maxFrames, samples - offset); // Preallocated backing store: no resizing/capacity bookkeeping in RT. - // Two-channel AudioBuffer view refers to scratch_ without ownership. - // JUCE uses its inline channel pointer storage for two channels. - juce::AudioBuffer scratchView ( - scratch_.getArrayOfWritePointers(), 2, frames); + // Test-only stereo buffers are preallocated. There is no VST + // buffer view or plugin dispatch in the diagnostic-only path. if (toneTest) { auto* left = scratch_.getWritePointer (0); @@ -1930,55 +2288,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback for (int i = 0; i < frames; ++i) if (!toneTest) inPeak = juce::jmax (inPeak, std::abs (dst[i])); } - // MIDI capacity is empty unless the plugin itself changes it. - juce::MidiBuffer midi; - if (!dry) - { - // One atomic order snapshot per block: stable physical FX and bypass identity. - const auto order = cycle.graph->orderPacked.load (std::memory_order_acquire); - for (int fx = 0; fx < cycle.graph->count; ++fx) - { - const int physical = Graph::physicalAt (order, fx); - auto& slot = cycle.graph->slots[physical]; - if (!slot.processor) {midi.clear();continue;} - auto& bypass=cycle.graph->bypassEnvelope[physical]; - bypass.request(cycle.graph->bypassFlags[physical].load(std::memory_order_acquire)); - // Steady wet/dry requires no copy or extra arithmetic. - // A transition temporarily snapshots the exact input to - // this insert; a second full FX graph is never created. - const bool blend=bypass.transitioning(); - if (blend) - for(int ch=0;ch<2;++ch) - juce::FloatVectorOperations::copy( - dryScratch_.getWritePointer(ch), - scratch_.getReadPointer(ch),frames); - if (bypass.shouldProcessWet()) - { - const auto pluginBeginUs = clockMicros(); - slot.processor->processBlock (scratchView, midi); - const auto pluginUs = clockMicros() - pluginBeginUs; - lastPluginUsBySlot_[physical].store (pluginUs, std::memory_order_relaxed); - publishMax (worstPluginUsBySlot_[physical], pluginUs); - publishMax (worstPluginUs_, pluginUs); - if (static_cast (pluginUs) > periodUs * 0.75) - slowPlugins_.fetch_add (1, std::memory_order_relaxed); - } - if (blend) - { - float* wetL=scratch_.getWritePointer(0); - float* wetR=scratch_.getWritePointer(1); - const float* dryL=dryScratch_.getReadPointer(0); - const float* dryR=dryScratch_.getReadPointer(1); - for(int i=0;i #include @@ -61,6 +65,7 @@ class LiveDryRoutingLab final { // JUCE calls aboutToStart after configuring the input/output device. // One device session gets a new epoch; stored route cannot survive it. void prepareDevice (juce::AudioIODevice* device) noexcept { + channelIdPcmEpoch_.store(0,std::memory_order_release); const auto generation=deviceEpoch_.fetch_add(1,std::memory_order_acq_rel)+1; userPatched_.store(false,std::memory_order_release); registryValid_.store(false,std::memory_order_release); @@ -90,6 +95,7 @@ class LiveDryRoutingLab final { registryValid_.store(true,std::memory_order_release); } void deviceStopped() noexcept { + channelIdPcmEpoch_.store(0,std::memory_order_release); // A stale lab cannot silently resume legacy CH1 on device hotplug. userPatched_.store(false,std::memory_order_release); deviceEpoch_.fetch_add(1,std::memory_order_acq_rel); @@ -132,12 +138,19 @@ class LiveDryRoutingLab final { return "Clear the active input patch before creating an unpatched session"; if(active() && ready() && !hasExplicitRoute())return {}; auto request=std::make_unique(); + // New silent sessions use typed v2 from the first callback so the + // operator can choose MONO/STEREO processing BEFORE a physical IN. + // Old saved v1 Shows remain readable by NativeDryRouteCommand. + request->setProperty("schemaVersion",2); request->setProperty("deviceEpoch",static_cast(epoch())); request->setProperty("revision",static_cast(revision())); juce::Array channels; for(int i=0;i(); row->setProperty("mode","NONE"); + row->setProperty("sourceKind","NONE"); + row->setProperty("sourceFormat","NONE"); + row->setProperty("channelFormat","STEREO"); row->setProperty("left",-1); row->setProperty("right",-1); row->setProperty("gain",0.25); @@ -162,6 +175,12 @@ class LiveDryRoutingLab final { juce::AudioPluginFormatManager& formats, double sampleRate,int deviceFrames,bool explicitSelection=true, const FxRestores* restores=nullptr) { + // E5: the M4 compiler cannot encode an admitted native GROUP/FX RETURN. + // An M4 APPLY, Show recall or structural SOURCE/AUX edit must not + // erase native BUS PCM while its ChannelId graph owns the callback. + // After real device reopen a new epoch can start with a clean roster. + if(nativeStructureLive_ && nativeAccepted_.deviceEpoch==epoch()) + return "REMOVE native GROUP/FX RETURN buses before replacing the M4 route"; // Called by the native message thread only. Not callable from RT. if(!directPermitted || independentClock) return "Dry Routing LAB requires one verified DIRECT audio device"; @@ -399,6 +418,9 @@ class LiveDryRoutingLab final { if(!registryValid_.load(std::memory_order_acquire) || epochAtPublish!=currentEpoch) return "Audio device changed before routing publication"; + // New M4 routing must not render against an older ChannelId graph. + // Output must remain disarmed throughout structural native APPLY. + channelIdPcmEpoch_.store(0,std::memory_order_release); const auto result=publisher_.publish(std::move(next),expectedRevision,epochAtPublish); switch(result) { case Publisher::Result::applied: @@ -411,6 +433,11 @@ class LiveDryRoutingLab final { // displays an acknowledged immutable copy; draft changes // never update this until graph publication succeeds. acceptedRoute_=explicitSelection?command:juce::var(); + // Retain the REAL prepared (possibly UNPATCHED/SILENT) M4 + // input topology so a single native SOURCE selection can + // compile the first mono route. No UI draft is authoritative. + sourceTemplate_=command; + acceptedFxSelections_=selections; // Release-store only AFTER a valid immutable graph publishes. // Even if OUTPUT is mistakenly armed, unpatched renders never // enter ANY channel/master vendor DSP or produce sound. @@ -479,6 +506,25 @@ class LiveDryRoutingLab final { return "SOURCE SWITCH: native graph rejected same-format input"; // This is the authoritative native parameter target, not an // unacknowledged browser draft. The callback fades PCM over 64 samples. + if(channelIdPhysicalPcmActive()) { + const auto id=nativeAccepted_.graph.ids.inputs[strip]; + if(!nativePublisher_.setPhysicalSource( + expectedEpoch,nativeAccepted_.pcmRevision,id, + callbackLeft,mode=="STEREO"?callbackRight:-1, + mode=="STEREO"))rejectedNativeMirror(); + else { + // Physical SOURCE changes are LIVE atomic controls. Persist + // the actual callback ordinals for the NEXT Group/FX Return + // structural compile rather than reusing stale APPLY pins. + auto& patches=nativeAccepted_.graph.request.sources; + const auto found=std::find_if(patches.begin(),patches.end(), + [id](const auto& patch){return patch.id==id;}); + if(found!=patches.end()) { + found->inputL=callbackLeft; + found->inputR=mode=="STEREO"?callbackRight:-1; + } + } + } if(auto* object=row.getDynamicObject()){ object->setProperty("left",physicalLeft); object->setProperty("right",mode=="STEREO"?physicalRight:-1); @@ -486,6 +532,207 @@ class LiveDryRoutingLab final { return {}; } + // A source changing from NONE to MONO/STEREO needs a new prepared + // topology. A source changing physical pin within the same format uses + // the existing zero-heap atomic source switch above. Both cases are + // handled through ONE native command and ONE ACK, not GUI APPLY wizard. + // All heavy preparation/reuse and deep cloning happen on message thread. + juce::String repatchPhysicalSource(int strip,std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,const juce::String& mode, + int physicalLeft,int physicalRight,bool directPermitted, + bool independentClock,int occupiedCh1Fx, + juce::AudioPluginFormatManager& formats,double sampleRate, + int deviceFrames) + { + if(!ready() || !registryValid_.load(std::memory_order_acquire) || + topologyFault_.load(std::memory_order_acquire) || + expectedEpoch!=epoch() || expectedRevision!=revision() || + !sourceTemplate_.isObject()) + return "SOURCE: native device, graph or accepted template stale"; + const auto sourceRows=sourceTemplate_.getProperty("channels",juce::var()); + const auto* rows=sourceRows.getArray(); + if(!rows || strip<0 || strip>=count || rows->size()!=count) + return "SOURCE: target channel unavailable"; + // Preserve the proven live-safe atomic path for an already scheduled + // channel. Never force a vendor graph rebuild for ordinary pin moves. + if(hasExplicitRoute() && + rows->getReference(strip).getProperty("mode",{}).toString()==mode) + return switchPhysicalSource(strip,expectedEpoch,expectedRevision, + mode,physicalLeft,physicalRight); + const int available=portCount_.load(std::memory_order_acquire); + if(available<=0||available>armix::device::LiveInputPortRegistry::limit) + return "SOURCE: driver did not verify active capture pins"; + std::array pins{}; + for(int i=0;i(available)}, + expectedEpoch,expectedRevision,staged); + if(error.isNotEmpty())return error; + return publishRevisedTopology(staged,expectedEpoch,expectedRevision, + directPermitted,independentClock,occupiedCh1Fx,formats, + sampleRate,deviceFrames); + } + + // One-click channel OUT and format: the existing native M4 routing/FX + // graph is the sole PCM owner. Prepare OUT/format on the JUCE control + // thread, then publish with exactly the same epoch/VST3 lease/Show + // rollback transaction as SOURCE. No device restart or UI-side routing. + juce::String repatchChannelStructure(int strip, + std::uint64_t expectedEpoch,std::uint64_t expectedRevision, + const juce::String& operation,const juce::String& requested, + bool directPermitted,bool independentClock,int occupiedCh1Fx, + juce::AudioPluginFormatManager& formats,double sampleRate, + int deviceFrames) { + if(!ready()||!registryValid_.load(std::memory_order_acquire)|| + topologyFault_.load(std::memory_order_acquire)|| + epoch()!=expectedEpoch||revision()!=expectedRevision|| + !sourceTemplate_.isObject()) + return "CHANNEL PATCH: native device or graph is stale"; + if(strip<0||strip>=count) + return "CHANNEL PATCH: invalid native channel"; + // This preserves all source pins, AUX taps, master and monitor + // destinations, original VST3 vendor state and all other channels. + auto staged=juce::JSON::parse(juce::JSON::toString(sourceTemplate_,false)); + if(!staged.isObject())return "CHANNEL PATCH: cannot clone accepted graph"; + auto rows=staged.getProperty("channels",juce::var()); + auto* list=rows.getArray(); + if(!list||list->size()!=count|| + !list->getReference(strip).isObject()) + return "CHANNEL PATCH: no accepted channel row"; + auto* row=list->getReference(strip).getDynamicObject(); + if(operation=="SET_PRIMARY_OUT") { + if(requested!="MAIN"&&requested!="NONE") + return "CHANNEL PATCH: only MAIN and NONE are installed M4 outputs"; + row->setProperty("main",requested=="MAIN"); + } else if(operation=="SET_PROCESSING_FORMAT") { + if(requested!="MONO"&&requested!="STEREO") + return "CHANNEL PATCH: processing format must be MONO or STEREO"; + const auto schema=staged.getProperty("schemaVersion",juce::var()); + if(!schema.isInt() || static_cast(schema)!=2) + return "CHANNEL PATCH: typed processing format requires native schema v2"; + row->setProperty("channelFormat",requested); + } else return "CHANNEL PATCH: unsupported graph operation"; + return publishRevisedTopology(staged,expectedEpoch,expectedRevision, + directPermitted,independentClock,occupiedCh1Fx,formats, + sampleRate,deviceFrames); + } + + // Operator one-action AUX send connection: prepare a real parallel + // edge in the SAME M4 graph that owns the channel VST3/AUX rack. + // The recipient must already own a genuine prepared effect. An empty + // AUX summed into MAIN doubles the dry path and is rejected. + juce::String connectPreparedAuxSend(int source,int bus, + std::uint64_t expectedEpoch,std::uint64_t expectedRevision, + armix::mixer::SendTap tap,float gain,float pan, + bool directPermitted,bool independentClock,int occupiedCh1Fx, + juce::AudioPluginFormatManager& formats,double sampleRate, + int deviceFrames) { + if(!hasExplicitRoute()||!ready()||!registryValid_.load(std::memory_order_acquire)|| + epoch()!=expectedEpoch||revision()!=expectedRevision|| + topologyFault_.load(std::memory_order_acquire)|| + source<0||source>=count||bus<0||bus>=auxCount|| + (tap!=armix::mixer::SendTap::preFader&& + tap!=armix::mixer::SendTap::postFader)|| + !std::isfinite(gain)||gain<0.f||gain>1.f|| + !std::isfinite(pan)||pan< -1.f||pan>1.f) + return "AUX CONNECT: invalid source, send or stale native graph"; + const auto* old=publisher_.controlPrepared(expectedEpoch,expectedRevision); + if(!old||old->insertsOn(count+bus)<=0) + return "AUX CONNECT: insert a real effect on AUX first; an empty return doubles dry MAIN"; + auto staged=juce::JSON::parse(juce::JSON::toString(sourceTemplate_,false)); + if(!staged.isObject())return "AUX CONNECT: accepted topology unavailable"; + const auto lanes=staged.getProperty("channels",juce::var()); + const auto* sources=lanes.getArray(); + if(!sources||sources->size()!=count|| + sources->getReference(source).getProperty("mode","NONE").toString()=="NONE") + return "AUX CONNECT: select a verified physical source first"; + auto aux=staged.getProperty("auxes",juce::var()); + if(aux.isVoid()) { + juce::Array defaults; + for(int b=0;b(); + row->setProperty("enabled",false); + row->setProperty("main",true); + row->setProperty("mute",false); + row->setProperty("gain",1.0); + defaults.add(juce::var(row.release())); + } + staged.getDynamicObject()->setProperty("auxes",juce::var(defaults)); + aux=staged.getProperty("auxes",juce::var()); + } + auto* auxes=aux.getArray(); + if(!auxes||auxes->size()!=auxCount)return "AUX CONNECT: corrupt return roster"; + auto* returnRow=auxes->getReference(bus).getDynamicObject(); + if(!returnRow)return "AUX CONNECT: invalid return"; + if(!static_cast(returnRow->getProperty("enabled"))) { + returnRow->setProperty("enabled",true); + returnRow->setProperty("main",true); // one-click parallel effect to MAIN + } + auto rawSends=staged.getProperty("sends",juce::var()); + if(rawSends.isVoid()) { + staged.getDynamicObject()->setProperty("sends", + juce::var(juce::Array{})); + rawSends=staged.getProperty("sends",juce::var()); + } + auto* sendRows=rawSends.getArray(); + if(!sendRows)return "AUX CONNECT: invalid accepted sends"; + juce::DynamicObject* existing=nullptr; + for(auto& item:*sendRows) { + if(static_cast(item.getProperty("from",-1))==source && + static_cast(item.getProperty("to",-1))==count+bus) { + existing=item.getDynamicObject(); + if(!existing)return "AUX CONNECT: invalid existing edge"; + break; + } + } + if(!existing) { + if(sendRows->size()>=armix::mixer::maxChannelSends) + return "AUX CONNECT: send capacity exhausted"; + auto row=std::make_unique(); + existing=row.get(); + sendRows->add(juce::var(row.release())); + } + existing->setProperty("from",source); + existing->setProperty("to",count+bus); + existing->setProperty("tap",tap==armix::mixer::SendTap::preFader?"PRE":"POST"); + existing->setProperty("gain",static_cast(gain)); + existing->setProperty("pan",static_cast(pan)); + return publishRevisedTopology(staged,expectedEpoch,expectedRevision, + directPermitted,independentClock,occupiedCh1Fx,formats, + sampleRate,deviceFrames); + } + + // Both SOURCE and channel structure edits share one graph compiler, + // VST3 lease policy and rollback path. Keep fast faders/pan/mute/solo + // on their separate atomic parameter path without any compilation. + juce::String publishRevisedTopology(juce::var& staged, + std::uint64_t expectedEpoch,std::uint64_t expectedRevision, + bool directPermitted,bool independentClock,int occupiedCh1Fx, + juce::AudioPluginFormatManager& formats,double sampleRate, + int deviceFrames) { + auto stagedRows=staged.getProperty("channels",juce::var()); + auto* editable=stagedRows.getArray(); + if(!editable||editable->size()!=count) + return "CHANNEL PATCH: malformed native topology"; + for(int i=0;igetReference(i).getDynamicObject(); + if(!row)return "CHANNEL PATCH: missing native channel"; + const auto& c=channelEdits_[i]; + row->setProperty("gain",static_cast(c.linear)); + row->setProperty("pan",static_cast(c.pan)); + row->setProperty("mute",c.mute); + row->setProperty("solo",c.solo); + } + if(expectedEpoch!=epoch()||expectedRevision!=revision()|| + !registryValid_.load(std::memory_order_acquire)) + return "CHANNEL PATCH: device changed; previous mix preserved"; + return apply(staged,directPermitted,independentClock,occupiedCh1Fx, + acceptedFxSelections_,formats,sampleRate,deviceFrames,true); + } + // Native live control path. Only the JUCE message thread writes. No // graph recompilation, VST3 instantiation or callback detach. // Browser carries the exact acknowledged route token to reject stale @@ -507,6 +754,22 @@ class LiveDryRoutingLab final { if(name=="mute")updated.mute=value>0.5f; else updated.solo=value>0.5f; }else return false; + // The admitted native ChannelId graph is the ONLY active PCM control + // authority. Reject before changing legacy M4 DSP or claiming ACK. + if(channelIdPhysicalPcmActive()) { + if(nativeStructureLive_)return false; // old ordinal is now stale + const auto id=nativeAccepted_.graph.ids.inputs[strip]; + const bool accepted=(name=="mute"||name=="solo") + ?setNativeInputMuteSolo(expectedEpoch,nativeAccepted_.pcmRevision, + id,updated.mute,updated.solo) + :setNativeInputMix(expectedEpoch,nativeAccepted_.pcmRevision, + id,updated.linear,updated.pan); + if(!accepted)return false; + channelEdits_[strip]=updated; // CONTROL-thread Show/re-admission baseline + return true; + } + if(nativeStructureLive_ || nativeControlDirty_)return false; + // Legacy M4 is still the installed PCM owner before native cutover. if(!publisher_.updateActiveControl(expectedEpoch,expectedRevision, [&](FxGraph& fx) noexcept { return fx.setStripControl(strip,updated.linear,updated.pan, @@ -516,12 +779,15 @@ class LiveDryRoutingLab final { return true; } - // Operator M1: one POST gain is a realtime PARAMETER, never topology. - // The accepted send identity must exist and match THIS device epoch. + // Real AUX FX RETURN: one existing PRE or POST send has an independent + // realtime level. The tap/destination/edge identity are immutable here. + // A single render of source PCM, vendor VST, and AUX return remains + // authoritative on the installed JUCE callback. // The UI may adjust it while physical output is ARMED; no new plugin, // graph, callback or device restart occurs. bool setAuxSendGain(int source,int bus,std::uint64_t expectedEpoch, - std::uint64_t expectedRevision,float gain) noexcept { + std::uint64_t expectedRevision,float gain, + armix::mixer::SendTap tap=armix::mixer::SendTap::postFader) noexcept { if(source<0||source>=count||bus<0||bus>=auxCount|| !std::isfinite(gain)||gain<0.f||gain>1.f|| !ready()||!hasExplicitRoute()|| @@ -533,16 +799,27 @@ class LiveDryRoutingLab final { for(auto& item:*list) { if(static_cast(item.getProperty("from",-1))==source && static_cast(item.getProperty("to",-1))==count+bus && - item.getProperty("tap",{}).toString()=="POST") { + item.getProperty("tap",{}).toString()== + (tap==armix::mixer::SendTap::preFader?"PRE":"POST")) { accepted=&item;break; } } if(!accepted)return false; // No implicit creation of an AUX edge. if(!publisher_.updateActiveControl(expectedEpoch,expectedRevision, [&](FxGraph& fx) noexcept { - return fx.setAuxSendGain(source,bus,gain); + return fx.setAuxSendGain(source,bus,tap,gain); }))return false; accepted->getDynamicObject()->setProperty("gain",static_cast(gain)); + if(channelIdPhysicalPcmActive()) { + const auto id=nativeAccepted_.graph.ids.inputs[source]; + const auto target=nativeAccepted_.graph.ids.aux[bus]; + const bool pre=tap==armix::mixer::SendTap::preFader; + if(!nativePublisher_.setParallelSendGain( + expectedEpoch,nativeAccepted_.pcmRevision, + id,target,pre,gain))rejectedNativeMirror(); + else nativeAccepted_.graph.roster.rememberLiveParallelSend( + id,target,pre,gain); + } return true; } @@ -563,6 +840,96 @@ class LiveDryRoutingLab final { return false; if(auto* obj=(*arr)[bus].getDynamicObject()) obj->setProperty("gain",static_cast(gain)); + if(channelIdPhysicalPcmActive()) { + const auto id=nativeAccepted_.graph.ids.aux[bus]; + if(!nativePublisher_.setChannelMix( + expectedEpoch,nativeAccepted_.pcmRevision, + id,gain,0.f))rejectedNativeMirror(); + else nativeAccepted_.graph.roster.rememberLiveMix(id,gain,0.f); + } + return true; + } + + // Independent physical MONITOR/CUE bus: control only changes one + // existing send's target. PRE/POST AUX and MAIN VST PCM remain unchanged. + // If no verified distinct MONITOR output pair exists, reject. + bool setMonitorSendGain(int source,std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,float gain) noexcept { + if(source<0||source>=fxSlots||!std::isfinite(gain)|| + gain<0.f||gain>1.f||!hasExplicitRoute()|| + expectedEpoch!=epoch()||expectedRevision!=revision()) + return false; + auto gains=acceptedRoute_.getProperty("monitorSends",juce::var()); + auto* array=gains.getArray(); + const auto* current=publisher_.controlPrepared(expectedEpoch,expectedRevision); + if(!array||array->size()!=fxSlots||!current|| + !current->monitorEnabled())return false; + if(!publisher_.updateActiveControl(expectedEpoch,expectedRevision, + [&](FxGraph& fx) noexcept { + return fx.setMonitorSendGain(source,gain); + }))return false; + array->set(source,static_cast(gain)); // same accepted topology + if(channelIdPhysicalPcmActive()) { + const auto id=source laneIds, + armix::mixer::DynamicChannelFxLeaseBank& destination, + juce::String& error) const { + using Bank=armix::mixer::DynamicChannelFxLeaseBank; + if(laneIds.size()!=static_cast(fxSlots) || + !hasExplicitRoute() || !ready() || + expectedEpoch!=epoch() || expectedRevision!=revision()) { + error="M5: native epoch/revision or 10CH+4AUX FX roster stale"; + return false; + } + const FxGraph* current=publisher_.controlPrepared(expectedEpoch,expectedRevision); + if(!current) { + error="M5: no current M4 prepared vendor FX graph"; + return false; + } + std::vector staged; + staged.reserve(fxSlots); + for(int lane=0;lane(lane)], + format,*current,slot)) { + error="M5: failed to retain M4 VST3 token for lane "+ + juce::String(lane); + return false; + } + staged.push_back(std::move(slot)); + } + const auto fault=Bank::prepare(expectedEpoch,expectedRevision,staged, + destination); + if(fault!=Bank::Fault::none) { + error="M5: ChannelId VST lease migration rejected, fault "+ + juce::String(static_cast(fault)); + return false; + } + error.clear(); return true; } @@ -630,7 +997,820 @@ class LiveDryRoutingLab final { return {}; } + + // E2: ACTUAL hardware callback cutover for the admitted fixed 10CH+4AUX + // topology, retaining original per-lane JUCE VST3 leases and Show state. + // This CONTROL-only transaction uses real sparse driver port masks and + // the same physical destinations already validated by the M4 owner. + // Occupied original CH1/Orbit is leased as its existing shared Graph, + // including the exact atomic bypass, FX order, state, tail and editor. + // The published ChannelId snapshot retains this owner until RT retires. + bool admitChannelIdFromAcceptedM4(int occupiedExternalCh1Fx, + int deviceFrames,bool outputsDisarmed, + armix::mixer::DynamicChannelFxLeaseBank::ExternalLease externalCh1={}) { + // E5: a native BUS uses topology that M4 cannot represent. Never + // demote its renderer on an unsupported legacy re-admission. + if((nativeStructureLive_ || nativeControlDirty_) && + nativeAccepted_.deviceEpoch==epoch()) + return false; + // Otherwise the last ACCEPTED M4 graph is the safe physical fallback + // if migration rejects. This also handles a successfully replaced M4 + // route whose new ChannelId candidate cannot be prepared. + channelIdPcmEpoch_.store(0,std::memory_order_release); + nativeStructureLive_=false; + try { + if(!outputsDisarmed || occupiedExternalCh1Fx<0 || + (occupiedExternalCh1Fx>0)!=externalCh1.populated() || + !hasExplicitRoute()||!ready() || + topologyFault_.load(std::memory_order_acquire)) + return false; + const auto generation=epoch(),m4Revision=revision(); + const auto* old=publisher_.controlPrepared(generation,m4Revision); + if(!old || deviceFrames<=0) return false; + armix::mixer::NativeDryRouteCommand decoded; + juce::String problem; + if(!armix::mixer::NativeDryRouteCommand::decode( + acceptedRoute_,decoded,problem))return false; + // A native IN is a callback ordinal, not the numerical physical + // port label. Preserve original order including sparse ASIO pins. + const int inputs=portCount_.load(std::memory_order_acquire); + if(inputs<=0||inputs>armix::device::LiveInputPortRegistry::limit) + return false; + std::array ports{}; + for(int i=0;imainOutputLeft();hw.mainR=old->mainOutputRight(); + hw.monitorEnabled=old->monitorEnabled(); + if(hw.monitorEnabled) { + hw.monitorL=old->monitorOutputLeft(); + hw.monitorR=old->monitorOutputRight(); + } + std::array monitor{}; + if(hw.monitorEnabled) { + const auto gains=acceptedRoute_.getProperty("monitorSends",juce::var()); + const auto* list=gains.getArray(); + if(!list||list->size()!=fxSlots)return false; + for(int i=0;i( + static_cast(list->getReference(i))); + } + // The previous publisher belongs to another device generation. + // Retire it only on CONTROL, never from JUCE's device callback. + if(nativeAccepted_.deviceEpoch!=generation && + nativePublisher_.acceptedRevision()!=0) + nativePublisher_.unpublish(); + const int frames=juce::jmax(32,juce::jmin( + deviceFrames,old->maxFramesPerPlugin())); + auto applied=armix::mixer::UnifiedLegacyProductionAdmission::compileAndCommit( + decoded.channels,{ports.data(),static_cast(inputs)}, + decoded.sends,decoded.aux,monitor,*old, + occupiedExternalCh1Fx>0,hw, + frames,32u*1024u*1024u, + nativePublisher_.acceptedRevision(),generation,epoch(), + true,nativePublisher_,nativeAccepted_,std::move(externalCh1)); + if(!applied.ok() || generation!=epoch() || m4Revision!=revision()) + return false; // selected M4 PCM owns the safe fallback + nativeControlDirty_=false; // fresh accepted legacy/native control baseline + channelIdPcmEpoch_.store(generation,std::memory_order_release); + return true; + } catch(...) { + // Failure is on CONTROL; the original M4/Orbit graph remains + // valid and is the only callback PCM renderer selected. + return false; + } + } + // The accepted original four AUX/FX RETURNS are fixed M4-owned lanes. + // Generic roster.removeBus() accepts any FX_RETURN; this physical host + // must protect their actual stable IDs, not rely on role/display order. + bool originalM4Aux(armix::mixer::ChannelId id) const noexcept { + for(const auto aux:nativeAccepted_.graph.ids.aux) + if(aux.value && aux==id)return true; + return false; + } + // E3: structural native GROUP/FX RETURN transaction on the SAME + // accepted physical ChannelId publisher. This is the CONTROL writer, + // not a second graph/audio callback or a simulated Console mutation. + // An error leaves the last accepted roster, plugin leases and PCM intact. + struct NativeBusResult final { + bool accepted=false; + armix::mixer::ChannelId created{}; + std::uint64_t pcmRevision=0,rosterRevision=0; + const char* error="NATIVE_GRAPH_NOT_READY"; + }; + // A real VST3 instance is prepared in LiveAudioEngine on CONTROL before + // this call. ChannelId roster, actual processor lease and the one PCM + // renderer commit as ONE accepted native revision. Previous sound/owner + // survives plugin validation, routing or publication failure. + NativeBusResult attachNativeInsert( + std::uint64_t expectedEpoch,std::uint64_t expectedPcmRevision, + std::uint64_t expectedRosterRevision,armix::mixer::ChannelId target, + const juce::String& catalogId, + armix::mixer::DynamicChannelFxLeaseBank::Lease processor, + bool outputsDisarmed=false) { + using namespace armix::mixer; + NativeBusResult out{}; + out.pcmRevision=nativeAccepted_.pcmRevision; + out.rosterRevision=nativeAccepted_.graph.roster.revision(); + if(!channelIdPhysicalPcmActive()||!ready()|| + expectedEpoch!=epoch()||nativeAccepted_.deviceEpoch!=expectedEpoch|| + !nativeAccepted_.fxOwners||!processor||!processor->processor|| + expectedPcmRevision!=nativeAccepted_.pcmRevision|| + expectedRosterRevision!=nativeAccepted_.graph.roster.revision()) + return out; + if(!outputsDisarmed) {out.error="OUTPUT_MUST_BE_DISARMED";return out;} + const auto* current=nativeAccepted_.graph.roster.find(target); + if(!current || (current->role!=ChannelRole::input && + current->role!=ChannelRole::group)) { + out.error="NATIVE_INSERT_TARGET_UNAVAILABLE";return out; + } + // The fixed 10 CH/4 AUX rack remains owned by M4/Show while migrating. + // Never replace or double-render one of its vendor instances. + for(const auto id:nativeAccepted_.graph.ids.inputs) + if(id==target){out.error="M4_INSERT_USE_EXISTING_RACK";return out;} + if(originalM4Aux(target)){ + out.error="M4_INSERT_USE_EXISTING_RACK";return out; + } + if(catalogId.isEmpty()||catalogId.getNumBytesAsUTF8()>256) { + out.error="INVALID_VST3_CATALOG_ID";return out; + } + try { + auto next=nativeAccepted_.graph.roster; + // LiveDryRoutingLab also defines a legacy ChannelEdit; explicitly + // select the ChannelId roster action, not the M4 routing type. + armix::mixer::ChannelEdit add; + add.kind=armix::mixer::ChannelEdit::Kind::addInsertReference; + add.id=target;add.text=catalogId.toStdString(); + const std::array edits{add}; + if(!next.edit(expectedRosterRevision,edits).ok()) { + out.error="NATIVE_INSERT_CAPACITY_REJECTED";return out; + } + DynamicChannelFxLeaseBank prepared; + const auto fault=DynamicChannelFxLeaseBank::appendOwned( + expectedEpoch,expectedPcmRevision+1,*nativeAccepted_.fxOwners, + target,current->format,std::move(processor),prepared); + if(fault!=DynamicChannelFxLeaseBank::Fault::none) { + out.error="NATIVE_VST3_LEASE_PREPARE_REJECTED";return out; + } + auto owner=std::make_shared( + std::move(prepared)); + DynamicNativeSessionPublisher::FxPlan fx; + fx.owner=std::static_pointer_cast(owner); + fx.context=owner.get(); + fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept{ + (*static_cast(ctx))(id,l,r,n); + }; + fx.deviceEpoch=expectedEpoch; + fx.graphRevision=expectedPcmRevision+1; + const auto published=nativePublisher_.commit( + next,nativeAccepted_.graph.request,expectedPcmRevision, + expectedEpoch,epoch(),true,std::move(fx)); + if(!published.ok()) { + out.error="NATIVE_VST3_PCM_COMMIT_REJECTED";return out; + } + nativeAccepted_.graph.roster=std::move(next); + nativeAccepted_.fxOwners=std::move(owner); + nativeAccepted_.pcmRevision=published.revision; + nativeStructureLive_=true; // M4 Show cannot represent new inserts. + nativeMeterEpoch_.store(0,std::memory_order_release); + out.accepted=true;out.error=""; + out.pcmRevision=published.revision; + out.rosterRevision=nativeAccepted_.graph.roster.revision(); + out.created=target; + return out; + } catch(...) { + out.error="NATIVE_VST3_ADMISSION_FAILED";return out; + } + } + bool bypassNativeInsert(std::uint64_t epochAtEdit,std::uint64_t pcmRevision, + armix::mixer::ChannelId target,std::size_t slot, + const juce::String& token,bool bypass) noexcept { + return nativeAccepted_.setFxBypass(nativePublisher_,epochAtEdit, + pcmRevision,target,slot,token,bypass); + } + armix::mixer::DynamicChannelFxLeaseBank::Lease leaseNativeInsertEditor( + std::uint64_t epochAtEdit,std::uint64_t pcmRevision, + armix::mixer::ChannelId target,std::size_t slot, + const juce::String& token) const noexcept { + return nativeAccepted_.leaseFxEditor(nativePublisher_,epochAtEdit, + pcmRevision,target,slot,token); + } + + NativeBusResult editNativeBus(std::uint64_t expectedEpoch, + std::uint64_t expectedPcmRevision, + std::uint64_t expectedRosterRevision, + armix::mixer::ChannelRole role, + std::span selection, + const std::string& name,float sendGain, + armix::mixer::ChannelId remove={}, + bool outputsDisarmed=false) { + using namespace armix::mixer; + NativeBusResult reply{}; + reply.pcmRevision=nativeAccepted_.pcmRevision; + reply.rosterRevision=nativeAccepted_.graph.roster.revision(); + if(!channelIdPhysicalPcmActive() || !ready() || + expectedEpoch!=epoch() || nativeAccepted_.deviceEpoch!=expectedEpoch || + !nativeAccepted_.fxOwners || + expectedPcmRevision!=nativeAccepted_.pcmRevision || + expectedRosterRevision!=nativeAccepted_.graph.roster.revision()) + return reply; + if(!outputsDisarmed) { + reply.error="OUTPUT_MUST_BE_DISARMED";return reply; + } + // A new FX_RETURN has no attached native VST3 owner yet. Reusing + // the old lease bank cannot create an insert for the new ChannelId: + // its parallel input would be routed back as extra DRY PCM. Until + // INSERT/REMOVE FX is transactional for dynamic BUSes, reject + // creation instead of offering a falsely wet, louder return. + // Original M4 AUX 1-4 remain true processed FX return paths. + if(!remove.value && role==ChannelRole::fxReturn) { + reply.error="FX_RETURN_REQUIRES_NATIVE_VST3_OWNER";return reply; + } + if(remove.value && originalM4Aux(remove)) { + reply.error="FIXED_M4_AUX_NOT_REMOVABLE";return reply; + } + try { + auto next=nativeAccepted_.graph.roster; // CONTROL only + ChannelEditResult changed; + if(remove.value) { + changed=next.removeBusAndRestoreSources( + expectedRosterRevision,remove); + } else if(selection.empty()) { + changed=next.createStandaloneBus( + expectedRosterRevision,name,role); + } else { + changed=next.createBusForSelected( + expectedRosterRevision,selection,name,role,sendGain); + } + if(!changed.ok()) { + reply.error="INVALID_NATIVE_BUS_EDIT";return reply; + } + // The bank is a revision-bound immutable map of actual VST3 + // owners. Reuse every current instance incl. original CH1 + // without duplicating, releasing or instantiating a processor. + DynamicChannelFxLeaseBank bank; + if(DynamicChannelFxLeaseBank::reuseRevision( + expectedEpoch,expectedPcmRevision+1, + *nativeAccepted_.fxOwners,bank)!= + DynamicChannelFxLeaseBank::Fault::none) { + reply.error="NATIVE_FX_LEASE_REJECTED";return reply; + } + auto owner=std::make_shared( + std::move(bank)); + DynamicNativeSessionPublisher::FxPlan fx; + fx.owner=std::static_pointer_cast(owner); + fx.context=owner.get(); + fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(ctx))(id,l,r,n); + }; + fx.deviceEpoch=expectedEpoch; + fx.graphRevision=expectedPcmRevision+1; + const auto published=nativePublisher_.commit( + next,nativeAccepted_.graph.request,expectedPcmRevision, + expectedEpoch,epoch(),true,std::move(fx)); + if(!published.ok()) { + reply.error="NATIVE_PCM_COMMIT_REJECTED";return reply; + } + nativeAccepted_.graph.roster=std::move(next); + nativeAccepted_.fxOwners=std::move(owner); + nativeAccepted_.pcmRevision=published.revision; + // From now on original fixed M4 cannot express the extra BUS. + // The native publisher remains the authoritative PCM, and a + // failed scalar mirror MUST fault silent rather than reselect + // an incompatible legacy route. + nativeStructureLive_=nativeAccepted_.graph.roster.size()> + static_cast(fxSlots+1+ + (nativeAccepted_.hardware.monitorEnabled?1:0)); + reply.accepted=true;reply.error=""; + reply.pcmRevision=published.revision; + reply.rosterRevision=nativeAccepted_.graph.roster.revision(); + if(!changed.createdIds.empty())reply.created=changed.createdIds[0]; + return reply; + } catch(...) { + reply.error="NATIVE_BUS_PREPARE_FAILED";return reply; + } + } + + // Product Console: a NEW stable ChannelId input, not a fixed M4 ordinal + // or an unowned JS strip. Starts unpatched and silent. Structural graph, + // old vendor FX leases and MAIN routing publish as ONE control transaction. + NativeBusResult createNativeInputChannel(std::uint64_t expectedEpoch, + std::uint64_t expectedPcmRevision,std::uint64_t expectedRosterRevision, + const std::string& name,armix::mixer::ProcessingFormat format, + bool outputsDisarmed=false) { + using namespace armix::mixer; + NativeBusResult reply{}; + reply.pcmRevision=nativeAccepted_.pcmRevision; + reply.rosterRevision=nativeAccepted_.graph.roster.revision(); + if(!outputsDisarmed){reply.error="OUTPUT_MUST_BE_DISARMED";return reply;} + if(!channelIdPhysicalPcmActive()||!ready()|| + expectedEpoch!=epoch()||nativeAccepted_.deviceEpoch!=expectedEpoch|| + !nativeAccepted_.fxOwners|| + expectedPcmRevision!=nativeAccepted_.pcmRevision|| + expectedRosterRevision!=nativeAccepted_.graph.roster.revision()) + return reply; + if(name.empty()||name.size()>64 || + (format!=ProcessingFormat::mono&&format!=ProcessingFormat::stereo)){ + reply.error="INVALID_NATIVE_CHANNEL";return reply; + } + try { + auto roster=nativeAccepted_.graph.roster; + const auto& existing=roster.channels(); + const auto main=std::find_if(existing.begin(),existing.end(), + [](const auto& r){return r.role==ChannelRole::main;}); + if(main==existing.end()) { + reply.error="NATIVE_MAIN_NOT_FOUND";return reply; + } + armix::mixer::ChannelEdit add; + add.kind=armix::mixer::ChannelEdit::Kind::add;add.role=ChannelRole::input; + add.format=format;add.text=name; + add.connectMainOnCreate=true; // exact one real POST_FADER MAIN edge + add.position=static_cast(main-existing.begin()); + // One accepted roster revision and ONE prepared PCM publication, + // not create + second independent OUT routing mutation. + auto created=roster.edit(expectedRosterRevision, + std::span(&add,1)); + if(!created.ok()||created.createdIds.size()!=1) { + reply.error="CHANNEL_MAIN_ADMISSION_REJECTED";return reply; + } + DynamicChannelFxLeaseBank bank; + if(DynamicChannelFxLeaseBank::reuseRevision( + expectedEpoch,expectedPcmRevision+1, + *nativeAccepted_.fxOwners,bank)!= + DynamicChannelFxLeaseBank::Fault::none) { + reply.error="NATIVE_FX_LEASE_REJECTED";return reply; + } + auto owner=std::make_shared(std::move(bank)); + DynamicNativeSessionPublisher::FxPlan fx; + fx.owner=std::static_pointer_cast(owner); + fx.context=owner.get(); + fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(ctx))(id,l,r,n); + }; + fx.deviceEpoch=expectedEpoch; + fx.graphRevision=expectedPcmRevision+1; + const auto published=nativePublisher_.commit( + roster,nativeAccepted_.graph.request,expectedPcmRevision, + expectedEpoch,epoch(),true,std::move(fx)); + if(!published.ok()) { + reply.error="CHANNEL_PCM_COMMIT_REJECTED";return reply; + } + nativeAccepted_.graph.roster=std::move(roster); + nativeAccepted_.fxOwners=std::move(owner); + nativeAccepted_.pcmRevision=published.revision; + nativeStructureLive_=true; // M4 can no longer represent CH11+ + reply.accepted=true;reply.error=""; + reply.created=created.createdIds.front(); + reply.pcmRevision=published.revision; + reply.rosterRevision=nativeAccepted_.graph.roster.revision(); + return reply; + }catch(...){ + reply.error="CHANNEL_NATIVE_PREPARE_FAILED";return reply; + } + } + + // Wire a verified physical capture pin to a dynamically CREATED input. + // M4-owned CH1–10 keep the original device/VST continuity contract. + // Prepared topology + lease revision is published once; never patch an + // active callback's source vector or create an audio JS path. + NativeBusResult patchNativeInputSource(std::uint64_t expectedEpoch, + std::uint64_t expectedPcmRevision,std::uint64_t expectedRosterRevision, + armix::mixer::ChannelId channel,int physicalLeft, + int physicalRight,bool stereo,bool outputsDisarmed=false) { + using namespace armix::mixer; + NativeBusResult reply{}; + reply.pcmRevision=nativeAccepted_.pcmRevision; + reply.rosterRevision=nativeAccepted_.graph.roster.revision(); + if(!outputsDisarmed){reply.error="OUTPUT_MUST_BE_DISARMED";return reply;} + if(!channelIdPhysicalPcmActive()||!ready()|| + expectedEpoch!=epoch()||nativeAccepted_.deviceEpoch!=expectedEpoch|| + !nativeAccepted_.fxOwners|| + expectedPcmRevision!=nativeAccepted_.pcmRevision|| + expectedRosterRevision!=nativeAccepted_.graph.roster.revision()) + return reply; + const auto* target=nativeAccepted_.graph.roster.find(channel); + if(!target||target->role!=ChannelRole::input||!nativeStructureLive_) { + reply.error="NOT_DYNAMIC_INPUT";return reply; + } + for(const auto id:nativeAccepted_.graph.ids.inputs) + if(channel==id) {reply.error="M4_INPUT_NOT_DYNAMIC";return reply;} + int l=-1,r=-1; + for(int i=0;i(std::move(bank)); + DynamicNativeSessionPublisher::FxPlan fx; + fx.owner=std::static_pointer_cast(owner); + fx.context=owner.get(); + fx.render=+[](void* ctx,ChannelId id,float* left,float* right,int n) noexcept { + (*static_cast(ctx))(id,left,right,n); + }; + fx.deviceEpoch=expectedEpoch;fx.graphRevision=expectedPcmRevision+1; + const auto published=nativePublisher_.commit( + nativeAccepted_.graph.roster,request,expectedPcmRevision, + expectedEpoch,epoch(),true,std::move(fx)); + if(!published.ok()) { + reply.error="NATIVE_INPUT_PCM_COMMIT_REJECTED";return reply; + } + nativeAccepted_.graph.request=std::move(request); + nativeAccepted_.fxOwners=std::move(owner); + nativeAccepted_.pcmRevision=published.revision; + reply.accepted=true;reply.error=""; + reply.pcmRevision=published.revision; + reply.rosterRevision=nativeAccepted_.graph.roster.revision(); + return reply; + }catch(...){ + reply.error="NATIVE_SOURCE_PREPARE_FAILED";return reply; + } + } + // CONTROL-only primary OUT/WIRE transaction: stable ChannelId routing, + // native graph DAG validation and immutable PCM publication. + NativeBusResult setNativePrimaryOutput(std::uint64_t ep, + std::uint64_t expectedPcmRev,std::uint64_t expectedRosterRev, + armix::mixer::ChannelId src,armix::mixer::ChannelId dst, + bool outputsDisarmed=false) { + using namespace armix::mixer; + NativeBusResult r{}; + r.pcmRevision=nativeAccepted_.pcmRevision; + r.rosterRevision=nativeAccepted_.graph.roster.revision(); + if(!outputsDisarmed){r.error="OUTPUT_MUST_BE_DISARMED";return r;} + if(!nativeStructureLive_||!channelIdPhysicalPcmActive()||!ready()|| + ep!=epoch()||nativeAccepted_.deviceEpoch!=ep|| + !nativeAccepted_.fxOwners|| + expectedPcmRev!=nativeAccepted_.pcmRevision|| + expectedRosterRev!=nativeAccepted_.graph.roster.revision())return r; + const auto* source=nativeAccepted_.graph.roster.find(src); + const auto* target=nativeAccepted_.graph.roster.find(dst); + if(!source||(source->role!=ChannelRole::input&& + source->role!=ChannelRole::group)|| + (dst.value&&(!target||(target->role!=ChannelRole::main&& + target->role!=ChannelRole::group)))||src==dst){ + r.error="INVALID_NATIVE_WIRE_ENDPOINT";return r; + } + for(const auto id:nativeAccepted_.graph.ids.inputs) + if(id==src){r.error="M4_INPUT_ROUTE_NOT_DYNAMIC";return r;} + if(originalM4Aux(src)){r.error="M4_AUX_ROUTE_NOT_DYNAMIC";return r;} + try { + auto roster=nativeAccepted_.graph.roster; + armix::mixer::ChannelEdit edit; + edit.kind=armix::mixer::ChannelEdit::Kind::setPrimaryOutput; + edit.id=src;edit.target=dst; + if(!roster.edit(expectedRosterRev, + std::span(&edit,1)).ok()){ + r.error="NATIVE_WIRE_ROUTE_REJECTED";return r; + } + DynamicChannelFxLeaseBank nextBank; + if(DynamicChannelFxLeaseBank::reuseRevision( + ep,expectedPcmRev+1,*nativeAccepted_.fxOwners,nextBank)!= + DynamicChannelFxLeaseBank::Fault::none){ + r.error="NATIVE_WIRE_FX_LEASE_REJECTED";return r; + } + auto owner=std::make_shared(std::move(nextBank)); + DynamicNativeSessionPublisher::FxPlan fx; + fx.owner=std::static_pointer_cast(owner); + fx.context=owner.get(); + fx.render=+[](void* ctx,ChannelId id,float* l,float* rr,int n) noexcept{ + (*static_cast(ctx))(id,l,rr,n); + }; + fx.deviceEpoch=ep;fx.graphRevision=expectedPcmRev+1; + const auto published=nativePublisher_.commit( + roster,nativeAccepted_.graph.request,expectedPcmRev, + ep,epoch(),true,std::move(fx)); + if(!published.ok()){ + r.error="NATIVE_WIRE_PCM_GRAPH_REJECTED";return r; + } + nativeAccepted_.graph.roster=std::move(roster); + nativeAccepted_.fxOwners=std::move(owner); + nativeAccepted_.pcmRevision=published.revision; + nativeMeterEpoch_.store(0,std::memory_order_release); + r.accepted=true;r.error=""; + r.pcmRevision=published.revision; + r.rosterRevision=nativeAccepted_.graph.roster.revision(); + return r; + }catch(...){ + r.error="NATIVE_WIRE_PREPARE_FAILED";return r; + } + } + + + // Real installed ChannelId PCM transaction. No alternate router: compile + // the accepted roster's SAME send inventory, lease the SAME native VST3 + // processors and publish once to the JUCE callback's existing publisher. + // M4 cannot represent arbitrary WIRE afterwards; never downgrade it. + NativeBusResult applyNativeWireTransaction( + std::uint64_t ep,std::uint64_t expectedPcmRev, + std::uint64_t expectedRosterRev, + std::span changes) { + using namespace armix::mixer; + NativeBusResult r{}; + r.pcmRevision=nativeAccepted_.pcmRevision; + r.rosterRevision=nativeAccepted_.graph.roster.revision(); + // This method has NO physical request argument. Always publish + // the previously accepted identical source/clock configuration. + if(!channelIdPhysicalPcmActive()||!ready()|| + ep!=epoch()||nativeAccepted_.deviceEpoch!=ep|| + !nativeAccepted_.fxOwners|| + expectedPcmRev!=nativeAccepted_.pcmRevision|| + expectedRosterRev!=nativeAccepted_.graph.roster.revision()) { + r.error="STALE_NATIVE_WIRE_GRAPH";return r; + } + if(changes.empty()||changes.size()>256){ + r.error="INVALID_NATIVE_WIRE_BATCH";return r; + } + try { + auto roster=nativeAccepted_.graph.roster; + const auto changed=roster.wireTransaction(expectedRosterRev,changes); + if(!changed.ok()){ + r.error="NATIVE_WIRE_TRANSACTION_REJECTED";return r; + } + DynamicChannelFxLeaseBank bank; + if(DynamicChannelFxLeaseBank::reuseRevision( + ep,expectedPcmRev+1,*nativeAccepted_.fxOwners,bank)!= + DynamicChannelFxLeaseBank::Fault::none){ + r.error="NATIVE_WIRE_FX_LEASE_REJECTED";return r; + } + auto owner=std::make_shared(std::move(bank)); + DynamicNativeSessionPublisher::FxPlan fx; + fx.owner=std::static_pointer_cast(owner); + fx.context=owner.get(); + fx.render=+[](void* ctx,ChannelId id,float* l,float* rr,int n) noexcept { + (*static_cast(ctx))(id,l,rr,n); + }; + fx.deviceEpoch=ep; + fx.graphRevision=expectedPcmRev+1; + const auto published=nativePublisher_.commit( + roster,nativeAccepted_.graph.request,expectedPcmRev, + ep,epoch(),false,std::move(fx),true); + if(!published.ok()){ + r.error="NATIVE_WIRE_PCM_GRAPH_REJECTED";return r; + } + nativeAccepted_.graph.roster=std::move(roster); + nativeAccepted_.fxOwners=std::move(owner); + nativeAccepted_.pcmRevision=published.revision; + nativeStructureLive_=true; // never fall back to incompatible M4 + nativeMeterEpoch_.store(0,std::memory_order_release); + r.accepted=true;r.error=""; + r.pcmRevision=published.revision; + r.rosterRevision=nativeAccepted_.graph.roster.revision(); + return r; + }catch(...){ + r.error="NATIVE_WIRE_PREPARE_FAILED";return r; + } + } + + // E6: Original migrated CH1-10 AND added dynamic INPUTs are driven + // by the same installed ChannelId publisher, callback and VST3 lease. + // Identity/epoch/revision gates precede any audible DSP mutation. + bool setNativeInputMix(std::uint64_t epochValue,std::uint64_t revision, + armix::mixer::ChannelId id,float gain,float pan) noexcept { + if(!channelIdPhysicalPcmActive()|| + nativeAccepted_.deviceEpoch!=epochValue|| + epochValue!=epoch()||revision!=nativeAccepted_.pcmRevision|| + !std::isfinite(gain)||gain<0.f||gain>4.f|| + !std::isfinite(pan)||pan< -1.f||pan>1.f)return false; + const auto* channel=nativeAccepted_.graph.roster.find(id); + if(!channel||channel->role!=armix::mixer::ChannelRole::input)return false; + if(!nativePublisher_.setChannelMix(epochValue,revision,id,gain,pan)) + return false; + if(!nativeAccepted_.graph.roster.rememberLiveMix(id,gain,pan)) { + topologyFault_.store(true,std::memory_order_release); + return false; // never ACK a rendered state missing from readback + } + nativeControlDirty_=true; + return true; + } + bool setNativeInputMuteSolo(std::uint64_t epochValue,std::uint64_t revision, + armix::mixer::ChannelId id, + bool mute,bool solo) noexcept { + if(!channelIdPhysicalPcmActive()|| + nativeAccepted_.deviceEpoch!=epochValue|| + epochValue!=epoch()||revision!=nativeAccepted_.pcmRevision)return false; + const auto* channel=nativeAccepted_.graph.roster.find(id); + if(!channel||channel->role!=armix::mixer::ChannelRole::input)return false; + if(!nativePublisher_.setChannelMuteSolo( + epochValue,revision,id,mute,solo))return false; + if(!nativeAccepted_.graph.roster.rememberLiveMuteSolo(id,mute,solo)) { + topologyFault_.store(true,std::memory_order_release); + return false; + } + nativeControlDirty_=true; + return true; + } + + bool nativeBusTopologyLive() const noexcept { + return nativeStructureLive_ && channelIdPhysicalPcmActive(); + } + // Live bus controls update only verified ChannelIds and their canonical + // roster values. Group/FX RETURN faders are actual post-insert PCM, + // not a browser-only knob or duplicated legacy M4 strip. + bool setNativeBusMix(std::uint64_t epochAtEdit, + std::uint64_t expectedPcmRevision, + armix::mixer::ChannelId id,float gain,float pan) noexcept { + if(!channelIdPhysicalPcmActive() || epochAtEdit!=epoch() || + expectedPcmRevision!=nativeAccepted_.pcmRevision)return false; + const auto* channel=nativeAccepted_.graph.roster.find(id); + if(!channel || (channel->role!=armix::mixer::ChannelRole::group && + channel->role!=armix::mixer::ChannelRole::fxReturn) || + originalM4Aux(id)) + return false; // original AUX 1–4 belong to M4 control state + if(!nativePublisher_.setChannelMix( + epochAtEdit,expectedPcmRevision,id,gain,pan))return false; + return nativeAccepted_.graph.roster.rememberLiveMix(id,gain,pan); + } + + // CONTROL snapshot: genuine stable ChannelIds from the SAME publisher + // as physical PCM. No guessed IDs, synthetic UI routes or JS DSP. + juce::var nativeBusStatus() const { + if(!channelIdPhysicalPcmActive() || !nativeAccepted_.fxOwners)return {}; + const auto* routing=nativePublisher_.acceptedRouting( + epoch(),nativeAccepted_.pcmRevision); + if(!routing)return {}; + auto state=std::make_unique(); + state->setProperty("graphRevision",juce::String( + std::to_string(nativeAccepted_.pcmRevision))); + state->setProperty("rosterRevision",juce::String( + std::to_string(routing->rosterRevision))); + state->setProperty("structural",nativeStructureLive_); + juce::Array allowed; + // Only expose operations backed by a real DSP lease. Dynamic + // FX_RETURN insertion is not available until a native VST3 owner + // can be prepared for its new ChannelId; do not advertise it. + for(const char* op: {"NATIVE_CREATE_GROUP_SELECTED", + "NATIVE_REMOVE_BUS","NATIVE_SET_BUS_MIX", + "NATIVE_CREATE_CHANNEL","NATIVE_PATCH_CHANNEL", + "NATIVE_SET_PRIMARY_OUT", + "NATIVE_APPLY_WIRE_TRANSACTION", + "NATIVE_SET_CHANNEL_MIX", + "NATIVE_SET_CHANNEL_MUTE_SOLO", + "NATIVE_LOAD_INSERT","NATIVE_SET_INSERT_BYPASS", + "NATIVE_OPEN_INSERT_EDITOR"}) + allowed.add(juce::var(juce::String(op))); + state->setProperty("supportedOps",juce::var(allowed)); + juce::Array rows; + // Meter taps come from the SAME realtime ChannelId renderer, in + // accepted roster order. No JS guesses or second DSP render. + const bool pcmMeterValid=nativeMeterEpoch_.load(std::memory_order_acquire)==epoch(); + std::size_t meterIndex=0; + for(const auto& ch:routing->channels) { + auto row=std::make_unique(); + row->setProperty("id",juce::String(std::to_string(ch.id.value))); + const char* role=ch.role==armix::mixer::ChannelRole::input?"INPUT": + ch.role==armix::mixer::ChannelRole::group?"GROUP": + ch.role==armix::mixer::ChannelRole::fxReturn?"FX_RETURN": + ch.role==armix::mixer::ChannelRole::main?"MAIN":"MONITOR"; + row->setProperty("role",role); + // Only E3-created BUSes can be edited here. The original AUX + // 1–4 have FX_RETURN roles too, but are still M4-owned lanes. + row->setProperty("nativeManaged", + (ch.role==armix::mixer::ChannelRole::group || + ch.role==armix::mixer::ChannelRole::fxReturn) && + !originalM4Aux(ch.id)); + row->setProperty("name",juce::String(ch.name)); + row->setProperty("format",ch.format==armix::mixer::ProcessingFormat::stereo + ?"STEREO":"MONO"); + if(const auto* accepted=nativeAccepted_.graph.roster.find(ch.id)) { + row->setProperty("fader",static_cast(accepted->faderLinear)); + row->setProperty("pan",static_cast(accepted->pan)); + row->setProperty("mute",accepted->mute); + row->setProperty("solo",accepted->solo); + } + row->setProperty("primaryOutput", + juce::String(std::to_string(ch.primaryOutput.value))); + juce::Array liveInserts; + const auto fxCount=nativeAccepted_.fxOwners->insertCount(ch.id); + for(std::size_t slot=0;slotownerForControl( + ch.id,slot); + if(!lease||!*lease)continue; + auto item=std::make_unique(); + item->setProperty("instanceId",(*lease)->instanceId); + item->setProperty("id",(*lease)->catalogId); + item->setProperty("name",(*lease)->name); + item->setProperty("bypassed",(*lease)->bypassRequested.load( + std::memory_order_relaxed)); + liveInserts.add(juce::var(item.release())); + } + row->setProperty("inserts",juce::var(liveInserts)); + if(pcmMeterValid && meterIndexsetProperty("peakL",static_cast( + nativeMeterPeaksL_[meterIndex].load(std::memory_order_relaxed))); + row->setProperty("peakR",static_cast( + nativeMeterPeaksR_[meterIndex].load(std::memory_order_relaxed))); + } else { + row->setProperty("peakL",0.); + row->setProperty("peakR",0.); + } + ++meterIndex; + // Actual committed physical patches. Expose the verified original + // physical pin, not the reordered callback ordinal. + for(const auto& source:nativeAccepted_.graph.request.sources) { + if(source.id!=ch.id)continue; + auto physical=std::make_unique(); + if(source.inputL>=0&&source.inputLsetProperty("portId","in:"+juce::String(pin)); + } + // Preserve BOTH actual physical pins on native readback, not + // just the left pin. The GUI may not invent the right channel. + if(source.stereo && source.inputR>=0 && + source.inputRsetProperty("portIdRight","in:"+juce::String(right)); + } + physical->setProperty("sourceFormat",source.stereo?"STEREO":"MONO"); + row->setProperty("source",juce::var(physical.release())); + break; + } + juce::Array sends; + for(const auto& send:ch.parallelSends) { + auto edge=std::make_unique(); + edge->setProperty("target",juce::String( + std::to_string(send.destination.value))); + edge->setProperty("preFader",send.preFader); + edge->setProperty("gain",static_cast(send.gain)); + edge->setProperty("pan",static_cast(send.pan)); + sends.add(juce::var(edge.release())); + } + row->setProperty("parallelSends",juce::var(sends)); + rows.add(juce::var(row.release())); + } + state->setProperty("channels",juce::var(rows)); + juce::Array edges; + for(const auto& accepted:routing->edges) { + auto edge=std::make_unique(); + edge->setProperty("edgeId",juce::String( + std::to_string(accepted.edgeId))); + edge->setProperty("from",juce::String( + std::to_string(accepted.from.value))); + edge->setProperty("to",juce::String( + std::to_string(accepted.to.value))); + edge->setProperty("gainLinear", + static_cast(accepted.gainLinear)); + edge->setProperty("tap",accepted.preFader?"PRE_FADER":"POST_FADER"); + edge->setProperty("primaryOutput",accepted.primaryOutput); + edges.add(juce::var(edge.release())); + } + state->setProperty("edges",juce::var(edges)); + return juce::var(state.release()); + } + + + void revokeChannelIdPcm() noexcept { + channelIdPcmEpoch_.store(0,std::memory_order_release); + // Neither a structural BUS nor a native-owned fader/mute/pan may + // silently resume on the out-of-date legacy M4 PCM renderer. + if(nativeStructureLive_ || nativeControlDirty_) + topologyFault_.store(true,std::memory_order_release); + } + void rejectedNativeMirror() noexcept { + // A failed AUX/mirror after any native-owned fader gesture must not + // reactivate stale legacy M4 controls on the original channels. + if(nativeStructureLive_ || nativeControlDirty_) + topologyFault_.store(true,std::memory_order_release); + else channelIdPcmEpoch_.store(0,std::memory_order_release); + } + bool channelIdPhysicalPcmActive() const noexcept { + const auto active=channelIdPcmEpoch_.load(std::memory_order_acquire); + return active!=0 && active==epoch() && ready() && + !topologyFault_.load(std::memory_order_acquire); + } + void disable() noexcept { + channelIdPcmEpoch_.store(0,std::memory_order_release); + nativeMeterEpoch_.store(0,std::memory_order_release); + nativeStructureLive_=false; + nativeControlDirty_=false; + nativePublisher_.unpublish(); // CONTROL-only; audio lease retires safely + nativeAccepted_=armix::mixer::UnifiedLegacyAccepted{}; userPatched_.store(false,std::memory_order_release); enabled_.store(false,std::memory_order_release); publishedEpoch_.store(0,std::memory_order_release); @@ -641,13 +1821,18 @@ class LiveDryRoutingLab final { fxCount_.store(0,std::memory_order_relaxed); fxReused_.store(0,std::memory_order_relaxed); acceptedRoute_=juce::var(); // control-thread STOP only + sourceTemplate_=juce::var(); + acceptedFxSelections_=FxSelections{}; for(auto& n:auxFxNames_)n.clear(); for(auto& p:channelPeaks_)p.store(0.f,std::memory_order_relaxed); for(auto& p:channelPeaksL_)p.store(0.f,std::memory_order_relaxed); for(auto& p:channelPeaksR_)p.store(0.f,std::memory_order_relaxed); for(auto& p:auxPeaks_)p.store(0.f,std::memory_order_relaxed); } - void poll() noexcept {publisher_.pollRetirement();} // message thread + void poll() noexcept { + publisher_.pollRetirement(); + nativePublisher_.pollRetirement(); + } // message thread only, reclaim both graph generations bool active() const noexcept {return enabled_.load(std::memory_order_acquire);} float peakLeft() const noexcept {return peakL_.load(std::memory_order_relaxed);} float peakRight() const noexcept {return peakR_.load(std::memory_order_relaxed);} @@ -679,6 +1864,17 @@ class LiveDryRoutingLab final { if(actualOutputPair)*actualOutputPair={{-1,-1}}; if(actualMonitorPair)*actualMonitorPair={{-1,-1}}; if(!active())return false; + // The real JUCE M4 callback owns one mutable DSP scratch/fade state. + // A broken backend overlapping two process() calls must never run + // two VST chains against the same prepared buffers. Fail SILENT, + // do not spin or take a lock on the host-owned realtime callback. + armix::rt::RealtimeRenderPermit exclusive{rendering_}; + if(!exclusive) { + if(outputs && frames>0 && frames<=Block::hardFrameLimit) + for(int c=0;c perChannelPeaks{}; std::array perChannelPeaksL{},perChannelPeaksR{}; + // Bounded realtime meter scratch for all accepted ChannelIds, not + // only the original ten. No allocation or graph iteration on AUDIO. + std::array nativeMaxL{},nativeMaxR{}; std::array perAuxPeaks{}; for(int offset=0;offsetprepared->process(shifted.data(),inputCount, - mainL+offset,mainR+offset,n,&level, - externalContext,externalFx, - monitorL?monitorL+offset:nullptr, - monitorR?monitorR+offset:nullptr)) { + bool processed=false; + if(channelIdRender) { + // The current M4 import is at most 10+4+MAIN+MONITOR. + // Meter sources are the ACTUAL ChannelId PCM POST-fader + // lanes, not another mixer pass or reused M4 peak values. + std::array tapsL{},tapsR{}; + const auto noExtraFx=[](armix::mixer::ChannelId,float*,float*,int) noexcept {}; + processed=nativePublisher_.render( + generation,shifted.data(),inputCount, + mainL+offset,mainR+offset,n,false,noExtraFx, + monitorL?monitorL+offset:nullptr, + monitorR?monitorR+offset:nullptr,tapsL,tapsR); + if(processed) { + for(std::size_t ch=0;chprepared->process( + shifted.data(),inputCount,mainL+offset,mainR+offset,n, + &level,externalContext,externalFx, + monitorL?monitorL+offset:nullptr, + monitorR?monitorR+offset:nullptr); + } + if(!processed) { // A failed DSP pass must never leak partially rendered // MAIN/MONITOR PCM into an armed physical output. topologyFault_.store(true,std::memory_order_release); @@ -866,6 +2097,13 @@ class LiveDryRoutingLab final { } for(int b=0;bsetProperty("topologyFault",topologyFault_.load(std::memory_order_acquire)); out->setProperty("ready",ready()); out->setProperty("hasAcceptedRoute",hasExplicitRoute()); + const bool nativePcm=channelIdPhysicalPcmActive(); + out->setProperty("nativeChannelIdPcmActive",nativePcm); + // ShowV2 and the legacy M4 route cannot serialize extra ChannelId + // GROUP/FX RETURN buses. This stays visible even after DSP faults + // silent so SAVE/RECALL cannot silently discard audible topology. + out->setProperty("nativeBusStructural",nativeStructureLive_); + if(nativePcm)out->setProperty("nativeBus",nativeBusStatus()); + // This exact original vendor Graph owner is retained by the native + // accepted snapshot, NOT merely a catalog name or M4 CH1 label. + // Message-thread diagnostic only; no false universal capabilities. + out->setProperty("originalCh1GraphLeased", + nativePcm && nativeAccepted_.fxOwners && + nativeAccepted_.fxOwners->externalChannel()== + nativeAccepted_.graph.ids.inputs[0]); out->setProperty("epoch",static_cast(epoch())); out->setProperty("revision",static_cast(revision())); out->setProperty("peakL",peakL_.load(std::memory_order_relaxed)); @@ -893,8 +2145,15 @@ class LiveDryRoutingLab final { out->setProperty("auxFxNames",juce::var(auxNames)); out->setProperty("auxPeaks",juce::var(auxPeaks)); out->setProperty("fxReused",fxReused_.load(std::memory_order_relaxed)); - // Only the message thread calls status(), never the audio callback. + // Control-thread snapshot; the existing channelControls property + // below is the single authoritative atomic-target readback, while + // acceptedRoute remains the immutable topology of the same revision. if(active() && ready())out->setProperty("acceptedRoute",acceptedRoute_); + // A fresh device starts with a REAL native silent prepared topology. + // Expose it to the Console so IN can be selected directly, without + // inventing ten browser channels or an APPLY ROUTING prerequisite. + if(active() && ready() && !hasExplicitRoute() && sourceTemplate_.isObject()) + out->setProperty("preparedM4Route",sourceTemplate_); juce::Array liveFxInstances; const auto* prepared=hasExplicitRoute() ?publisher_.controlPrepared(epoch(),revision()):nullptr; @@ -991,7 +2250,13 @@ class LiveDryRoutingLab final { return juce::var(out.release()); } private: + std::atomic_flag rendering_=ATOMIC_FLAG_INIT; // one AUDIO producer Publisher publisher_; + armix::mixer::DynamicNativeSessionPublisher nativePublisher_; + armix::mixer::UnifiedLegacyAccepted nativeAccepted_; + std::atomic channelIdPcmEpoch_{0}; + bool nativeStructureLive_=false; // CONTROL only; never read by callback + bool nativeControlDirty_=false; // Native edit cannot fall back to stale M4 PCM std::atomic monitorPeakL_{0.f},monitorPeakR_{0.f}; armix::dsp::MasterOutputMonoPolicy masterMonoPolicy_; // audio thread only std::array channelEdits_{}; // JUCE message thread only @@ -1000,6 +2265,8 @@ class LiveDryRoutingLab final { std::array,auxCount> auxPeaks_{}; std::atomic auxCountActive_{0},auxSendCount_{0}; juce::var acceptedRoute_; // native ACK only, no UI preview/localStorage truth + juce::var sourceTemplate_; // last prepared M4 template, including SILENT/NONE startup + FxSelections acceptedFxSelections_{}; // CONTROL ONLY: original VST3 identity for FX reuse // All data shared between JUCE device lifecycle and GUI/control reads // are atomic; the callback never enumerates masks or channel names. std::array,armix::device::LiveInputPortRegistry::limit> enabledPorts_{}; @@ -1019,6 +2286,11 @@ class LiveDryRoutingLab final { std::atomic fxReused_{0}; std::array,count> channelPeaks_{}; std::array,count> channelPeaksL_{},channelPeaksR_{}; + // Constant-memory native post-fader meters; capacity affects only + // telemetry, not how many channels the audio graph can admit. + static constexpr std::size_t nativeMeterCapacity=128; + std::array,nativeMeterCapacity> nativeMeterPeaksL_{},nativeMeterPeaksR_{}; + std::atomic nativeMeterEpoch_{0}; // Exclusive render-producer state. Bounded fade starts from the exact // previously output sample, preventing a topology switch discontinuity. static constexpr int rampFrames=256; diff --git a/src/NativeDryShowRecall.h b/src/NativeDryShowRecall.h index ef26a631c..49f6339d6 100644 --- a/src/NativeDryShowRecall.h +++ b/src/NativeDryShowRecall.h @@ -41,6 +41,11 @@ class NativeDryShowRecall final { if(!borrowed.isInt() || static_cast(borrowed)!=0) return "Remove CH1 vendor FX before restoring a DRY-only Show"; const auto lab=status.getProperty("dryRoutingLab",{}); + // ShowV2 cannot represent a live extra ChannelId GROUP/FX RETURN. + // This check protects the saved state and currently accepted PCM + // before any hardware port or VST3 restore side effect. + if(static_cast(lab.getProperty("nativeBusStructural",false))) + return "Remove extra native GROUP/FX RETURN buses before Show RECALL"; if(!lab.isObject() || !lab.getProperty("ready",{}).isBool() || !static_cast(lab.getProperty("ready",{})) || diff --git a/src/NativeLiveShowCapture.h b/src/NativeLiveShowCapture.h index 40bc855be..2d766f817 100644 --- a/src/NativeLiveShowCapture.h +++ b/src/NativeLiveShowCapture.h @@ -49,6 +49,11 @@ class NativeLiveShowCapture final { return "CH1 FX Rack has VST3 state: cannot SAVE as a DRY-only Show"; const auto lab=nativeStatus.getProperty("dryRoutingLab",{}); if(!lab.isObject())return "Native Routing LAB has no published session"; + // The accepted ShowV2 contains only 10 fixed CH/4 AUX. Saving a + // live native GROUP/FX RETURN would discard real serial/parallel PCM. + // Reject even if topologyFault subsequently forced silent fallback. + if(static_cast(lab.getProperty("nativeBusStructural",false))) + return "Remove extra native GROUP/FX RETURN buses before Show SAVE"; bool active=false,ready=false; if(!flag(lab.getProperty("active",{}),active) || !flag(lab.getProperty("ready",{}),ready) || !active || !ready) diff --git a/src/NativeShowSaveWorker.h b/src/NativeShowSaveWorker.h index f44e1f23f..f568003d2 100644 --- a/src/NativeShowSaveWorker.h +++ b/src/NativeShowSaveWorker.h @@ -43,17 +43,19 @@ class NativeShowSaveWorker final : private juce::Thread { } bool launch(juce::File studio,SnapshotV2 snapshot, std::vector binaryStates,Completion completion) { - if(!reserve(Operation::save,std::move(studio),std::move(completion)) || - !detail::uuid(snapshot.id))return false; + // Reject invalid requests BEFORE reserving or retaining a potentially + // large vendor-state payload on this long-lived worker. + if(!detail::uuid(snapshot.id) || + !reserve(Operation::save,std::move(studio),std::move(completion))) + return false; snapshot_=std::move(snapshot); blobs_=std::move(binaryStates); - if(startThread())return true; - return false; + return startOrRelease(); } bool list(juce::File studio,Completion completion) { if(!reserve(Operation::list,std::move(studio),std::move(completion))) return false; - return startThread(); + return startOrRelease(); } bool read(juce::File studio,juce::String showId, juce::int64 epoch,juce::int64 revision,Completion completion) { @@ -62,9 +64,27 @@ class NativeShowSaveWorker final : private juce::Thread { return false; requestedId_=std::move(showId); requestEpoch_=epoch;requestRevision_=revision; - return startThread(); + return startOrRelease(); } private: + // Start failure must release captured Show snapshots, binary-state blobs + // and completion closures. The worker never transfers these to RT. + bool startOrRelease() { + if(startThread())return true; + releaseJob(); + return false; + } + // Exclusively invoked after the worker's IO is finished or before it + // started. No concurrent use with the caller/message thread. + void releaseJob() { + snapshot_=SnapshotV2{}; + blobs_.clear(); + blobs_.shrink_to_fit(); + requestedId_={}; + requestEpoch_=0;requestRevision_=0; + studio_={}; + finished_={}; + } bool reserve(Operation mode,juce::File studio,Completion completion) { if(isThreadRunning()||!completion)return false; operation_=mode;studio_=std::move(studio); @@ -86,10 +106,11 @@ class NativeShowSaveWorker final : private juce::Thread { } catch(...) { result.error="Unknown native Show IO exception; session unchanged"; } - blobs_.clear(); // release captured bytes on IO thread after commit - blobs_.shrink_to_fit(); + // Move the completion closure out: the worker must not retain a + // second copy of UI captures or a large Show snapshot between jobs. + auto done=std::move(finished_); + releaseJob(); // IO worker thread, never audio callback auto alive=alive_; - auto done=finished_; // A 128 MB vendor-blob result must not be copied by std::function // when JUCE queues an async callback on the message thread. auto delivered=std::make_shared(std::move(result)); diff --git a/src/NativeVerifiedSourcePatch.h b/src/NativeVerifiedSourcePatch.h new file mode 100644 index 000000000..ca9927d87 --- /dev/null +++ b/src/NativeVerifiedSourcePatch.h @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include + +// Message-thread SOURCE transaction: one verified input selection from an +// initially SILENT M4 session, without modifying the accepted Show or FX +// until the whole graph/epoch has compiled. Both MAIN and auxiliary outputs +// remain owned by the existing one JUCE production callback. +namespace armix::mixer { +struct NativeVerifiedSourcePatch final { + static juce::String prepare(const juce::var& accepted, + int channel,const juce::String& mode,int physicalLeft,int physicalRight, + std::span enabledPhysicalPorts, + std::uint64_t actualEpoch,std::uint64_t actualRevision, + juce::var& destination) + { + if(!actualEpoch || + actualEpoch>static_cast(std::numeric_limits::max()) || + actualRevision>static_cast(std::numeric_limits::max()) || + !accepted.isObject() || channel<0 || channel>=10) + return "SOURCE: stale device epoch or invalid native channel"; + if(mode!="MONO"&&mode!="STEREO") + return "SOURCE: MONO or STEREO mode required"; + if(physicalLeft<0 || enabledPhysicalPorts.empty()) + return "SOURCE: select an enabled physical capture pin"; + if(static_cast(accepted.getProperty("deviceEpoch",juce::var(-1))) != + static_cast(actualEpoch)) + return "SOURCE: device epoch changed; accepted patch preserved"; + bool validLeft=false,validRight=false; + for(const int port:enabledPhysicalPorts) { + if(port==physicalLeft)validLeft=true; + if(port==physicalRight)validRight=true; + } + if(!validLeft || (mode=="STEREO" && + (!validRight || physicalLeft==physicalRight))) + return "SOURCE: STEREO requires two distinct active physical pins; MONO accepts one"; + // JUCE var assignment shares the underlying DynamicObject. Deep + // clone before touching a row, or failed prepare would silently + // mutate the still-audible accepted routing snapshot. + auto copy=juce::JSON::parse(juce::JSON::toString(accepted,false)); + if(!copy.isObject()) + return "SOURCE: cannot clone accepted native patch"; + auto channels=copy.getProperty("channels",juce::var()); + auto* list=channels.getArray(); + if(!list || list->size()!=10 || !list->getReference(channel).isObject()) + return "SOURCE: accepted patch channel layout unavailable"; + auto* row=list->getReference(channel).getDynamicObject(); + // Native routing v2 separates SOURCE format from the processing + // channel width. A source is not audible if only the old "mode" + // field changes: NativeDryRouteCommand::decode will reject the stale + // sourceKind/sourceFormat. Keep selected channelFormat intact so a + // one-pin MONO microphone may feed STEREO processing without IN2. + const auto schema=copy.getProperty("schemaVersion",juce::var()); + if(!schema.isVoid() && (!schema.isInt() || + (static_cast(schema)!=1 && static_cast(schema)!=2))) + return "SOURCE: unsupported accepted native route version"; + if(schema.isInt() && static_cast(schema)==2) { + const auto width=row->getProperty("channelFormat").toString(); + if(width!="MONO" && width!="STEREO") + return "SOURCE: native processing format missing or invalid"; + row->setProperty("sourceKind","PHYSICAL"); + row->setProperty("sourceFormat",mode); + } + row->setProperty("mode",mode); + row->setProperty("left",physicalLeft); + row->setProperty("right",mode=="STEREO"?physicalRight:-1); + // The existing M4 producer handles revision/epoch publication and + // fails back to its prior accepted graph on any bad plugin/routing. + copy.getDynamicObject()->setProperty("deviceEpoch",static_cast(actualEpoch)); + copy.getDynamicObject()->setProperty("revision",static_cast(actualRevision)); + destination=std::move(copy); + return {}; + } +}; +} // namespace armix::mixer diff --git a/tests/dedicated_aux_bus_test.cpp b/tests/dedicated_aux_bus_test.cpp index c1f7899e3..309d080c5 100644 --- a/tests/dedicated_aux_bus_test.cpp +++ b/tests/dedicated_aux_bus_test.cpp @@ -75,6 +75,25 @@ int main(){ assert(near(meters.auxPeak[0],auxA)); // after bus gain 0.5 assert(near(meters.auxPeak[1],auxB)); assert(near(meters.channelPeak[9],.1f*std::sqrt(.5f))); + // This is real PRE/POST native PCM, never a JS send simulation. + // A 64-frame gain ramp must not collapse to an 8-frame hard step. + assert(block.setAuxSendGain(0,0,SendTap::preFader,0.f)); + assert(block.setAuxSendGain(9,1,SendTap::postFader,0.f)); + assert(!block.setAuxSendGain(9,0,SendTap::postFader,0.f)); // edge absent + const auto beforeSendAutomation=allocations.load(std::memory_order_relaxed); + for(int cycle=0;cycle<8;++cycle) + assert(block.process(input.data(),stripCount,outL.data(),outR.data(), + frames,effects,&meters)); + assert(allocations.load(std::memory_order_relaxed)==beforeSendAutomation); + assert(near(outL[7],direct)&&near(outR[7],direct)); + assert(near(block.auxSendGain(0,0,SendTap::preFader),0.f)); + assert(near(block.auxSendGain(9,1,SendTap::postFader),0.f)); + assert(block.setAuxSendGain(0,0,SendTap::preFader,.5f)); + assert(block.setAuxSendGain(9,1,SendTap::postFader,.25f)); + for(int cycle=0;cycle<8;++cycle) + assert(block.process(input.data(),stripCount,outL.data(),outR.data(), + frames,effects,&meters)); + assert(near(outL[7],direct+auxA+auxB)); // Shared stereo AUX receives an explicitly left-panned mono PRE send. // The right output must not inherit phantom mono power. @@ -208,6 +227,27 @@ int main(){ assert(near(monL[f],.4f*monoCenter*.75f)); assert(near(monR[f],.4f*monoCenter*.75f)); } + // Native MONITOR targets move independent of MAIN, and their ramp + // follows AUDIO samples across eight 8-frame callbacks. + std::array,stripCount+auxBusCount> liveMonitor{}; + for(int i=0;i #if defined(NDEBUG) #undef NDEBUG // Native Release CTest must actually run assertions. @@ -7,6 +8,7 @@ #include #include #include +#include #include using namespace armix::mixer; @@ -26,7 +28,535 @@ static ChannelEdit send(ChannelId from,ChannelId to,float gain,bool pre=false) { ChannelEdit e;e.kind=ChannelEdit::Kind::addSendReference; e.id=from;e.target=to;e.value=gain;e.preFader=pre;return e; } + +static void verifyRealtimeSlewAndNativeChannelIdContinuousControls() { + using armix::dsp::RealtimeSlew64; + // Sub-64 variable callbacks must not finish a 64-sample gesture in 4 + // frames. Coalescing multiple UI writes before a read keeps latest goal. + RealtimeSlew64 s; + s.reset(1.f); + s.retarget(.2f); + s.retarget(.5f); // replaces the old unrendered target; no queue buildup + for(int i=0;i<4;++i)s.next(); + assert(near(s.current,1.f-(.5f*4.f/64.f))); + for(int i=0;i<16;++i)s.next(); + assert(near(s.current,1.f-(.5f*20.f/64.f))); + for(int i=0;i<32;++i)s.next(); + assert(near(s.current,1.f-(.5f*52.f/64.f))); + for(int i=0;i<12;++i)s.next(); + assert(s.remaining==0 && s.current==.5f); + s.retarget(0.f); + for(int i=0;i<20;++i)s.next(); + const float applied=s.current; + s.retarget(.75f); // reverse while in flight; no jump on target update + assert(s.current==applied); + assert(s.next()>applied); + for(int i=1;i<64;++i)s.next(); + assert(s.current==.75f && s.remaining==0); + + // The approved GUI sends ChannelId-keyed realtime moves. Verify actual + // PCM through GROUP-compatible Main, PRE wet Return and POST Monitor, + // not a disconnected smoothing helper or browser-only fixture. + DynamicAcceptedSession session; + constexpr std::uint64_t epoch=9401; + DynamicGraphRequest route; + route.physicalInputs=1; + route.maxFrames=64; + std::array creates{ + add(0,ChannelRole::input,"VOICE"), + add(1,ChannelRole::fxReturn,"WET",ProcessingFormat::stereo), + add(2,ChannelRole::main,"MAIN",ProcessingFormat::stereo), + add(3,ChannelRole::monitor,"CUE",ProcessingFormat::stereo) + }; + auto a=session.edit(0,0,creates,route,epoch,epoch,true); + assert(a.ok()); + const auto voice=a.edit.createdIds[0]; + const auto wet=a.edit.createdIds[1]; + const auto main=a.edit.createdIds[2]; + const auto cue=a.edit.createdIds[3]; + std::array links{ + output(voice,main), + output(wet,main), + send(voice,wet,.5f,true), + send(voice,cue,.5f,false) + }; + route.sources={{voice,0,-1,false}}; + a=session.edit(1,1,links,route,epoch,epoch,true); + assert(a.ok()&&session.acceptedGraphRevision()==2); + std::array input{},outL{},outR{},cueL{},cueR{}; + input.fill(.5f); + const float* pins[]{input.data()}; + const auto fx=+[](ChannelId,float*,float*,int) noexcept {}; + const auto render=[&](int n) { + return session.render(epoch,pins,1,outL.data(),outR.data(),n, + false,fx,cueL.data(),cueR.data()); + }; + assert(render(64)); + const float initialMain=outL[63]; + const float initialCue=cueL[63]; + assert(initialMain>.1f && initialCue>.01f); + assert(session.setLiveMix(epoch,2,voice,0.f,0.f)); + assert(session.setLiveParallelSend(epoch,2,voice,wet,true,0.f)); + assert(session.setLiveParallelSend(epoch,2,voice,cue,false,0.f)); + // PRE send, POST send and channel fader must all advance across + // 4+16+32+12 (one complete ramp), not finish on the FIRST 4 samples. + assert(render(4)); + const float after4=outL[3],cue4=cueL[3]; + assert(after4>0.f && after40.f && cue40.f && after200.f && cue200.f); + assert(render(60)); + constexpr float center=.7071067811865475f; + assert(near(outL[59],.5f*.8f*center,0.0001f)); + assert(!session.setLiveMix(epoch,1,voice,1.f,0.f)); + assert(!session.setLiveParallelSend(epoch-1,2,voice,wet,true,1.f)); + assert(session.acceptedGraphRevision()==2); + session.unpublish(); + session.pollRetirement(); +} + +// Native WIRE PCM regression: source OUT → Group → MAIN must be an +// exclusive serial route, not two dry feeds. Rejected feedback preserves the +// previous audible graph. Disconnect really removes primary audio. +static void verifyConsoleWirePrimaryOutputPcm() { + constexpr std::uint64_t epoch=9751; + constexpr float center=.7071067811865475f; + DynamicAcceptedSession session; + DynamicGraphRequest request; + request.physicalInputs=1;request.maxFrames=64; + const std::array created{ + add(0,ChannelRole::input,"CH11"), + add(1,ChannelRole::group,"VOICE GROUP",ProcessingFormat::stereo), + add(2,ChannelRole::main,"MAIN",ProcessingFormat::stereo) + }; + auto result=session.edit(0,0,created,request,epoch,epoch,true); + assert(result.ok()&&result.edit.createdIds.size()==3); + const auto ch=result.edit.createdIds[0]; + const auto group=result.edit.createdIds[1]; + const auto main=result.edit.createdIds[2]; + const std::array first{ + output(ch,main),output(group,main) + }; + request.sources={{ch,0,-1,false}}; + result=session.edit(1,1,first,request,epoch,epoch,true); + assert(result.ok()&&result.graphRevision==2); + std::array audio{},left{},right{}; + audio.fill(.35f); + const float* inputs[]{audio.data()}; + const auto noFx=+[](ChannelId,float*,float*,int) noexcept {}; + const auto render=[&]{ + return session.render(epoch,inputs,1,left.data(),right.data(),64,false,noFx); + }; + assert(render()&&near(left[63],.35f*center,1e-4f)); + const std::array routeGroup{output(ch,group)}; + result=session.edit(session.acceptedRosterRevision(),2,routeGroup, + request,epoch,epoch,true); + assert(result.ok()&&session.acceptedGraphRevision()==3); + const auto* graph=session.acceptedRouting(epoch,3); + assert(graph&&graph->find(ch)->primaryOutput==group); + assert(graph->find(group)->primaryOutput==main); + assert(render()&&near(left[63],.35f*center,1e-4f)); + + // Group -> CH11 while CH11 -> Group is cyclic. A rejected native + // publication must preserve CH11 -> Group -> MAIN and real PCM. + const std::array feedback{output(group,ch)}; + const auto rejected=session.edit(session.acceptedRosterRevision(),3, + feedback,request,epoch,epoch,true); + assert(!rejected.ok()&&session.acceptedGraphRevision()==3); + assert(session.acceptedRouting(epoch,3)->find(group)->primaryOutput==main); + assert(render()&&near(left[63],.35f*center,1e-4f)); + const std::array disconnected{output(ch,ChannelId{})}; + result=session.edit(session.acceptedRosterRevision(),3,disconnected, + request,epoch,epoch,true); + assert(result.ok()&&session.acceptedGraphRevision()==4); + assert(!session.acceptedRouting(epoch,4)->find(ch)->primaryOutput.value); + assert(render()&&near(left[63],0.f,1e-5f)); + // Reconnect to the same real Group, with exactly one primary route. + result=session.edit(session.acceptedRosterRevision(),4,routeGroup, + request,epoch,epoch,true); + assert(result.ok()&&session.acceptedGraphRevision()==5); + assert(render()&&near(left[63],.35f*center,1e-4f)); + session.unpublish(); + session.pollRetirement(); +} + + +// Native WIRE-first acceptance: exactly ONE immutable PCM graph owner. +// Direct, nested and reconvergent paths process within the SAME sample block; +// exact edgeId detach only affects its source, rejected DAG stays audible. +static void verifyAtomicWireTransactionAndZeroSampleHops() { + constexpr std::uint64_t epoch=9909; + constexpr float center=.7071067811865475f; + DynamicAcceptedSession session; + DynamicGraphRequest physical; + physical.physicalInputs=1;physical.maxFrames=64; + const std::array create{ + add(0,ChannelRole::input,"INPUT"), + add(1,ChannelRole::input,"SUM 1",ProcessingFormat::stereo), + add(2,ChannelRole::input,"SUM 2",ProcessingFormat::stereo), + add(3,ChannelRole::main,"MAIN",ProcessingFormat::stereo) + }; + auto a=session.edit(0,0,create,physical,epoch,epoch,true); + assert(a.ok() && a.edit.createdIds.size()==4); + const auto one=a.edit.createdIds[0],two=a.edit.createdIds[1]; + const auto three=a.edit.createdIds[2],main=a.edit.createdIds[3]; + physical.sources={{one,0,-1,false}}; + auto connect=[](ChannelId from,ChannelId to,float gain=1.f) { + WireChange w;w.kind=WireChange::Kind::connect;w.from=from; + w.to=to;w.gain=gain;return w; + }; + auto routeOnly=[](ChannelId from,ChannelId to) { + WireChange w;w.kind=WireChange::Kind::routeOnly; + w.from=from;w.to=to;return w; + }; + auto remove=[](ChannelId from,std::uint64_t id) { + WireChange w;w.kind=WireChange::Kind::remove; + w.from=from;w.edgeId=id;return w; + }; + const std::array initial{ + connect(one,main),connect(two,main),connect(three,main) + }; + a=session.wireTransaction(1,1,initial,physical,epoch,epoch,true); + assert(a.ok()&&a.graphRevision==2&&a.edit.createdEdgeIds.size()==3); + const auto* graph=session.acceptedRouting(epoch,2); + assert(graph&&graph->edges.size()==3); + const auto findEdge=[&](ChannelId from,ChannelId to, + std::uint64_t revision){ + const auto* current=session.acceptedRouting(epoch,revision); + assert(current); + const auto it=std::find_if(current->edges.begin(),current->edges.end(), + [&](const auto& edge){return edge.from==from && edge.to==to;}); + return it==current->edges.end()?std::uint64_t{0}:it->edgeId; + }; + const auto originalMain=findEdge(one,main,2); + const auto otherMain=findEdge(three,main,2); + assert(originalMain!=0 && otherMain!=0 && originalMain!=otherMain); + std::array impulse{},left{},right{}; + impulse[11]=.3f; + const float* inputs[]{impulse.data()}; + const auto noFx=+[](ChannelId,float*,float*,int) noexcept {}; + const auto render=[&]{ + return session.render(epoch,inputs,1,left.data(),right.data(),64, + false,noFx); + }; + assert(render() && near(left[11],.3f*center)); + for(int i=0;i<64;++i) + if(i!=11)assert(near(left[i],0.f)); + + const std::array hop1{routeOnly(one,two)}; + a=session.wireTransaction(2,2,hop1,physical,epoch,epoch,false); // live PCM routing while armed + assert(a.ok() && a.graphRevision==3); + assert(!findEdge(one,main,3) && findEdge(one,two,3)); + assert(render() && near(left[11],.3f*center)); + + const std::array hop2{routeOnly(two,three)}; + a=session.wireTransaction(3,3,hop2,physical,epoch,epoch,true); + assert(a.ok() && a.graphRevision==4); + const auto chainId=findEdge(one,two,4); + assert(chainId && !findEdge(two,main,4)); + assert(findEdge(three,main,4)==otherMain); + assert(render() && near(left[11],.3f*center)); + for(int i=0;i<64;++i) + if(i!=11)assert(near(left[i],0.f)); + + // A second real path doubles PCM only by explicit legal fan-out. + const std::array parallel{connect(one,main)}; + a=session.wireTransaction(4,4,parallel,physical,epoch,epoch,true); + assert(a.ok() && a.graphRevision==5); + const auto directId=findEdge(one,main,5); + assert(directId && directId!=originalMain); + assert(render() && near(left[11],2.f*.3f*center,1e-4f)); + const std::array unplug{remove(one,directId)}; + a=session.wireTransaction(5,5,unplug,physical,epoch,epoch,true); + assert(a.ok() && a.graphRevision==6); + assert(!findEdge(one,main,6) && findEdge(three,main,6)==otherMain); + assert(render() && near(left[11],.3f*center)); + + // Wrong edge identity cannot disconnect another source's MAIN. + const std::array wrongEdge{remove(one,otherMain)}; + auto rejected=session.wireTransaction(6,6,wrongEdge,physical,epoch,epoch,true); + assert(rejected.fault==DynamicAcceptedSession::Fault::editRejected); + assert(session.acceptedGraphRevision()==6); + assert(render() && near(left[11],.3f*center)); + const std::array duplicate{connect(one,two)}; + rejected=session.wireTransaction(6,6,duplicate,physical,epoch,epoch,true); + assert(rejected.fault==DynamicAcceptedSession::Fault::editRejected); + assert(session.acceptedGraphRevision()==6); + + // Mixed existing route cycle: whole native DAG compile must roll back. + const std::array feedback{connect(three,one)}; + rejected=session.wireTransaction(6,6,feedback,physical,epoch,epoch,true); + if(rejected.fault!=DynamicAcceptedSession::Fault::graphRejected) + std::fprintf(stderr,"WIRE feedback rejection diagnostic: acceptedFault=%u rosterFault=%u nativeFault=%u graphFault=%u revision=%llu\\n", + static_cast(rejected.fault), + static_cast(rejected.edit.fault), + static_cast(rejected.native.fault), + static_cast(rejected.native.graphError.fault), + static_cast(rejected.graphRevision)); + assert(rejected.fault==DynamicAcceptedSession::Fault::graphRejected); + assert(rejected.edit.createdEdgeIds.empty()); // no phantom rejected ID + assert(session.acceptedGraphRevision()==6); + assert(render() && near(left[11],.3f*center)); + // Preserve output safety: the same WIRE edit with a changed hardware + // block budget is rejected BEFORE the native PCM graph is published. + DynamicGraphRequest changedPhysical=physical; + changedPhysical.maxFrames=128; + const std::array validTopology{connect(two,main)}; + rejected=session.wireTransaction(6,6,validTopology,changedPhysical, + epoch,epoch,false); + assert(rejected.fault==DynamicAcceptedSession::Fault::graphRejected); + assert(rejected.native.fault==DynamicNativeSessionPublisher::Fault::outputArmed); + assert(rejected.edit.createdEdgeIds.empty()); + assert(session.acceptedGraphRevision()==6); + assert(render() && near(left[11],.3f*center)); + rejected=session.wireTransaction(5,5,unplug,physical,epoch,epoch,true); + assert(rejected.fault==DynamicAcceptedSession::Fault::staleRoster); + assert(session.acceptedGraphRevision()==6); + rejected=session.wireTransaction(6,6,unplug,physical,epoch+1,epoch,true); + assert(rejected.fault==DynamicAcceptedSession::Fault::graphRejected); + assert(rejected.native.fault==DynamicNativeSessionPublisher::Fault::staleDevice); + assert(rejected.edit.createdEdgeIds.empty()); + // A genuinely valid edge must also reject the wrong epoch before + // publication, irrespective of the edit's own validity. + const std::array validButStale{connect(one,main)}; + rejected=session.wireTransaction(6,6,validButStale,physical,epoch+1,epoch,true); + assert(rejected.fault==DynamicAcceptedSession::Fault::graphRejected); + assert(rejected.native.fault==DynamicNativeSessionPublisher::Fault::staleDevice); + assert(session.acceptedGraphRevision()==6); + assert(render() && near(left[11],.3f*center)); + + // RETARGET keeps identity and gain, not a new/ghost wire. + WireChange retarget; + retarget.kind=WireChange::Kind::retarget; + retarget.from=one;retarget.to=main;retarget.edgeId=chainId; + const std::array reroute{retarget}; + a=session.wireTransaction(6,6,reroute,physical,epoch,epoch,true); + assert(a.ok() && a.graphRevision==7); + assert(findEdge(one,main,7)==chainId && !findEdge(one,two,7)); + assert(render() && near(left[11],.3f*center)); + session.unpublish(); + session.pollRetirement(); +} + + +// New native channel = exactly one CH->MAIN edge in ONE accepted revision, +// even when MAIN appears later in the same initial transaction. Restoring +// an intentionally disconnected older channel never auto-repairs its route. +static void verifyDefaultNativeMainEdgeAndDisconnectedRestore() { + constexpr std::uint64_t epoch=9910; + DynamicAcceptedSession session; + DynamicGraphRequest physical; + physical.maxFrames=64; + auto source=add(0,ChannelRole::input,"NEW WIRE"); + source.connectMainOnCreate=true; + const auto main=add(1,ChannelRole::main,"MAIN",ProcessingFormat::stereo); + const std::array first{source,main}; + auto a=session.edit(0,0,first,physical,epoch,epoch,true); + assert(a.ok() && a.edit.createdIds.size()==2); + const auto ch=a.edit.createdIds[0],master=a.edit.createdIds[1]; + const auto* routing=session.acceptedRouting(epoch,1); + assert(routing && routing->edges.size()==1); + const auto id=routing->edges.front().edgeId; + assert(id && routing->edges.front().from==ch && + routing->edges.front().to==master && + routing->edges.front().primaryOutput && + routing->edges.front().gainLinear==1.f); + WireChange unplug;unplug.kind=WireChange::Kind::remove; + unplug.from=ch;unplug.edgeId=id; + const std::array batch{unplug}; + a=session.wireTransaction(1,1,batch,physical,epoch,epoch,true); + assert(a.ok() && a.graphRevision==2); + assert(session.acceptedRouting(epoch,2)->edges.empty()); + auto newer=add(1,ChannelRole::input,"NEWER WIRE"); + newer.connectMainOnCreate=true; + const std::array append{newer}; + a=session.edit(2,2,append,physical,epoch,epoch,true); + assert(a.ok() && a.edit.createdIds.size()==1); + routing=session.acceptedRouting(epoch,3); + assert(routing && routing->edges.size()==1); + assert(routing->edges.front().from==a.edit.createdIds.front()); + assert(routing->edges.front().to==master); + assert(routing->edges.front().edgeId!=id); + session.unpublish();session.pollRetirement(); +} + +static void verifyPrimaryOutKeepsCanonicalEdgeIdentity() { + constexpr std::uint64_t epoch=9931; + DynamicAcceptedSession session; + DynamicGraphRequest physical; + physical.physicalInputs=1;physical.maxFrames=64; + const std::array first{ + add(0,ChannelRole::input,"SOURCE"), + add(1,ChannelRole::input,"INTERMEDIATE",ProcessingFormat::stereo), + add(2,ChannelRole::main,"MAIN",ProcessingFormat::stereo) + }; + auto a=session.edit(0,0,first,physical,epoch,epoch,true); + assert(a.ok()); + const auto src=a.edit.createdIds[0],via=a.edit.createdIds[1]; + const auto main=a.edit.createdIds[2]; + const std::array initial{output(src,main),output(via,main)}; + physical.sources={{src,0,-1,false}}; + a=session.edit(1,1,initial,physical,epoch,epoch,true); + assert(a.ok()); + const auto* accepted=session.acceptedRouting(epoch,2); + assert(accepted&&accepted->edges.size()==2); + const auto edgeId=accepted->edges[0].edgeId; + const auto viaId=accepted->edges[1].edgeId; + assert(edgeId!=0&&viaId!=0&&edgeId!=viaId); + std::array impulse{},left{},right{}; + impulse[19]=.25f; + const float* pins[]{impulse.data()}; + const auto noFx=+[](ChannelId,float*,float*,int) noexcept {}; + const auto render=[&] { + return session.render(epoch,pins,1,left.data(),right.data(),64,false,noFx); + }; + assert(render() && near(left[19],.25f*.7071067811865475f)); + const std::array same{output(src,main)}; + a=session.edit(2,2,same,physical,epoch,epoch,true); + assert(a.ok()); + assert(session.acceptedRouting(epoch,3)->edges[0].edgeId==edgeId); + assert(render() && near(left[19],.25f*.7071067811865475f)); + const std::array retarget{output(src,via)}; + a=session.edit(3,3,retarget,physical,epoch,epoch,true); + assert(a.ok()); + accepted=session.acceptedRouting(epoch,4); + assert(accepted->edges[0].edgeId==edgeId); + assert(accepted->edges[0].to==via); + assert(accepted->edges[1].edgeId==viaId); + assert(render() && near(left[19],.25f*.7071067811865475f)); + session.unpublish(); + session.pollRetirement(); +} + +// Original CH1-10 do not get a different fader/solo DSP owner from CH11. +// This is an actual accepted native publisher PCM test, not a mock GUI reducer. +static void verifyOriginalAndAddedInputsShareNativePcmControls() { + constexpr std::uint64_t epoch=94011; + constexpr float center=.7071067811865475f; + DynamicAcceptedSession pcm; + DynamicGraphRequest physical; + physical.physicalInputs=3; + physical.maxFrames=64; + std::vector initial; + for(int i=0;i<10;++i) + initial.push_back(add(static_cast(i), + ChannelRole::input,"ORIGINAL CH")); + initial.push_back(add(10,ChannelRole::main,"MAIN", + ProcessingFormat::stereo)); + auto applied=pcm.edit(0,0,initial,physical,epoch,epoch,true); + assert(applied.ok() && applied.edit.createdIds.size()==11); + const auto ch1=applied.edit.createdIds[0]; + const auto ch2=applied.edit.createdIds[1]; + const auto main=applied.edit.createdIds[10]; + const std::array originals{ + output(ch1,main),output(ch2,main)}; + physical.sources={{ch1,0,-1,false},{ch2,1,-1,false}}; + applied=pcm.edit(1,1,originals,physical,epoch,epoch,true); + assert(applied.ok() && pcm.acceptedGraphRevision()==2); + // CH11 is added to the SAME accepted native graph later, not indexed + // as CH1 and not assigned a second VST/PCM process callback. + const std::array added{ + add(10,ChannelRole::input,"DYNAMIC CH11")}; + applied=pcm.edit(2,2,added,physical,epoch,epoch,true); + assert(applied.ok() && applied.edit.createdIds.size()==1); + const auto ch11=applied.edit.createdIds[0]; + assert(ch11!=ch1 && ch11!=ch2); + physical.sources.push_back({ch11,2,-1,false}); + const std::array connect{output(ch11,main)}; + applied=pcm.edit(3,3,connect,physical,epoch,epoch,true); + assert(applied.ok() && pcm.acceptedGraphRevision()==4); + std::array a{},b{},c{},l{},rr{}; + a.fill(.2f);b.fill(.3f);c.fill(.4f); + const float* inputs[]{a.data(),b.data(),c.data()}; + const auto noFx=+[](ChannelId,float*,float*,int) noexcept {}; + const auto render=[&] { + return pcm.render(epoch,inputs,3,l.data(),rr.data(),64,false,noFx); + }; + assert(render() && near(l[63],(.2f+.3f+.4f)*center)); + const float minus12=std::pow(10.f,-12.f/20.f); + assert(pcm.setLiveMix(epoch,4,ch1,minus12,0.f)); + assert(render() && near(l[63],(.2f*minus12+.3f+.4f)*center)); + assert(pcm.setLiveMix(epoch,4,ch2,1.f,-1.f)); + assert(render() && near(l[63],(.2f*minus12+.4f)*center+.3f)); + assert(near(rr[63],(.2f*minus12+.4f)*center)); + assert(pcm.setLiveMuteSolo(epoch,4,ch1,true,false)); + assert(render() && near(l[63],.3f+.4f*center)); + assert(pcm.setLiveMuteSolo(epoch,4,ch11,false,true)); + assert(render() && near(l[63],.4f*center)); + assert(pcm.setLiveMix(epoch,4,ch11,.5f,1.f)); + assert(render() && near(l[63],0.f) && near(rr[63],.2f)); + // No old device, old graph revision or invented ChannelId can change + // accepted native PCM, even while a solo/fader edit is in flight. + assert(!pcm.setLiveMix(epoch-1,4,ch1,1.f,0.f)); + assert(!pcm.setLiveMix(epoch,3,ch2,1.f,0.f)); + assert(!pcm.setLiveMuteSolo(epoch,3,ch11,false,false)); + assert(!pcm.setLiveMuteSolo(epoch,4,ChannelId{987654},true,false)); + assert(render() && near(l[63],0.f) && near(rr[63],.2f)); + assert(pcm.acceptedGraphRevision()==4); + assert(near(pcm.acceptedRoster().find(ch1)->faderLinear,minus12)); + assert(near(pcm.acceptedRoster().find(ch11)->faderLinear,.5f)); + assert(pcm.acceptedRoster().find(ch1)->mute); + assert(pcm.acceptedRoster().find(ch11)->solo); + pcm.unpublish(); + pcm.pollRetirement(); +} + int main() { + verifyOriginalAndAddedInputsShareNativePcmControls(); + verifyPrimaryOutKeepsCanonicalEdgeIdentity(); + verifyDefaultNativeMainEdgeAndDisconnectedRestore(); + verifyAtomicWireTransactionAndZeroSampleHops(); + + // WIRE-first regression: PRE and POST to the SAME destination are + // NOT two valid edges. Reject before accepting duplicate dry PCM. + // A failed compile must preserve the previous prepared graph. + { + DynamicChannelRoster roster; + const std::array create{ + add(0,ChannelRole::input,"WIRE SRC"), + add(1,ChannelRole::main,"MAIN",ProcessingFormat::stereo) + }; + const auto created=roster.edit(0,create); + assert(created.ok() && created.createdIds.size()==2); + const auto src=created.createdIds[0], dst=created.createdIds[1]; + const std::array first{output(src,dst)}; + assert(roster.edit(1,first).ok()); + DynamicGraphRequest request; + request.maxFrames=64; + DynamicPreparedMixerBlock block; + DynamicGraphError fault; + assert(DynamicPreparedMixerBlock::compile(roster,request,block,fault)); + assert(block.channelCount()==2); + const std::array duplicate{send(src,dst,.5f,true)}; + assert(roster.edit(2,duplicate).ok()); // legacy draft may still hold it + assert(!DynamicPreparedMixerBlock::compile(roster,request,block,fault)); + assert(fault.fault==DynamicGraphFault::duplicateSend); + assert(block.channelCount()==2); // previous prepared PCM untouched + } + + verifyConsoleWirePrimaryOutputPcm(); + verifyRealtimeSlewAndNativeChannelIdContinuousControls(); constexpr std::uint64_t epoch=77; constexpr float center=.7071067811865475f; DynamicAcceptedSession session; @@ -56,13 +586,104 @@ int main() { const float gain=id==group?2.f:id==fx?.5f:1.f; for(int i=0;i(.2f+.4f)*center && l[3]<(.4f+.4f)*center); + assert(render(16)&&render(32)&&render(12)); + assert(near(l[11],(.4f+.4f)*center)); + assert(near(ml[11],(.4f*.2f+.4f*.25f)*center)); + // A last-target-wins reverse retains the same PCM and plugin graph. + assert(session.setLivePhysicalSource(epoch,2,micA,0,-1,false)); + assert(render()); + assert(near(l[63],(.2f+.4f)*center)); + assert(near(ml[63],(.2f*.2f+.4f*.25f)*center)); + assert(session.acceptedGraphRevision()==2); + // E1: structural draft pins are preflighted BEFORE accepted SOURCE + // reconciliation. Out-of-range or same-pin stereo must not be hidden by + // an earlier valid MONO source, falsely ACKed, or silence existing PCM. + ChannelEdit renameAttempt; + renameAttempt.kind=ChannelEdit::Kind::rename; + renameAttempt.id=micA; + renameAttempt.text="MUST_NOT_APPEAR_AFTER_REJECTION"; + const std::array structuralAttempt{renameAttempt}; + auto invalidSource=route; + invalidSource.sources[0].inputL=2; // exactly physicalInputs + auto deniedSource=session.edit(2,2,structuralAttempt,invalidSource,epoch,epoch,true); + assert(!deniedSource.ok()); + assert(deniedSource.fault==DynamicAcceptedSession::Fault::graphRejected); + assert(deniedSource.native.fault==DynamicNativeSessionPublisher::Fault::invalidGraph); + assert(deniedSource.native.graphError.fault==DynamicGraphFault::invalidSource); + assert(deniedSource.edit.createdIds.empty()); + assert(session.acceptedGraphRevision()==2); + assert(session.acceptedRosterRevision()==2); + assert(session.acceptedRoster().find(micA)->name=="LEAD"); + assert(session.acceptedPhysicalRequest().sources[0].inputL==0); + invalidSource=route; + invalidSource.sources[0].stereo=true; + invalidSource.sources[0].inputR=0; + deniedSource=session.edit(2,2,structuralAttempt,invalidSource,epoch,epoch,true); + assert(!deniedSource.ok() && + deniedSource.native.graphError.fault==DynamicGraphFault::invalidSource); + assert(render()&&near(l[63],(.2f+.4f)*center)); + // A physically valid but different pin is NOT an implicit IN request + // during RENAME/GROUP/OUT. Previously the old SOURCE was overlaid and + // an unfulfilled new pin was ACKed as successful (GUI/PCM disagreement). + auto validButUnacceptedSource=route; + validButUnacceptedSource.sources[0].inputL=1; + auto deniedValidSource=session.edit(2,2,structuralAttempt, + validButUnacceptedSource,epoch,epoch,true); + assert(!deniedValidSource.ok() && + deniedValidSource.fault==DynamicAcceptedSession::Fault::graphRejected); + assert(deniedValidSource.native.graphError.fault== + DynamicGraphFault::invalidSource); + assert(deniedValidSource.native.graphError.id==micA); + assert(session.acceptedGraphRevision()==2 && + session.acceptedPhysicalRequest().sources[0].inputL==0); + assert(session.acceptedRoster().find(micA)->name=="LEAD"); + assert(render()&&near(l[63],(.2f+.4f)*center)); + // One accepted ChannelId graph: realtime MUTE/SOLO and PRE/POST follow + // the same callback, not a recompilation or an extra FX instance. + assert(session.setLiveMuteSolo(epoch,2,micA,true,false)); + assert(session.acceptedRoster().find(micA)->mute); + assert(render(4)); + assert(l[3]>.4f*center && l[3]<.6f*center); + assert(render(16)&&render(32)&&render(12)); + assert(near(l[11],.4f*center)); + assert(near(ml[11],(.4f*.25f)*center)); + assert(session.setLiveMuteSolo(epoch,2,micA,false,true)); + assert(render()); + assert(near(l[63],.2f*center)); + assert(near(ml[63],(.2f*.2f)*center)); + assert(session.setLiveMuteSolo(epoch,2,main,true,false)); + assert(render()); + assert(near(l[63],0.f)&&near(r[63],0.f)); + assert(near(ml[63],(.2f*.2f)*center)); // independent MONITOR + assert(session.setLiveMuteSolo(epoch,2,main,false,false)); + assert(session.setLiveMuteSolo(epoch,2,micA,false,false)); + assert(render()); + assert(near(l[63],(.2f+.4f)*center)); + assert(near(ml[63],(.2f*.2f+.4f*.25f)*center)); + assert(!session.setLiveMuteSolo(epoch-1,2,micA,true,false)); + assert(!session.setLiveMuteSolo(epoch,1,micA,true,false)); + assert(!session.setLiveMuteSolo(epoch,2,ChannelId{987654},true,false)); + assert(!session.acceptedRoster().find(micA)->mute&& + !session.acceptedRoster().find(micA)->solo&& + session.acceptedGraphRevision()==2); // Control update is a real RT atomic, but is ALSO preserved by roster so // subsequent BUS compilation cannot silently reset fader/send gain. assert(session.setLiveMix(epoch,2,micA,.5f,0.f)); diff --git a/tests/engine_runtime_reconciliation_test.mjs b/tests/engine_runtime_reconciliation_test.mjs new file mode 100644 index 000000000..b12f24109 --- /dev/null +++ b/tests/engine_runtime_reconciliation_test.mjs @@ -0,0 +1,418 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Fast G0 architecture gate. Tests the INSTALLED owner (M4 compatibility) +// without pretending that the prepared ChannelId graph is live. +// When ChannelId cutover is actually approved, this gate MUST change in +// the same exact-SHA integration commit as the JUCE callback and native ACK. +import test from 'node:test'; +import vm from 'node:vm'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; + +const read=p=>readFileSync(p,'utf8'); +const engine=read('src/LiveAudioEngine.h'); +const host=read('src/Main.cpp'); +const cmake=read('CMakeLists.txt'); +const authority=read('engine/core/NativeRenderAuthority.h'); +const bridge=read('src/ConsoleLiveBridgeV6.h'); +const wire=read('engine/core/ConsolePuzzleV8Wire.h'); +const schema=JSON.parse(read('contracts/console-puzzle-v8.json')); +const worker=read('src/NativeShowSaveWorker.h'); +const showCapture=read('src/NativeLiveShowCapture.h'); +const showRecall=read('src/NativeDryShowRecall.h'); +const physical=read('src/LiveDryRoutingLab.h'); +const dynamic=read('engine/core/DynamicNativeSessionPublisher.h'); +const realtimePermit=read('engine/core/RealtimeRenderPermit.h'); +const start=engine.indexOf('void audioDeviceIOCallbackWithContext ('); +assert.ok(start>0,'missing ONE JUCE production callback'); +const callback=engine.slice(start); +const count=(s,pattern)=>[...s.matchAll(pattern)].length; + +test('exactly one production audio callback and one native PCM owner',()=>{ + assert.equal(count(engine,/void audioDeviceIOCallbackWithContext\s*\(/g),1); + assert.equal(count(host,/LiveAudioEngine engine_;/g),1); + assert.match(engine,/#include "\.\.\/engine\/core\/NativeRenderAuthority\.h"/); + assert.match(callback,/NativeRenderAuthority::select\(/); + assert.match(callback,/NativeRenderOwner::failSilentUnpatched/); + assert.match(callback,/NativeRenderOwner::acceptedM4Session/); + assert.equal(count(callback,/dryRoutingLab_\.process\(/g),1, + 'two native M4 PCM renders would double-sum or double-process vendor FX'); + assert.doesNotMatch(callback,/DynamicNativeSessionPublisher|DynamicAcceptedSession|\.publisher_\.render\(/, + 'unadmitted universal graph must never run alongside real M4 callback'); + assert.match(authority,/acceptedM4Session/); + assert.match(authority,/isolatedDiagnostic/); +}); + +test('unpatched is silent and diagnostic path cannot host a legacy second VST engine',()=>{ + const unpatched=callback.indexOf('NativeRenderOwner::failSilentUnpatched'); + const routed=callback.indexOf('NativeRenderOwner::acceptedM4Session'); + const isolated=callback.indexOf('// The only remaining stereo renderer is DIAGNOSTIC'); + const finish=callback.indexOf('const auto elapsedUs = clockMicros() - beginUs',isolated); + assert.ok(unpatched>=0&&routed>unpatched&&isolated>routed&&finish>isolated); + const first=callback.slice(unpatched,routed); + assert.match(first,/FloatVectorOperations::clear\(outputs\[c\], samples\)/); + assert.match(first,/handoff_\.endCycle\(cycle\)/, + 'plugin owner must still retire on the CONTROL thread when unpatched'); + const tail=callback.slice(isolated,finish); + assert.doesNotMatch(tail,/processor->processBlock|MidiBuffer midi|createPluginInstance|prepareToPlay/, + 'do not revive a hidden stereo plugin engine in diagnostic fallback'); + assert.match(tail,/diagnosticTone_\.next/); +}); + +test('original CH1 vendor FX/Orbit is leased exactly once in accepted M4 renderer',()=>{ + const old=engine.indexOf('static void renderOriginalChannelOneGraph('); + const end=engine.indexOf('void audioDeviceIOCallbackWithContext',old); + assert.ok(old>=0&&end>old); + const fx=engine.slice(old,end); + assert.match(fx,/slot\.processor->processBlock\(buffer,midi\)/); + assert.match(fx,/bypass\.request\(graph\.bypassFlags/); + assert.match(fx,/catch\(\.\.\.\)/); + assert.match(callback,/LegacyChannelOneLease ch1Lease\{cycle\.graph\}/); + assert.match(callback,/&processLegacyChannelOne/); + assert.doesNotMatch(callback,/std::make_unique<|std::make_shared<|createPluginInstance\(/, + 'no FX instantiation or graph allocation in device callback'); +}); + +test('occupied CH1 Orbit uses one strong Graph lease through native renderer and Show handoff',()=>{ + assert.match(engine,/std::shared_ptr graphOwned_\s*\{std::make_shared\(\)\}/); + assert.match(engine,/std::shared_ptr stagedOwner_/); + assert.match(engine,/fx\.owner=std::static_pointer_cast\(graphOwned_\)/); + assert.match(engine,/fx\.context=graphOwned_\.get\(\)/); + assert.match(engine,/fx\.render=&processOwnedChannelOne/); + assert.match(engine,/renderOriginalChannelOneGraph\(\s*\*static_cast\(token\)/); + assert.match(engine,/Graph\(\) \{ dryScratch\.setSize\(2,maxFrames,false,true,false\); \}/); + assert.match(engine,/graph\.dryScratch\.getWritePointer\(0\)/); + assert.match(engine,/graph\.orderPacked\.load\(std::memory_order_acquire\)/); + assert.match(engine,/dryRoutingLab_\.revokeChannelIdPcm\(\)/); + assert.equal(count(engine,/dryRoutingLab_\.revokeChannelIdPcm\(\)/g),2, + 'both Show recall and original CH1 ADD/REMOVE must revoke native renderer'); + assert.match(physical,/occupiedExternalCh1Fx>0,hw/); + assert.match(physical,/nativePublisher_,nativeAccepted_,std::move\(externalCh1\)/); + assert.match(physical,/channelIdPcmEpoch_\.store\(0,std::memory_order_release\)/); + assert.equal(count(engine,/void audioDeviceIOCallbackWithContext\s*\(/g),1); +}); + +test('E6 original CH1-10 and dynamic INPUT use one accepted native PCM control writer',()=>{ + const legacy=physical.slice(physical.indexOf('bool setChannelParameter('), + physical.indexOf('// Real AUX FX RETURN')); + const native=physical.slice(physical.indexOf('bool setNativeInputMix('), + physical.indexOf('bool nativeBusTopologyLive()')); + assert.ok(legacy.indexOf('if(channelIdPhysicalPcmActive())')>=0); + assert.ok(legacy.indexOf('setNativeInputMix(')>=0); + assert.ok(legacy.indexOf('setNativeInputMuteSolo(')>=0); + assert.ok(legacy.indexOf('setNativeInputMix(')< + legacy.indexOf('publisher_.updateActiveControl('), + 'legacy M4 PCM must never be mutated before accepted ChannelId write'); + assert.match(legacy,/if\(!accepted\)return false/); + assert.doesNotMatch(native,/for\(const auto original/); + assert.doesNotMatch(native,/!nativeStructureLive_\|\|!channelIdPhysicalPcmActive/); + assert.match(native,/nativeAccepted_\.deviceEpoch!=epochValue/); + assert.match(native,/nativePublisher_\.setChannelMix/); + assert.match(native,/nativePublisher_\.setChannelMuteSolo/); + assert.match(native,/nativeAccepted_\.graph\.roster\.rememberLiveMix/); + assert.match(native,/nativeAccepted_\.graph\.roster\.rememberLiveMuteSolo/); + assert.match(physical,/nativeStructureLive_ \|\| nativeControlDirty_/); + assert.match(physical,/void rejectedNativeMirror\(\) noexcept \{[\s\S]*?nativeControlDirty_/); + assert.match(physical,/nativeControlDirty_=false; \/\/ fresh accepted legacy\/native/); +}); + +test('E3 stable ChannelId GROUP/FX RETURN is a real guarded physical PCM transaction',()=>{ + assert.match(physical,/NativeBusResult editNativeBus\(/); + assert.match(physical,/next\.createBusForSelected\(/); + assert.match(physical,/next\.removeBusAndRestoreSources\(/); + assert.match(physical,/DynamicChannelFxLeaseBank::reuseRevision\(/); + assert.match(physical,/nativePublisher_\.commit\(/); + assert.match(physical,/nativeAccepted_\.graph\.roster=std::move\(next\)/); + assert.match(physical,/if\(!published\.ok\(\)\)/); + assert.match(physical,/nativeStructureLive_=nativeAccepted_\.graph\.roster\.size\(\)/); + assert.match(physical,/nativeAccepted_\.hardware\.monitorEnabled/); + assert.match(physical,/topologyFault_\.store\(true,std::memory_order_release\)/); + assert.match(engine,/LiveDryRoutingLab::NativeBusResult editNativeBus\(/); + assert.match(engine,/if\(dryRoutingLab_\.nativeBusTopologyLive\(\)\)return false/); + assert.match(bridge,/juce::var processNativeBusIntent\(/); + assert.match(bridge,/nativeGraphRevision/); + assert.match(bridge,/NATIVE_CREATE_GROUP_SELECTED/); + assert.match(bridge,/NATIVE_CREATE_FX_RETURN_SELECTED/); + assert.match(bridge,/NATIVE_REMOVE_BUS/); + assert.match(host,/consoleBridge_\.processNativeBusIntent\(/); + assert.match(bridge,/w\.productionCallbackLive=false/); + assert.match(wire,/callbackOwnsChannelIds/); + assert.match(physical,/nativeBusStructural/); + assert.match(showCapture,/nativeBusStructural/); + assert.match(showRecall,/nativeBusStructural/); + assert.equal(count(callback,/dryRoutingLab_\.process\(/g),1); +}); + + + +test('E5 rejected M4 structural edit and failed re-admission preserve native BUS PCM',()=>{ + const apply=physical.slice(physical.indexOf('juce::String apply ('),physical.indexOf('juce::String repatchPhysicalSource(')); + assert.match(apply,/nativeStructureLive_ && nativeAccepted_\.deviceEpoch==epoch\(\)/, + 'same-epoch native BUS blocks legacy M4 compilation before graph publication'); + assert.match(apply,/REMOVE native GROUP\/FX RETURN buses before replacing the M4 route/); + const admission=physical.slice(physical.indexOf('bool admitChannelIdFromAcceptedM4('), + physical.indexOf('bool originalM4Aux(')); + const commit=admission.indexOf('UnifiedLegacyProductionAdmission::compileAndCommit('); + assert.ok(commit>0,'native re-admission must commit genuine PCM'); + const dynamicFence=admission.indexOf('if(nativeStructureLive_ && nativeAccepted_.deviceEpoch==epoch())'); + const fixedFallback=admission.indexOf('channelIdPcmEpoch_.store(0,std::memory_order_release)'); + assert.ok(dynamicFence>=0 && fixedFallback>dynamicFence, + 'dynamic BUS cannot be demoted, but rejected fixed M4 migration must select matching M4 PCM'); + assert.match(admission,/nativeStructureLive_=false;/); + assert.ok(admission.indexOf('channelIdPcmEpoch_.store(generation',commit)>commit); + assert.match(engine,/if \(dryRoutingLab_\.nativeBusTopologyLive\(\)\)\s*return "REMOVE native GROUP\/FX RETURN buses/); + assert.equal(count(callback,/dryRoutingLab_\.process\(/g),1); +}); + + +test('E5 native FX return cannot advertise a no-VST dry-doubling physical bus',()=>{ + const structural=physical.slice(physical.indexOf('NativeBusResult editNativeBus('), + physical.indexOf('bool nativeBusTopologyLive()')); + assert.match(structural,/role==ChannelRole::fxReturn/); + assert.match(structural,/FX_RETURN_REQUIRES_NATIVE_VST3_OWNER/); + assert.match(structural,/DynamicChannelFxLeaseBank::reuseRevision/); + const advertised=physical.slice(physical.indexOf('juce::var nativeBusStatus() const'), + physical.indexOf('void disable() noexcept')); + assert.match(advertised,/"NATIVE_CREATE_GROUP_SELECTED"/); + assert.match(advertised,/"NATIVE_REMOVE_BUS"/); + assert.doesNotMatch(advertised,/"NATIVE_CREATE_FX_RETURN_SELECTED"/, + 'physical operator cannot create a parallel return without a real native insert'); +}); + +test('E4 installed PATCH operator uses native ChannelId BUS ACK and real PCM snapshot, never ten-strip draft',()=>{ + const ui=read('web/monitor.js'); + const binding=ui.slice(ui.indexOf('// E4: The EXISTING routing workspace controls'), + ui.indexOf('// Processing channel width is independent')); + assert.ok(binding.length>3000,'real native Group/FX operator binding absent'); + assert.match(binding,/const nativeBusAccepted=\(\)=>/); + assert.match(binding,/legacy\?\.controlPlane!=='LEGACY_M4_ORDINAL'/); + assert.match(binding,/legacy\?\.pcmRenderer!=='CHANNEL_ID_10CH4AUX'/); + assert.match(binding,/busWireDecimal\(c\.id\)===null/); + assert.match(binding,/bus\.supportedOps\.includes\(op\)/); + assert.match(binding,/state\.secondaryOutputArmed/); + assert.match(binding,/state\.monitor/); + assert.match(binding,/!mixerDraftActive/); + assert.match(binding,/targetChannelId:targetChannelId\|\|null,payload/); + assert.match(binding,/selectedChannelIds:ids,sendGain:gain/); + assert.match(binding,/api\.emitEvent\('arMixConsoleIntent',command\)/); + assert.match(binding,/api\.addEventListener\('arMixConsoleAck'/); + assert.match(binding,/api\.addEventListener\('arMixConsoleSnapshot'/); + assert.match(binding,/busSnapshotSerial>busPending\.ackSnapshotSerial/); + assert.match(binding,/BigInt\(info\.bus\.graphRevision\)>=BigInt\(ack\.nativeGraphRevision\)/); + assert.match(binding,/BigInt\(info\.bus\.rosterRevision\)>=BigInt\(ack\.nativeRosterRevision\)/); + assert.match(binding,/NATIVE_CREATE_GROUP_SELECTED/); + assert.match(binding,/NATIVE_CREATE_FX_RETURN_SELECTED/); + assert.match(binding,/NATIVE_REMOVE_BUS/); + assert.match(binding,/NATIVE_SET_BUS_MIX/); + assert.doesNotMatch(binding,/productionCallbackLive\s*=\s*true|createAudioContext|AudioContext\(/, + 'operator MUST NOT fabricate universal capabilities or DSP'); + assert.match(ui,/busRequest\(\);renderNativeBus\(true\)/); + assert.match(bridge,/processNativeBusIntent/); + assert.match(physical,/nativeBusStatus\(\)/); +}); + + +test('E4 operator native Group+FX Return controls run through real ACK then newer accepted PCM snapshot',()=>{ + const ui=read('web/monitor.js'); + const start=ui.indexOf('// E4: The EXISTING routing workspace controls'); + const end=ui.indexOf('// Processing channel width is independent',start); + assert.ok(start>0&&end>start,'E4 actual route controller must exist'); + class Node { + constructor(tag){this.tag=tag;this.children=[];this.listeners={}; + this.value='';this.disabled=false;this.checked=false;this.textContent=''; + this.className='';this.id='';this.attrs={};} + setAttribute(name,value){this.attrs[name]=value;} + append(...children){this.children.push(...children);} + replaceChildren(...children){this.children=[...children];} + addEventListener(name,fn){this.listeners[name]=fn;} + insertAdjacentElement(_,child){this.children.push(child);} + } + const root=new Node('section'),nativeCap=new Node('span'),sent=[],events={}; + const doc={createElement:tag=>new Node(tag), + createTextNode:text=>({textContent:text}), + getElementById:id=>id==='arBusCapability'?root:null}; + const api={emitEvent:(name,payload)=>sent.push({name,payload}), + addEventListener:(name,fn)=>events[name]=fn}; + const ctx=vm.createContext({ + document:doc,api,window:{crypto:{getRandomValues:n=>n.fill(7)}}, + routeOverlay:{classList:{contains:()=>true}, + querySelector:selector=>selector==='[data-bus-cap="missing"]'?nativeCap:null}, + state:{monitor:false,secondaryOutputArmed:false}, + patchPending:false,mixerDraftActive:false + }); + vm.runInContext(ui.slice(start,end),ctx,{timeout:1000}); + const snap=(revision='10',roster='3',epoch='12',armed=false)=>({ + schemaVersion:6,productionCallbackLive:false, + device:{epoch,outputArmed:armed}, + legacyM4:{controlPlane:'LEGACY_M4_ORDINAL', + pcmRenderer:'CHANNEL_ID_10CH4AUX',routingRevision:'7', + nativeBus:{graphRevision:revision,rosterRevision:roster, + supportedOps:['NATIVE_CREATE_GROUP_SELECTED', + 'NATIVE_CREATE_FX_RETURN_SELECTED','NATIVE_SET_BUS_MIX', + 'NATIVE_REMOVE_BUS'], + channels:[{id:'1',role:'INPUT',name:'Microphone'}, + {id:'2',role:'INPUT',name:'Music'}, + {id:'3',role:'MAIN',name:'MAIN'}, + // Accepted original M4 AUX1 has FX_RETURN role but its owner is + // NOT the dynamic E3 BUS edit transport: must stay read-only here. + {id:'4',role:'FX_RETURN',name:'AUX 1',nativeManaged:false, + fader:1,pan:0}]}} + }); + events.arMixConsoleSnapshot(snap()); + const probe=code=>vm.runInContext(code,ctx,{timeout:1000}); + assert.equal(probe('groupCreate.disabled'),false); + assert.equal(probe('nativeBusSources.children.length'),2); + assert.equal(probe('nativeBusRows.children.length'),0, + 'original M4 AUX receiver must never expose native REMOVE/mix controls'); + assert.match(nativeCap.textContent,/NATIVE PCM ACTIVE/); + probe("nativeBusSources.children[0].children[0].checked=true"); + probe("nativeBusSources.children[0].children[0].listeners.change()"); + probe("nativeBusName.value='Vocal Group';nativeBusGain.value='.6';groupCreate.listeners.click()"); + const commands=()=>sent.filter(x=>x.name==='arMixConsoleIntent'); + assert.equal(commands().length,1); + const one=commands()[0].payload; + assert.equal(one.operation,'NATIVE_CREATE_GROUP_SELECTED'); + assert.deepEqual(Array.from(one.payload.selectedChannelIds),['1']); + assert.equal(one.deviceEpoch,'12'); + assert.equal(one.legacyRoutingRevision,'7'); + assert.equal(one.nativeGraphRevision,'10'); + assert.equal(one.nativeRosterRevision,'3'); + assert.equal(one.payload.sendGain,.6); + assert.equal(probe('groupCreate.disabled'),true); + probe('groupCreate.listeners.click()'); + assert.equal(commands().length,1,'pending request must block duplicate AUDIO graph commit'); + // Engine ACK only proves acceptance. The UI stays locked until a + // strictly newer accepted PCM publisher snapshot supplies real revisions. + events.arMixConsoleAck({ + requestId:one.requestId,status:'ACCEPTED',deviceEpoch:'12', + nativeGraphRevision:'11',nativeRosterRevision:'4',errorCode:'' + }); + assert.equal(probe('groupCreate.disabled'),true); + events.arMixConsoleSnapshot(snap('10','3')); + assert.equal(probe('groupCreate.disabled'),true); + const updated=snap('11','4'); + updated.legacyM4.nativeBus.channels.splice(2,0,{ + id:'20',role:'GROUP',name:'Vocal Group',nativeManaged:true,fader:1,pan:0}); + events.arMixConsoleSnapshot(updated); + assert.equal(probe('groupCreate.disabled'),false); + assert.equal(probe('nativeBusRows.children.length'),1); + // Browser cannot forge a BUS by sending the universal graph capability: + // authoritative namespace must be ChannelId PCM actually installed. + const bogus=snap('12','5');bogus.legacyM4.pcmRenderer='M4_COMPAT'; + events.arMixConsoleSnapshot(bogus); + assert.equal(probe('groupCreate.disabled'),true); + probe("fxReturnCreate.listeners.click()"); + assert.equal(commands().length,1,'no synthetic native BUS without production PCM'); + events.arMixConsoleSnapshot(updated); + probe("nativeBusSources.children[0].children[0].checked=true"); + probe("nativeBusSources.children[0].children[0].listeners.change()"); + probe("nativeBusName.value='Vocal Wet';fxReturnCreate.listeners.click()"); + assert.equal(commands().length,2); + assert.equal(commands()[1].payload.operation,'NATIVE_CREATE_FX_RETURN_SELECTED'); + events.arMixConsoleAck({ + requestId:commands()[1].payload.requestId,status:'REJECTED', + deviceEpoch:'12',errorCode:'NATIVE_REJECTED' + }); + assert.equal(probe('groupCreate.disabled'),false, + 'rejected native intent should unlock controls while keeping old PCM unchanged'); + assert.match(probe('nativeBusState.textContent'),/REJECTED.*NATIVE_REJECTED/); + events.arMixConsoleSnapshot(snap('11','4','11')); + assert.equal(probe('busSession'),'12','old device generation must not replace live native BUS'); + const armed=snap('11','4','12',true); + events.arMixConsoleSnapshot(armed); + assert.equal(probe('groupCreate.disabled'),true,'output armed structural edits fail closed'); + probe("groupCreate.listeners.click()"); + assert.equal(commands().length,2); +}); + +test('E4 original 4 M4 AUX return IDs are immutable under dynamic native BUS edits',()=>{ + const physical=read('src/LiveDryRoutingLab.h'); + const ui=read('web/monitor.js'); + assert.match(physical,/bool originalM4Aux\(armix::mixer::ChannelId id\) const noexcept/); + assert.match(physical,/for\(const auto aux:nativeAccepted_\.graph\.ids\.aux\)/); + assert.match(physical,/if\(remove\.value && originalM4Aux\(remove\)\)/); + assert.match(physical,/FIXED_M4_AUX_NOT_REMOVABLE/); + assert.match(physical,/originalM4Aux\(id\)/); + assert.match(physical,/row->setProperty\("nativeManaged",/); + assert.match(ui,/x\.nativeManaged===true/); + assert.doesNotMatch(ui.slice(ui.indexOf('// E4: The EXISTING routing workspace controls'), + ui.indexOf('// Processing channel width is independent')),/M4_AUX_REMOVE|legacyAUXIdByIndex/, + 'Do not invent legacy AUX identities in the browser'); +}); + +test('shipping application does not compile a second test-only native mixer',()=>{ + const app=cmake.split(/\r?\n/).find(l=>l.startsWith('target_sources(ARMixConsole PRIVATE')); + assert.ok(app,'native JUCE application source list missing'); + assert.match(app,/src\/LiveAudioEngine\.h/); + assert.match(app,/engine\/core\/NativeRenderAuthority\.h/); + assert.doesNotMatch(app,/PreparedNativeMixerSession|DynamicNativeSessionPublisher|DynamicPreparedMixerBlock|UnifiedLegacyProductionAdmission|LegacyLiveGraphMigration/, + 'prepared graph may be compiled as tests/includes, not advertised as a second application entry point'); + assert.match(cmake,/target_sources\(ARMixNativeMixerSessionTests PRIVATE tests\/prepared_native_mixer_session_test\.cpp engine\/core\/PreparedNativeMixerSession\.h\)/); +}); + +test('GUI projection cannot falsely claim the prepared ChannelId engine is live',()=>{ + assert.equal(schema.schemaVersion,6); + assert.deepEqual(schema.wire.events, + ['arMixConsoleSubscribe','arMixConsoleSnapshot','arMixConsoleIntent','arMixConsoleAck']); + for(const item of ['deviceEpoch','baseGraphRevision','baseRosterRevision','requestId','targetChannelId']) + assert.ok(schema.intentRequired.includes(item)); + assert.ok(bridge.includes('w.productionCallbackLive=false')); + assert.match(bridge,/legacyM4/); + assert.match(wire,/callbackOwnsChannelIds\\":false/); + assert.match(wire,/fullVendorFxMigration\\":false/); + assert.ok(wire.includes('supportedOps')); + assert.match(bridge,/parseNativeChannelId/); + assert.match(bridge,/validConsoleRequestId/); +}); + +test('workers handle Show IO outside the audio callback, not as a second DSP engine',()=>{ + assert.match(worker,/class NativeShowSaveWorker final : private juce::Thread/); + assert.match(worker,/store\.commit\(show,\{snapshot_\},blobs_\)/); + assert.match(worker,/void releaseJob\(\)/); + assert.doesNotMatch(callback,/NativeShowStore|\.loadWithStates\(|\.commit\(show/); +}); + +test('E2 uses exactly one installed JUCE callback with admitted native ChannelId PCM and M4 fallback',()=>{ + assert.match(engine,/dryRoutingLab_\.admitChannelIdFromAcceptedM4\(/); + assert.match(physical,/UnifiedLegacyProductionAdmission::compileAndCommit\(/); + assert.match(physical,/channelIdPcmEpoch_\.store\(generation,std::memory_order_release\)/); + assert.match(physical,/const bool channelIdRender=/); + assert.match(physical,/if\(channelIdRender\)\s*\{/); + assert.match(physical,/nativePublisher_\.render\(/); + assert.match(physical,/else \{\s*processed=snapshot->prepared->process\(/); + assert.equal(count(callback,/dryRoutingLab_\.process\(/g),1); + assert.equal(count(callback,/DynamicNativeSessionPublisher::render\(/g),0, + 'a second JUCE native renderer may not be installed'); + assert.match(physical,/channelIdPcmEpoch_\.store\(0,std::memory_order_release\)/, + 'stale epoch and structural edits must turn off the native selector'); + assert.match(physical,/channelIdPhysicalPcmActive\(/, + 'live GUI scalar control must follow the admitted native renderer'); + assert.match(engine,/dryRoutingLab_\.revokeChannelIdPcm\(\)/, + 'original CH1 FX publication must first retire native PCM authority'); + assert.match(physical,/nativePublisher_\.pollRetirement\(\)/, + 'native VST owner generations must retire off audio callback'); +}); + +test('installed M4 and future ChannelId share one nonblocking render permit',()=>{ + assert.ok(physical.includes('RealtimeRenderPermit exclusive{rendering_}')); + assert.ok(dynamic.includes('RealtimeRenderPermit exclusive{rendering_}')); + assert.ok(realtimePermit.includes('test_and_set(std::memory_order_acquire)')); + assert.ok(realtimePermit.includes('clear(std::memory_order_release)')); + assert.ok(!realtimePermit.includes('std::mutex') && !realtimePermit.includes('condition_variable')); + assert.ok(physical.includes('if(!exclusive)')); + assert.ok(dynamic.includes('if(!exclusive)')); +}); + +test('legacy M4 operations are advertised separately, not as fake universal ChannelIds',()=>{ + assert.ok(bridge.includes('LEGACY_M4_ORDINAL')); + assert.ok(bridge.includes('acceptedChannels')); + assert.ok(bridge.includes('route.getProperty("topologyFault",false)')); + assert.ok(bridge.includes('object->setProperty("supportedOps",juce::var(allowed))')); + assert.ok(bridge.includes('w.productionCallbackLive=false')); + assert.ok(wire.includes('supportedOps')); +}); + +test('legacy M4 GUI commands require accepted physical authority, not just guessed ordinal',()=>{ + assert.ok(bridge.includes('.getProperty("controlPlane","").toString()!="LEGACY_M4_ORDINAL"')); + assert.ok(bridge.includes('PRODUCTION_GRAPH_NOT_ADMITTED')); + assert.ok(bridge.includes('legacyRoutingRevision')); +}); diff --git a/tests/fixtures/console-v8-native-unready.json b/tests/fixtures/console-v8-native-unready.json new file mode 100644 index 000000000..c4b3d9549 --- /dev/null +++ b/tests/fixtures/console-v8-native-unready.json @@ -0,0 +1 @@ +{"events":[{"event":"arMixConsoleSnapshot","payload":{"schemaVersion":6,"productionCallbackLive":false,"device":{"epoch":"1","backend":"","captureDevice":"","playbackDevice":"","inputEndpoints":[],"outputEndpoints":[],"enabledInputs":[],"enabledOutputs":[],"sampleRate":null,"bufferFrames":null,"outputArmed":false},"graph":{"revision":"0","rosterRevision":"0","channels":[],"destinations":[],"capabilities":{"callbackOwnsChannelIds":false,"fullVendorFxMigration":false,"showAndOutputParity":false,"physicalCaptureMapped":false,"dynamicChannels":false,"groups":false,"fxReturns":false,"monitor":false,"sendsOnFaders":false,"supportedOps":[]}},"telemetry":{"rawCapturePresent":false,"rawCapturePeak":0,"mainPcmPresent":false,"monitorPcmPresent":false,"channelMeterRmsPeak":[]},"legacyM4":{"active":false,"routeAccepted":false,"routingRevision":"0"}}},{"event":"arMixConsoleIntent","payload":{"requestId":"native-fixture-session:1","deviceEpoch":"1","baseGraphRevision":"0","baseRosterRevision":"0","operation":"SET_SOURCE","targetChannelId":null,"payload":{}}},{"event":"arMixConsoleAck","payload":{"requestId":"native-fixture-session:1","status":"REJECTED","deviceEpoch":"1","graphRevision":"0","rosterRevision":"0","errorCode":"UNIVERSAL_CALLBACK_NOT_READY"}},{"event":"arMixConsoleSnapshot","payload":{"schemaVersion":6,"productionCallbackLive":false,"device":{"epoch":"1","backend":"","captureDevice":"","playbackDevice":"","inputEndpoints":[],"outputEndpoints":[],"enabledInputs":[],"enabledOutputs":[],"sampleRate":null,"bufferFrames":null,"outputArmed":false},"graph":{"revision":"0","rosterRevision":"0","channels":[],"destinations":[],"capabilities":{"callbackOwnsChannelIds":false,"fullVendorFxMigration":false,"showAndOutputParity":false,"physicalCaptureMapped":false,"dynamicChannels":false,"groups":false,"fxReturns":false,"monitor":false,"sendsOnFaders":false,"supportedOps":[]}},"telemetry":{"rawCapturePresent":false,"rawCapturePeak":0,"mainPcmPresent":false,"monitorPcmPresent":false,"channelMeterRmsPeak":[]},"legacyM4":{"active":false,"routeAccepted":false,"routingRevision":"0"}}}]} diff --git a/tests/fx_add_contract_test.mjs b/tests/fx_add_contract_test.mjs index 2b449ac4e..50a8d09a2 100644 --- a/tests/fx_add_contract_test.mjs +++ b/tests/fx_add_contract_test.mjs @@ -33,7 +33,11 @@ test('every ADD click identifies request and reports result inside the open sele assert.match(host,/FX_LOAD_FAIL/); }); test('plugin load and preset restore both negotiate existing VST3 bus layouts',()=>{ - assert.equal((dsp.match(/prepareStereoEffectLayout/g)||[]).length,2); + // Legacy ADD + preset restore + native dynamic ChannelId insert share one + // JUCE stereo layout negotiator; no extra fake plugin host is allowed. + assert.equal((dsp.match(/prepareStereoEffectLayout/g)||[]).length,3); + assert.match(dsp,/LiveDryRoutingLab::NativeBusResult installNativeVst3/); + assert.match(dsp,/dryRoutingLab_\.attachNativeInsert/); assert.match(layout,/if \(compatible \(original\)\) return \{\};/); assert.match(layout,/requested\.inputBuses\.set \(i, disabled\)/); assert.match(layout,/processor\.setBusesLayout \(requested\)/); diff --git a/tests/live_channel_fx_graph_test.cpp b/tests/live_channel_fx_graph_test.cpp index 0dd136630..515c7481c 100644 --- a/tests/live_channel_fx_graph_test.cpp +++ b/tests/live_channel_fx_graph_test.cpp @@ -1,7 +1,13 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/core/LiveChannelFxGraph.h" +#include "../engine/core/DynamicChannelFxLeaseBank.h" +#include "../engine/core/DynamicNativeSessionPublisher.h" +#include "../engine/core/UnifiedLegacyProductionAdmission.h" #include "../engine/core/NativeOutputPairTap.h" #include "../engine/core/RealtimeRoutePublisher.h" +#include "../src/ConsoleLiveBridgeV6.h" +#include "../src/NativeVerifiedSourcePatch.h" +#include "../engine/core/NativeDryRouteCommand.h" #if defined(NDEBUG) #undef NDEBUG #endif @@ -13,6 +19,10 @@ #include #include #include +#include +#include +#include +#include using namespace armix::mixer; static std::atomic heapCalls{0}; @@ -87,7 +97,1793 @@ static std::unique_ptr makeGraph(float firstFx,float returnF assert(graph->maxFramesPerPlugin()==32); // clamp minimum safe plugin quantum return graph; } -int main() { +// M5: real M4 JUCE plugin instances survive ChannelId graph migration. +// CH11 and FX Return are not borrowed legacy strips: they receive their own +// native processor leases and execute in the same prepared PCM schedule. +static void verifyUniversalChannelIdFxLeaseAndLivePcm() { + using Bank=DynamicChannelFxLeaseBank; + DynamicChannelRoster roster; + std::array adds{}; + for(int i=0;i<4;++i) { + auto& op=adds[static_cast(i)]; + op.kind=ChannelEdit::Kind::add; + op.position=static_cast(i); + op.role=i==2?ChannelRole::fxReturn:i==3?ChannelRole::main:ChannelRole::input; + op.format=i<2?ProcessingFormat::mono:ProcessingFormat::stereo; + op.text=i==0?"CH1":i==1?"CH11":i==2?"FX RETURN":"MAIN"; + } + const auto created=roster.edit(0,adds); + assert(created.ok()&&created.createdIds.size()==4); + const auto ch1=created.createdIds[0],ch11=created.createdIds[1]; + const auto ret=created.createdIds[2],main=created.createdIds[3]; + std::vector wire; + const auto link=[&](ChannelId src,ChannelId dst,bool primary, + float gain=1.f) { + ChannelEdit op;op.kind=ChannelEdit::Kind::addSendReference; + op.id=src;op.target=dst;op.value=gain;op.primaryOutput=primary; + wire.push_back(std::move(op)); + }; + link(ch1,main,true); + link(ch11,main,true); + link(ret,main,true); + link(ch11,ret,false,.5f); + ChannelEdit marker;marker.kind=ChannelEdit::Kind::addInsertReference; + marker.id=ret;marker.text="native-vst3-fx-return"; + wire.push_back(std::move(marker)); + assert(roster.edit(roster.revision(),wire).ok()); + const std::array selected{ch1,ch11}; + const auto group=roster.createBusForSelected( + roster.revision(),selected,"VOCAL GROUP",ChannelRole::group); + assert(group.ok()&&group.createdIds.size()==1); + const auto bus=group.createdIds[0]; + // The accepted routing view, not a UI draft, proves exclusive primary OUT. + + DynamicGraphRequest req; + req.physicalInputs=2;req.maxFrames=32; + req.sources={{ch1,0,-1,false},{ch11,1,-1,false}}; + DynamicNativeSessionPublisher native; + constexpr std::uint64_t epoch=991; + assert(native.commit(roster,req,0,epoch,epoch,true).ok()); + const auto* view=native.acceptedRouting(epoch,1); + assert(view&&view->find(ch11)&&view->find(bus)); + assert(view->find(ch11)->primaryOutput==bus); + assert(view->find(bus)->primaryOutput==main); + + auto original=makeGraph(2.f,3.f); + Bank::Assignment first,groupOwner; + assert(Bank::captureLegacy(0,ch1,ProcessingFormat::mono,*original,first)); + assert(Bank::captureLegacy(1,bus,ProcessingFormat::stereo,*original,groupOwner)); + // These are genuinely new CH11/FX Return native instances. The M4 + // vendor processor ownership class and binary state path are reused. + const auto newFx=[&](float g,const char* catalog)->Bank::Lease { + auto p=std::make_unique(g); + p->prepareToPlay(48000.0,64); + return std::make_shared( + std::move(p),juce::String(catalog),juce::String(catalog),64); + }; + Bank::Assignment eleven;eleven.id=ch11;eleven.format=ProcessingFormat::mono; + eleven.inserts.push_back(newFx(4.f,"ch11-gain")); + Bank::Assignment returnFx;returnFx.id=ret;returnFx.format=ProcessingFormat::stereo; + returnFx.inserts.push_back(newFx(2.f,"fx-return-gain")); + std::array assignments{first,eleven,groupOwner,returnFx}; + Bank bank; + // The accepted FX owner and native PCM must share the NEXT graph revision. + assert(Bank::prepare(epoch,native.acceptedRevision()+1,assignments,bank)== + Bank::Fault::none); + assert(bank.lanes()==4&&bank.insertCount(ch11)==1&& + bank.insertCount(bus)==1&&bank.insertCount(ret)==1); + // Production control transaction appends a NEW real vendor instance + // to CH11 without touching original CH1, Group or FX Return owners. + Bank expanded; + auto second=newFx(1.25f,"ch11-second-vst3"); + assert(Bank::appendOwned(epoch,3,bank,ch11,ProcessingFormat::mono, + second,expanded)==Bank::Fault::none); + assert(expanded.insertCount(ch11)==2); + assert(expanded.insertCount(ch1)==bank.insertCount(ch1)); + assert((*expanded.ownerForControl(ch11,0))->instanceId== + (*bank.ownerForControl(ch11,0))->instanceId); + assert((*expanded.ownerForControl(ch11,1))->instanceId==second->instanceId); + assert(Bank::appendOwned(epoch,2,bank,ch11,ProcessingFormat::mono, + second,expanded)==Bank::Fault::invalidEpoch); + assert(expanded.revision()==3); + assert(Bank::appendOwned(epoch,4,expanded,ch11,ProcessingFormat::mono, + second,bank)==Bank::Fault::duplicateInstance); + assert(bank.revision()==2); // rollback left original accepted rack intact + + assert(bank.ownerForControl(ch1,0)&& + (*bank.ownerForControl(ch1,0))->instanceId== + original->insertInstanceId(0,0)); + Bank blocked; + std::array alias{first,groupOwner}; + alias[1].id=ch11; + alias[1].inserts=first.inserts; // same native processor twice + assert(Bank::prepare(epoch,2,alias,blocked)==Bank::Fault::duplicateInstance); + assert(blocked.lanes()==0); + // Native PDC is not yet installed. A real JUCE AudioProcessor reporting + // 64 samples of plugin delay must be rejected BEFORE accepted PCM/lease + // publication; mixing uncompensated Return with MAIN is phase-unsafe. + auto latentProcessor=std::make_unique(1.5f); + latentProcessor->setLatencySamples(64); + latentProcessor->prepareToPlay(48000.0,64); + Bank::Assignment latent; + latent.id=ch11;latent.format=ProcessingFormat::mono; + latent.inserts.push_back(std::make_shared( + std::move(latentProcessor),"latent-vst","latency-64",64)); + const std::array latentScene{latent}; + assert(Bank::prepare(epoch,2,latentScene,blocked)== + Bank::Fault::uncompensatedLatency); + assert(blocked.lanes()==0); // failed admission cannot mutate previous bank + assert(Bank::prepare(epoch,2,assignments,blocked)==Bank::Fault::none); + const auto token=original->insertInstanceId(0,0); + auto migrated=*bank.ownerForControl(ch1,0); + assert(migrated->instanceId==token); + original.reset(); // vendor instances retained by bank, no new VST3 scan + assert(GainFx::living>=4); + auto acceptedOwner=std::make_shared(std::move(bank)); + DynamicNativeSessionPublisher::FxPlan ownerPlan; + ownerPlan.owner=std::static_pointer_cast(acceptedOwner); + ownerPlan.context=acceptedOwner.get(); + ownerPlan.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(ctx))(id,l,r,n); + }; + ownerPlan.deviceEpoch=epoch;ownerPlan.graphRevision=2; + assert(ownerPlan.valid()); + // A mismatched raw callback context cannot be published or overwrite a + // working hardware graph. This is not a UI flag or an unchecked pointer. + auto wrong=ownerPlan;wrong.context=nullptr; + assert(native.commit(roster,req,1,epoch,epoch,true,std::move(wrong)).fault== + DynamicNativeSessionPublisher::Fault::invalidCandidate); + assert(native.acceptedRevision()==1); + assert(native.commit(roster,req,1,epoch,epoch,true,ownerPlan).ok()); + assert(native.acceptedRevision()==2); + // Only the accepted snapshot retains the vendor bank; local control + // holders can retire without losing a live VST during callback. + acceptedOwner.reset(); + std::array mic{},music{},left{},right{}; + mic.fill(.2f);music.fill(.1f); + const float* pins[]{mic.data(),music.data()}; + int legacyFallbackCalls=0; + const auto legacyFx=[&](ChannelId,float*,float*,int) noexcept { + ++legacyFallbackCalls; + }; + const auto beforeHeap=heapCalls.load(std::memory_order_relaxed); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(legacyFallbackCalls==0); // never dual-render M4 + M5 + assert(heapCalls.load(std::memory_order_relaxed)==beforeHeap); + constexpr float center=.7071067811865475f; + // Main: (CH1 .2*2 + CH11 .1*4) * mono pan * GROUP FX3 + // + CH11 post-send .5 * FX Return VST2 (no extra dry source). + assert(near(left[31],((.2f*2.f+.1f*4.f)*3.f+ + (.1f*4.f)*.5f*2.f)*center)); + assert(near(left[31],right[31])); + // E2: bypass a REAL hosted JUCE VST in the SAME native ChannelId graph. + // Acknowledged plugin identity, epoch and revision must all agree. The + // bypass uses FxInstance's existing 8ms audio-thread envelope, not a + // second DSP path or a control-thread plugin restart. + auto* acceptedBank=static_cast(ownerPlan.context); + const auto ch11Id=(*acceptedBank->ownerForControl(ch11,0))->instanceId; + const int livingAtBypass=GainFx::living; + assert(!acceptedBank->setInsertBypass(epoch-1,2,ch11,0,ch11Id,true)); + assert(!acceptedBank->setInsertBypass(epoch,1,ch11,0,ch11Id,true)); + assert(!acceptedBank->setInsertBypass(epoch,2,ch11,0,"wrong-token",true)); + assert(!acceptedBank->setInsertBypass(epoch,2,ch11,1,ch11Id,true)); + { + auto editorLease=acceptedBank->leaseEditor(epoch,2,ch11,0,ch11Id); + assert(editorLease && editorLease->instanceId==ch11Id); + assert(!acceptedBank->leaseEditor(epoch,1,ch11,0,ch11Id)); + assert(!acceptedBank->leaseEditor(epoch,2,ch11,0,"wrong-token")); + } + assert(acceptedBank->setInsertBypass(epoch,2,ch11,0,ch11Id,true)); + for(int i=0;i<16;++i) + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(near(left[31],((.2f*2.f+.1f)*3.f+.1f*.5f*2.f)*center)); + assert(GainFx::living==livingAtBypass && legacyFallbackCalls==0); + assert(acceptedBank->setInsertBypass(epoch,2,ch11,0,ch11Id,false)); + for(int i=0;i<16;++i) + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(near(left[31],((.2f*2.f+.1f*4.f)*3.f+ + (.1f*4.f)*.5f*2.f)*center)); + assert(GainFx::living==livingAtBypass && legacyFallbackCalls==0); + // M5.3 physical SOURCE hot switch reuses the exact live JUCE VST + // instances; no catalog lookup, plugin restart, heap or extra renderer. + const auto heapAtSource=heapCalls.load(std::memory_order_relaxed); + const auto liveAtSource=GainFx::living; + assert(native.setPhysicalSource(epoch,2,ch11,0,-1,false)); + assert(!native.setPhysicalSource(epoch,2,ch11,2,-1,false)); + assert(!native.setPhysicalSource(epoch-1,2,ch11,0,-1,false)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==heapAtSource); + assert(GainFx::living==liveAtSource&&legacyFallbackCalls==0); + assert(near(left[31],((.2f*2.f+.2f*4.f)*3.f+ + (.2f*4.f)*.5f*2.f)*center)); + assert(native.setPhysicalSource(epoch,2,ch11,1,-1,false)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==heapAtSource); + assert(GainFx::living==liveAtSource&&legacyFallbackCalls==0); + assert(near(left[31],((.2f*2.f+.1f*4.f)*3.f+ + (.1f*4.f)*.5f*2.f)*center)); + // Real hosted JUCE VST instances remain leased exactly once while + // a muted GROUP silences serial dry PCM, not the parallel FX Return. + const auto livingBeforeMute=GainFx::living; + const auto heapBeforeMute=heapCalls.load(std::memory_order_relaxed); + assert(native.setChannelMuteSolo(epoch,2,bus,true,false)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==heapBeforeMute); + assert(GainFx::living==livingBeforeMute && legacyFallbackCalls==0); + assert(near(left[31],(.1f*4.f)*.5f*2.f*center)); + assert(native.setChannelMuteSolo(epoch,2,bus,false,false)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==heapBeforeMute); + assert(GainFx::living==livingBeforeMute && legacyFallbackCalls==0); + assert(near(left[31],((.2f*2.f+.1f*4.f)*3.f+ + (.1f*4.f)*.5f*2.f)*center)); + // M-U2: the canonical ChannelId fader is smoothed over 64 SAMPLES, + // not 64 frames-per-callback. A 32-frame backend callback must reach + // only the halfway coefficient; the next 32 reaches the exact goal. + // Neither render may allocate, reinstantiate or call the old M4 FX. + assert(native.setChannelMix(epoch,2,bus,.5f,0.f)); + const auto beforeHalfHeap=heapCalls.load(std::memory_order_relaxed); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeHalfHeap); + assert(legacyFallbackCalls==0); + assert(near(left[31],((.2f*2.f+.1f*4.f)*3.f*.75f+ + (.1f*4.f)*.5f*2.f)*center)); + const auto half=left[31]; + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeHalfHeap); + assert(legacyFallbackCalls==0); + assert(left[0](std::move(refreshed)); + auto refreshedPlan=ownerPlan; + refreshedPlan.owner=std::static_pointer_cast(refreshedOwner); + refreshedPlan.context=refreshedOwner.get(); + refreshedPlan.graphRevision=3; + const auto originalProcessors=GainFx::living; + assert(native.commit(roster,req,2,epoch,epoch,true,refreshedPlan).ok()); + assert(GainFx::living==originalProcessors); // reuse, never rebuild VST + assert(native.acceptedRevision()==3); + const auto heapBeforeReload=heapCalls.load(std::memory_order_relaxed); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==heapBeforeReload); + assert(near(left[31],((.2f*2.f+.1f*4.f)*3.f*.5f+ + (.1f*4.f)*.5f*2.f)*center)); + assert(legacyFallbackCalls==0); + assert(!native.render(epoch+1,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(left[31]==0.f&&right[31]==0.f); +} + +// M-U1 full-fidelity preparation: 10 CH + 4 AUX + M4 VST owners, +// sparse verified input ports, independent physical MAIN and MONITOR, +// PRE/POST and native Show/epoch rejection. Compare actual old M4 processor +// output with the same owners in ONE new atomic ChannelId publication. +static void verifyMU1LegacyM4FxFullMigrationAndMonitorPcm() { + constexpr std::array ports{3,0,4,7}; + ChannelRoutingConfig channels; + channels.stripsAndMaster.strips[0]={ + SourceMode::mono,3,-1,.5f,-.3f,false,false}; + channels.stripsAndMaster.strips[1]={ + SourceMode::stereo,4,7,.75f,.2f,false,false}; + channels.formats[2]=ChannelFormat::stereo; + channels.stripsAndMaster.master={1.1f,.1f,false,true}; + SendRequest sends; + sends.toMaster[0]=false;sends.count=1; + sends.sends[0]={0,2,SendTap::postFader,.3f,-.3f,true}; + AuxBusRequest aux; + aux.buses[0]={true,true,false,.8f}; + aux.count=1; + aux.sends[0]={1,0,SendTap::postFader,.25f,.1f,true}; + std::array monitorGains{}; + monitorGains[0]=.25f;monitorGains[stripCount]=.3f; + PreparedRenderGraph legacyGraph; + RenderError legacyError; + assert(PreparedRenderGraph::compile(channels,ports,sends, + legacyGraph,legacyError,aux)); + auto legacy=std::make_unique(legacyGraph,32,32); + assert(legacy->setMonitorOutputBus(2,3,4,monitorGains)); + auto ch1=std::make_unique(1.2f); + auto returnFx=std::make_unique(.9f); + ch1->prepareToPlay(48000,32); + returnFx->prepareToPlay(48000,32); + assert(legacy->install(0,std::move(ch1),"CH1 VST3","m4-ch1")); + assert(legacy->install(stripCount,std::move(returnFx),"AUX VST3","m4-aux")); + const auto oldCh1=legacy->insertInstanceId(0,0); + const auto oldAux=legacy->insertInstanceId(stripCount,0); + std::array mono{},unrelated{},stL{},stR{}; + for(int i=0;i<32;++i){ + mono[i]=.2f+.001f*i;unrelated[i]=.8f; + stL[i]=.15f+.002f*i;stR[i]=.35f-.001f*i; + } + const float* physical[]{mono.data(),unrelated.data(),stL.data(),stR.data()}; + std::array legacyL{},legacyR{},legacyML{},legacyMR{}; + assert(legacy->process(physical,4,legacyL.data(),legacyR.data(),32, + nullptr,nullptr,nullptr,legacyML.data(),legacyMR.data())); + DynamicNativeSessionPublisher publisher; + UnifiedLegacyAccepted accepted; + constexpr std::uint64_t epoch=565; + VerifiedNativeOutputs outputs{4,0,1,2,3,true}; + const auto good=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitorGains,*legacy,false,outputs, + 32,2u*1024u*1024u,0,epoch,epoch,true,publisher,accepted); + assert(good.ok()); + assert(publisher.acceptedRevision()==1); + assert(accepted.deviceEpoch==epoch&&accepted.pcmRevision==1); + assert(accepted.graph.roster.size()==stripCount+auxBusCount+2); + assert(accepted.graph.request.sources.size()==2); + assert(accepted.fxOwners->insertCount(accepted.graph.ids.inputs[0])==1); + assert(accepted.fxOwners->insertCount(accepted.graph.ids.aux[0])==1); + assert((*accepted.fxOwners->ownerForControl( + accepted.graph.ids.inputs[0],0))->instanceId==oldCh1); + assert((*accepted.fxOwners->ownerForControl( + accepted.graph.ids.aux[0],0))->instanceId==oldAux); + // Actual FX ownership survives the old M4 graph retirement. + legacy.reset(); + std::array dynamicL{},dynamicR{},dynamicML{},dynamicMR{}; + const auto mustNeverCall=[&](ChannelId,float*,float*,int) noexcept { + assert(false && "M4 processor may not render twice"); + }; + const auto before=heapCalls.load(std::memory_order_relaxed); + assert(publisher.render(epoch,physical,4,dynamicL.data(),dynamicR.data(), + 32,false,mustNeverCall, + dynamicML.data(),dynamicMR.data())); + assert(heapCalls.load(std::memory_order_relaxed)==before); + // E2 native physical path reads true per-ChannelId POST-fader left + // and right peaks from the SAME render (no stale M4 GUI meter). + std::array nativeMeterL{},nativeMeterR{}; + assert(publisher.render(epoch,physical,4,dynamicL.data(),dynamicR.data(), + 32,false,mustNeverCall, + dynamicML.data(),dynamicMR.data(), + nativeMeterL,nativeMeterR)); + assert(heapCalls.load(std::memory_order_relaxed)==before); + assert(nativeMeterL[0]>0.f&&nativeMeterR[0]>0.f); + assert(!near(nativeMeterL[0],nativeMeterR[0])); + assert(nativeMeterL[stripCount]>0.f&&nativeMeterR[stripCount]>0.f); + assert(nativeMeterL[stripCount+auxBusCount]>0.f); + assert(nativeMeterL[stripCount+auxBusCount+1]>0.f); + + for(int i=0;i<32;++i) { + assert(near(legacyL[i],dynamicL[i])); + assert(near(legacyR[i],dynamicR[i])); + assert(near(legacyML[i],dynamicML[i])); + assert(near(legacyMR[i],dynamicMR[i])); + } + // E2 native accepted-state FX seam: stale epoch/revision/token is + // rejected; a genuine VST bypass changes PCM through the SAME accepted + // ChannelId processor lease, not through old M4 or a mock plug-in. + const auto ch1Id=accepted.graph.ids.inputs[0]; + assert(!accepted.setFxBypass(publisher,epoch-1,1,ch1Id,0,oldCh1,true)); + assert(!accepted.setFxBypass(publisher,epoch,0,ch1Id,0,oldCh1,true)); + assert(!accepted.setFxBypass(publisher,epoch,1,ch1Id,0,"unowned",true)); + { + auto editor=accepted.leaseFxEditor(publisher,epoch,1,ch1Id,0,oldCh1); + assert(editor && editor->instanceId==oldCh1); + assert(!accepted.leaseFxEditor(publisher,epoch,1,ch1Id,0,"unowned")); + } + assert(accepted.setFxBypass(publisher,epoch,1,ch1Id,0,oldCh1,true)); + const auto heapAtFxControl=heapCalls.load(std::memory_order_relaxed); + for(int i=0;i<16;++i) + assert(publisher.render(epoch,physical,4,dynamicL.data(),dynamicR.data(), + 32,false,mustNeverCall, + dynamicML.data(),dynamicMR.data())); + assert(heapCalls.load(std::memory_order_relaxed)==heapAtFxControl); + assert(!near(legacyL[31],dynamicL[31])); + assert(accepted.setFxBypass(publisher,epoch,1,ch1Id,0,oldCh1,false)); + for(int i=0;i<16;++i) + assert(publisher.render(epoch,physical,4,dynamicL.data(),dynamicR.data(), + 32,false,mustNeverCall, + dynamicML.data(),dynamicMR.data())); + assert(near(legacyL[31],dynamicL[31])); + // Faults are non-destructive: no external CH1 Orbit state dropped, no + // wrong-speaker output, no stale hardware, no armed graph recreation. + LiveChannelFxGraph blockedLegacy(legacyGraph,32,32); + assert(blockedLegacy.setMonitorOutputBus(2,3,4,monitorGains)); + auto bad=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitorGains,blockedLegacy, + true,outputs,32,2u*1024u*1024u,1,epoch,epoch,true, + publisher,accepted); + assert(bad.fault==UnifiedLegacyProductionAdmission::Fault::legacyCh1ExternalFx); + auto wrongPins=outputs; + wrongPins.monitorR=0; // same physical output as MAIN + bad=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitorGains,blockedLegacy, + false,wrongPins,32,2u*1024u*1024u,1,epoch,epoch,true, + publisher,accepted); + assert(bad.fault==UnifiedLegacyProductionAdmission::Fault::invalidOutputPins); + bad=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitorGains,blockedLegacy, + false,outputs,32,2u*1024u*1024u,1,epoch,epoch+1,true, + publisher,accepted); + assert(bad.fault==UnifiedLegacyProductionAdmission::Fault::staleHardware); + bad=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitorGains,blockedLegacy, + false,outputs,32,2u*1024u*1024u,1,epoch,epoch,false, + publisher,accepted); + assert(bad.fault==UnifiedLegacyProductionAdmission::Fault::outputArmed); + assert(publisher.acceptedRevision()==1); + assert(accepted.fxOwners->insertCount(accepted.graph.ids.inputs[0])==1); + assert(publisher.render(epoch,physical,4,dynamicL.data(),dynamicR.data(), + 32,false,mustNeverCall, + dynamicML.data(),dynamicMR.data())); + for(int i=0;i<32;++i){ + assert(near(legacyL[i],dynamicL[i])); + assert(near(legacyMR[i],dynamicMR[i])); + } + assert(!publisher.render(epoch+1,physical,4,dynamicL.data(), + dynamicR.data(),32,false,mustNeverCall, + dynamicML.data(),dynamicMR.data())); + assert(dynamicL[31]==0.f&&dynamicR[31]==0.f); +} + +// M-U1: occupied legacy CH1 with original JUCE FX owner; PCM and fail-closed. +static void verifyOccupiedExternalCh1Owner() { + struct Owner { + GainFx fx{1.7f}; int calls=0; + Owner(){fx.prepareToPlay(48000,32);} + void process(float* l,float* r,int n) noexcept { + float* ptrs[]{l,r};juce::AudioBuffer block(ptrs,2,n); + juce::MidiBuffer midi;fx.processBlock(block,midi);++calls; + } + }; + ChannelRoutingConfig channels; + channels.stripsAndMaster.strips[0]={ + SourceMode::mono,3,-1,.8f,-.2f,false,false}; + SendRequest sends;AuxBusRequest aux; + constexpr std::array ports{3,0}; + PreparedRenderGraph route;RenderError err; + assert(PreparedRenderGraph::compile(channels,ports,sends,route,err,aux)); + auto old=std::make_unique(route,32,32); + auto vendor=std::make_shared();auto* raw=vendor.get(); + std::weak_ptr retiringOwner=vendor; + std::array src{},silent{},oldL{},oldR{},newL{},newR{}; + src.fill(.25f); + const float* pins[]{src.data(),silent.data()}; + const auto legacyFx=+[](void* c,int strip,float* l,float* r,int n) noexcept { + assert(strip==0);static_cast(c)->process(l,r,n); + }; + assert(old->process(pins,2,oldL.data(),oldR.data(),32, + nullptr,raw,legacyFx)); + DynamicNativeSessionPublisher publisher;UnifiedLegacyAccepted accepted; + std::array monitor{}; + VerifiedNativeOutputs outputs{2,0,1,-1,-1,false}; + constexpr std::uint64_t epoch=701; + auto status=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitor,*old,true,outputs, + 32,2u*1024u*1024u,0,epoch,epoch,true,publisher,accepted); + assert(status.fault==UnifiedLegacyProductionAdmission::Fault::legacyCh1ExternalFx); + assert(publisher.acceptedRevision()==0); + LegacyMigratedGraph migrated;LegacyMigrationError migrationError; + assert(LegacyGraphMigration::compile(channels,ports,sends,aux,false, + monitor,32,2u*1024u*1024u,migrated,migrationError)); + DynamicChannelFxLeaseBank::ExternalLease lease; + // The original JUCE Graph has no ChannelId. The native ADMISSION, + // not GUI strip ordinals, must bind the verified imported CH1 identity. + lease.id=ChannelId{}; + lease.owner=std::static_pointer_cast(vendor); + lease.context=raw; + lease.render=+[](void* c,float* l,float* r,int n) noexcept { + static_cast(c)->process(l,r,n); + }; + auto invalid=lease;invalid.context=nullptr; + status=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitor,*old,true,outputs, + 32,2u*1024u*1024u,0,epoch,epoch,true,publisher,accepted,invalid); + assert(status.fault==UnifiedLegacyProductionAdmission::Fault::legacyCh1ExternalFx); + // A supplied but WRONG nonzero ChannelId cannot hijack another lane. + invalid=lease;invalid.id=ChannelId{987654}; + status=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitor,*old,true,outputs, + 32,2u*1024u*1024u,0,epoch,epoch,true,publisher,accepted,invalid); + assert(status.fault==UnifiedLegacyProductionAdmission::Fault::legacyCh1ExternalFx); + assert(publisher.acceptedRevision()==0); + status=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitor,*old,true,outputs, + 32,2u*1024u*1024u,0,epoch,epoch,true,publisher,accepted,lease); + assert(status.ok()&&publisher.acceptedRevision()==1); + assert(accepted.fxOwners->externalChannel()==migrated.ids.inputs[0]); + // The publisher owns the exact vendor processBlock and GUI state, + // regardless of the former M4 route/control owner's retirement. + old.reset();vendor.reset(); + lease={};invalid={}; + assert(!retiringOwner.expired()); + const auto fallback=+[](ChannelId,float*,float*,int) noexcept { + assert(false && "occupied vendor FX must never disappear"); + }; + const auto before=heapCalls.load(std::memory_order_relaxed); + assert(publisher.render(epoch,pins,2,newL.data(),newR.data(), + 32,false,fallback)); + assert(heapCalls.load(std::memory_order_relaxed)==before); + assert(raw->calls==2); + for(int n=0;n<32;++n){ + assert(near(newL[n],oldL[n]));assert(near(newR[n],oldR[n])); + } + assert(!publisher.render(epoch+1,pins,2,newL.data(),newR.data(), + 32,false,fallback)); + assert(newL[31]==0.f&&newR[31]==0.f); + assert(publisher.acceptedRevision()==1); + + // E3: the same physical publisher and original external VST owner + // survive a true serial GROUP then a parallel wet FX_RETURN. There is + // NO additional JUCE callback, source alias or vendor re-instantiation. + // A bounded prefix meter must not reject a graph > fixed 10CH+4AUX. + const auto publishBus=[&](ChannelRole role,const char* name, + float gain) { + auto candidate=accepted.graph.roster; + const ChannelId selected[]{accepted.graph.ids.inputs[0]}; + auto edit=candidate.createBusForSelected( + candidate.revision(),selected,name,role,gain); + assert(edit.ok()&&edit.createdIds.size()==1); + DynamicChannelFxLeaseBank nextBank; + const auto nextRevision=accepted.pcmRevision+1; + assert(DynamicChannelFxLeaseBank::reuseRevision( + epoch,nextRevision,*accepted.fxOwners,nextBank)== + DynamicChannelFxLeaseBank::Fault::none); + auto owner=std::make_shared( + std::move(nextBank)); + DynamicNativeSessionPublisher::FxPlan plan; + plan.owner=std::static_pointer_cast(owner); + plan.context=owner.get(); + plan.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(ctx))(id,l,r,n); + }; + plan.deviceEpoch=epoch;plan.graphRevision=nextRevision; + auto committed=publisher.commit( + candidate,accepted.graph.request,accepted.pcmRevision, + epoch,epoch,true,std::move(plan)); + assert(committed.ok()); + accepted.graph.roster=std::move(candidate); + accepted.fxOwners=std::move(owner); + accepted.pcmRevision=committed.revision; + publisher.pollRetirement(); // old VST Graph reclaimed on CONTROL + return edit.createdIds[0]; + }; + const auto group=publishBus(ChannelRole::group,"SERIAL GROUP",1.f); + const auto* groupView=publisher.acceptedRouting(epoch,2); + assert(groupView&&groupView->find(accepted.graph.ids.inputs[0]) + ->primaryOutput==group); + assert(groupView->find(group)->primaryOutput==accepted.graph.ids.main); + std::array meterL{},meterR{}; // fewer than total PCM lanes + const auto beforeGroup=heapCalls.load(std::memory_order_relaxed); + assert(publisher.render(epoch,pins,2,newL.data(),newR.data(),32, + false,fallback,nullptr,nullptr,meterL,meterR)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeGroup); + assert(raw->calls==3); + for(int i=0;i<32;++i){ + assert(near(newL[i],oldL[i]));assert(near(newR[i],oldR[i])); + } + // Operator GROUP fader changes the LIVE ChannelId bus. Preserve its + // accepted target before the next graph publication (FX Return). + assert(publisher.setChannelMix(epoch,2,group,2.f,0.f)); + assert(accepted.graph.roster.rememberLiveMix(group,2.f,0.f)); + assert(!publisher.setChannelMix(epoch,1,group,.5f,0.f)); + const auto wet=publishBus(ChannelRole::fxReturn,"PARALLEL WET",.25f); + const auto* wetView=publisher.acceptedRouting(epoch,3); + assert(wetView&&wetView->find(wet)); + assert(wetView->find(accepted.graph.ids.inputs[0])->primaryOutput==group); + assert(wetView->find(accepted.graph.ids.inputs[0])->parallelSends.size()==1); + assert(wetView->find(accepted.graph.ids.inputs[0]) + ->parallelSends[0].destination==wet); + const auto beforeWet=heapCalls.load(std::memory_order_relaxed); + assert(publisher.render(epoch,pins,2,newL.data(),newR.data(),32, + false,fallback,nullptr,nullptr,meterL,meterR)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeWet); + assert(raw->calls==4); // ONE original vendor process per graph pass + assert(std::abs(newL[31])>std::abs(oldL[31])); + assert(std::abs(newR[31])>std::abs(oldR[31])); + assert(publisher.acceptedRevision()==3); + // Stale or incompatible native topology must not advance the accepted + // graph; the existing audible GROUP + FX return remains intact. + const auto stale=publisher.commit(accepted.graph.roster, + accepted.graph.request,1,epoch,epoch,true); + assert(!stale.ok()&&publisher.acceptedRevision()==3); + // Once no callback may hold the accepted PCM snapshot, there is no + // hidden second FX owner. All vendor/plugin cleanup is off realtime. + publisher.unpublish(); + accepted=UnifiedLegacyAccepted{}; + publisher.pollRetirement(); + assert(retiringOwner.expired()); +} + +// M-U1 source/processing format independence: a mono microphone through a +// stereo native rack must retain the same equal-power PAN as M4. Conversely +// physical stereo folded to mono processing must not become stereo-balance. +// Compare exact physical L/R PCM for all four source/format combinations. +static void verifySourceFormatIndependentPanPcmParity() { + struct Case {bool sourceStereo,processStereo;float pan;}; + constexpr std::array cases{{ + {false,false,-.6f},{false,true,-.6f}, + {false,true,.6f},{true,false,.6f}, + {true,false,-.6f},{true,true,.6f} + }}; + constexpr std::array ports{3,7}; + std::array mic{},micR{}; + for(int i=0;i<32;++i){ + mic[i]=.15f+.001f*i; + micR[i]=.35f-.002f*i; + } + const float* physical[]{mic.data(),micR.data()}; + constexpr std::uint64_t epoch=800; + const auto noFx=+[](ChannelId,float*,float*,int) noexcept {}; + for(const auto& choice:cases) { + ChannelRoutingConfig cfg; + cfg.stripsAndMaster.strips[0]={ + choice.sourceStereo?SourceMode::stereo:SourceMode::mono, + 3,choice.sourceStereo?7:-1,.7f,choice.pan,false,false + }; + cfg.formats[0]=choice.processStereo? + ChannelFormat::stereo:ChannelFormat::mono; + SendRequest sends;AuxBusRequest aux; + PreparedRenderGraph oldRoute;RenderError legacyError; + assert(PreparedRenderGraph::compile( + cfg,ports,sends,oldRoute,legacyError,aux)); + auto old=std::make_unique(oldRoute,32,32); + assert(old->setStripControl(0,.7f,choice.pan, + !choice.sourceStereo||!choice.processStereo, + false,false)); + std::array oldL{},oldR{},nativeL{},nativeR{}; + assert(old->process(physical,2,oldL.data(),oldR.data(),32)); + DynamicNativeSessionPublisher native; + UnifiedLegacyAccepted accepted; + std::array monitor{}; + VerifiedNativeOutputs outs{2,0,1,-1,-1,false}; + auto admission=UnifiedLegacyProductionAdmission::compileAndCommit( + cfg,ports,sends,aux,monitor,*old,false,outs, + 32,2u*1024u*1024u,0,epoch,epoch,true,native,accepted); + assert(admission.ok()); + const auto before=heapCalls.load(std::memory_order_relaxed); + assert(native.render(epoch,physical,2,nativeL.data(), + nativeR.data(),32,false,noFx)); + assert(heapCalls.load(std::memory_order_relaxed)==before); + for(int i=0;i<32;++i){ + assert(near(nativeL[i],oldL[i])); + assert(near(nativeR[i],oldR[i])); + } + // A stale physical endpoint must fail silent and not change ACK. + assert(!native.render(epoch+1,physical,2,nativeL.data(), + nativeR.data(),32,false,noFx)); + assert(nativeL[31]==0.f&&nativeR[31]==0.f); + assert(native.acceptedRevision()==1); + } +} + +// G0: This is the real JUCE device/callback STATUS -> v6 Console wire, +// not a dry ChannelId graph or simulated universal engine. It must report +// measured M4 PCM while all unsupported ChannelId operations stay CLOSED. +static void verifyNativeConsoleWireRejectsUnsupportedM4AndPreservesEpoch() { + using Bridge=armix::console::LiveConsoleBridgeV6; + auto route=std::make_unique(); + constexpr juce::int64 epoch=9007199254740993LL; // beyond JS Number safety + route->setProperty("epoch",epoch); + route->setProperty("revision",juce::int64(77)); + route->setProperty("active",true); + route->setProperty("ready",true); + route->setProperty("hasAcceptedRoute",true); + // Exact native accepted publisher data, not an imagined v8 graph. + auto nativeBus=std::make_unique(); + nativeBus->setProperty("graphRevision","3"); + nativeBus->setProperty("rosterRevision","4"); + nativeBus->setProperty("structural",true); + juce::Array realBuses; + auto groupRow=std::make_unique(); + groupRow->setProperty("id","18"); + groupRow->setProperty("role","GROUP"); + groupRow->setProperty("primaryOutput","15"); + realBuses.add(juce::var(groupRow.release())); + nativeBus->setProperty("channels",juce::var(realBuses)); + route->setProperty("nativeBus",juce::var(nativeBus.release())); + // These booleans are device-loop truth, NOT permission to promote + // universal CH11, GROUP or WIRE operations in the GUI. + route->setProperty("nativeChannelIdPcmActive",true); + route->setProperty("originalCh1GraphLeased",true); + // Genuine admitted M4 rows, not fabricated universal ChannelIds. + juce::Array admittedRows; + for(int i=0;i(); + row->setProperty("mode",i==0?"MONO":"NONE"); + row->setProperty("left",i==0?2:-1); + row->setProperty("right",-1); + admittedRows.add(juce::var(row.release())); + } + auto admittedRoute=std::make_unique(); + admittedRoute->setProperty("channels",juce::var(admittedRows)); + route->setProperty("acceptedRoute",juce::var(admittedRoute.release())); + juce::Array ports; + auto port=std::make_unique(); + port->setProperty("port",2);port->setProperty("callback",0); + port->setProperty("label","ASIO Input 3"); + ports.add(juce::var(port.release())); + route->setProperty("ports",juce::var(ports)); + juce::Array outputs; + outputs.add(1);outputs.add(4); + route->setProperty("outputPorts",juce::var(outputs)); + juce::Array levels; + levels.add(.125);levels.add(0.0); + route->setProperty("channelPeaks",juce::var(levels)); + auto status=std::make_unique(); + status->setProperty("dryRoutingLab",juce::var(route.release())); + status->setProperty("driver","ASIO TEST"); + status->setProperty("inputDevice","TEST CAPTURE"); + status->setProperty("outputDevice","TEST RENDER"); + status->setProperty("connected",true); + status->setProperty("directRouteAuthorized",true); + status->setProperty("monitor",true); + status->setProperty("callbackCount",juce::int64(12)); + status->setProperty("callbackInputChannels",1); + status->setProperty("inputPeak",.25); + juce::Array perPort; + perPort.add(.25); + status->setProperty("captureCallbackPeaks",juce::var(perPort)); + status->setProperty("peak",.125); + status->setProperty("rate",48000); + status->setProperty("buffer",128); + const auto live=juce::var(status.release()); + auto snap=Bridge::snapshot(live); + auto device=snap.getProperty("device",{}); + auto graph=snap.getProperty("graph",{}); + auto measured=snap.getProperty("telemetry",{}); + assert(static_cast(snap.getProperty("schemaVersion",0))==6); + assert(!static_cast(snap.getProperty("productionCallbackLive",true))); + assert(device.getProperty("epoch","").toString()=="9007199254740993"); + assert(static_cast(device.getProperty("outputArmed",false))); + assert(static_cast(measured.getProperty("rawCapturePresent",false))); + assert(static_cast(measured.getProperty("mainPcmPresent",false))); + assert(graph.getProperty("revision","").toString()=="0"); + assert(graph.getProperty("rosterRevision","").toString()=="0"); + assert(graph.getProperty("channels",{}).getArray()->isEmpty()); + const auto caps=graph.getProperty("capabilities",{}); + assert(!static_cast(caps.getProperty("callbackOwnsChannelIds",true))); + assert(caps.getProperty("supportedOps",{}).getArray()->isEmpty()); + auto ins=device.getProperty("inputEndpoints",{}); + auto outs=device.getProperty("outputEndpoints",{}); + assert(ins.getArray()->size()==1 && outs.getArray()->size()==2); + const auto acceptedInputs=device.getProperty("enabledInputs",{}); + const auto acceptedOutputs=device.getProperty("enabledOutputs",{}); + assert(acceptedInputs.getArray() && acceptedInputs.getArray()->size()==1); + assert(acceptedOutputs.getArray() && acceptedOutputs.getArray()->size()==2); + assert(static_cast(acceptedInputs.getArray()->getReference(0))==2); + assert(static_cast(acceptedOutputs.getArray()->getReference(0))==1); + assert(static_cast(acceptedOutputs.getArray()->getReference(1))==4); + assert(static_cast(ins.getArray()->getReference(0).getProperty("port",0))==2); + assert(static_cast(ins.getArray()->getReference(0) + .getProperty("rawPeak",0.0))==.25); + assert(static_cast(ins.getArray()->getReference(0) + .getProperty("rawPresent",false))); + assert(static_cast(outs.getArray()->getReference(0).getProperty("port",0))==1); + assert(static_cast(outs.getArray()->getReference(1).getProperty("port",0))==4); + const auto diagnostic=snap.getProperty("legacyM4",{}); + assert(diagnostic.getProperty("routingRevision","").toString()=="77"); + assert(diagnostic.getProperty("controlPlane","").toString()=="LEGACY_M4_ORDINAL"); + assert(diagnostic.getProperty("pcmRenderer","").toString()=="CHANNEL_ID_10CH4AUX"); + assert(static_cast(diagnostic.getProperty("originalCh1GraphLeased",false))); + const auto deliveredBus=diagnostic.getProperty("nativeBus",{}); + assert(deliveredBus.isObject()); + assert(deliveredBus.getProperty("graphRevision","").toString()=="3"); + assert(deliveredBus.getProperty("rosterRevision","").toString()=="4"); + const auto* deliveredChannels=deliveredBus.getProperty("channels",{}).getArray(); + assert(deliveredChannels&&deliveredChannels->size()==1); + assert(deliveredChannels->getReference(0).getProperty("id","").toString()=="18"); + // A revoked native PCM mode must immediately report M4 fallback without + // inventing any universal ChannelId capabilities or stale FX identity. + auto pcmRouteReadback=live.getProperty("dryRoutingLab",{}); + pcmRouteReadback.getDynamicObject()->setProperty("nativeChannelIdPcmActive",false); + auto fallbackSnap=Bridge::snapshot(live); + const auto fallbackM4=fallbackSnap.getProperty("legacyM4",{}); + assert(fallbackM4.getProperty("pcmRenderer","").toString()=="M4_COMPAT"); + assert(!static_cast(fallbackM4.getProperty("originalCh1GraphLeased",true))); + assert(!static_cast(fallbackSnap.getProperty("productionCallbackLive",true))); + assert(fallbackM4.getProperty("nativeBus",{}).isVoid()); + pcmRouteReadback.getDynamicObject()->setProperty("nativeChannelIdPcmActive",true); + const auto legacyRows=diagnostic.getProperty("acceptedChannels",{}); + assert(legacyRows.getArray()&& + legacyRows.getArray()->size()==armix::mixer::stripCount); + assert(legacyRows.getArray()->getReference(0).getProperty("mode","").toString()=="MONO"); + const auto nativeM4Ops=diagnostic.getProperty("supportedOps",{}); + assert(nativeM4Ops.getArray() && + nativeM4Ops.getArray()->contains(juce::var(juce::String("SET_FADER"))) && + nativeM4Ops.getArray()->contains(juce::var(juce::String("SET_MUTE"))) && + !nativeM4Ops.getArray()->contains(juce::var(juce::String("CREATE_CHANNEL")))); + // No false universal promotion even when the installed M4 branch can + // really mutate physical PCM through its own separately fenced transport. + assert(!static_cast(snap.getProperty("productionCallbackLive",true))); + assert(caps.getProperty("supportedOps",{}).getArray()->isEmpty()); + // Universal revisions cannot be borrowed from M4; this unready source + // must not permit GUI ChannelId operations even while M4 PCM is active. + assert(graph.getProperty("revision","").toString()=="0"); + Bridge bridge; + const auto intent=[&](const juce::String& req,const juce::String& ep, + const juce::String& rev="0") { + auto o=std::make_unique(); + o->setProperty("requestId",req); + o->setProperty("deviceEpoch",ep); + o->setProperty("baseGraphRevision",rev); + o->setProperty("baseRosterRevision","0"); + o->setProperty("operation","SET_SOURCE"); + o->setProperty("targetChannelId","18446744073709551615"); + return juce::var(o.release()); + }; + const auto pending=intent("editor:nonce:1","9007199254740993"); + auto ack=bridge.rejectUnsupportedIntent(pending,snap); + assert(ack.getProperty("requestId","").toString()=="editor:nonce:1"); + assert(ack.getProperty("status","").toString()=="REJECTED"); + assert(ack.getProperty("errorCode","").toString()=="UNIVERSAL_CALLBACK_NOT_READY"); + assert(ack.getProperty("graphRevision","").toString()=="0"); + assert(bridge.rejectUnsupportedIntent(pending,snap) + .getProperty("errorCode","").toString()=="DUPLICATE_REQUEST_ID"); + assert(bridge.rejectUnsupportedIntent(intent("editor:nonce:2","9007199254740992"),snap) + .getProperty("errorCode","").toString()=="STALE_DEVICE_EPOCH"); + assert(bridge.rejectUnsupportedIntent(intent("editor:nonce:3","9007199254740993","9"),snap) + .getProperty("errorCode","").toString()=="STALE_GRAPH_REVISION"); + std::uint64_t decoded=0; + assert(Bridge::decodeDecimal(juce::var("18446744073709551615"),decoded)); + assert(decoded==std::numeric_limits::max()); + assert(!Bridge::decodeDecimal(juce::var("18446744073709551616"),decoded)); + assert(!Bridge::decodeDecimal(juce::var("01"),decoded)); + assert(!Bridge::decodeDecimal(juce::var(9007199254740993.0),decoded)); + // This adapter receives an actual operator WebView intent and returns + // a post-publication stable ChannelId+revisions, never graph revision 0 + // masquerading as the native PCM version. No device is required here: + // the transport test uses an injected native CONTROL writer; golden + // vendor PCM and lifetime were verified separately above. + struct BusControl { + struct Report { + bool accepted=false; + ChannelId created{}; + std::uint64_t pcmRevision=0,rosterRevision=0; + const char* error="NOT_ADMITTED"; + }; + int commits=0; + int liveMixes=0; + int nativeInputCreates=0,nativeInputPatches=0; + int nativeInputMixes=0,nativeInputToggles=0; + int nativeWireRoutes=0,nativeWireBatches=0; + Report createNativeInputChannel(std::uint64_t ep,std::uint64_t pcm, + std::uint64_t roster,const std::string& name, + ProcessingFormat format){ + assert(ep==9007199254740993ULL&&pcm==3&&roster==4); + assert(name=="CH11"&&format==ProcessingFormat::mono); + ++nativeInputCreates; + return {true,{20},4,6,""}; + } + Report patchNativeInputSource(std::uint64_t ep,std::uint64_t pcm, + std::uint64_t roster,ChannelId id,int left,int right,bool stereo){ + assert(ep==9007199254740993ULL&&pcm==3&&roster==4); + assert(id.value==20&&left==2&&right==-1&&!stereo); + ++nativeInputPatches; + return {true,{},4,4,""}; + } + bool setNativeInputMix(std::uint64_t ep,std::uint64_t rev, + ChannelId id,float gain,float pan){ + assert(ep==9007199254740993ULL&&rev==3); + assert(id.value==20&&near(gain,.5f)&&near(pan,0.f)); + ++nativeInputMixes;return true; + } + bool setNativeInputMuteSolo(std::uint64_t ep,std::uint64_t rev, + ChannelId id,bool mute,bool solo){ + assert(ep==9007199254740993ULL&&rev==3); + assert(id.value==20&&mute&&!solo); + ++nativeInputToggles;return true; + } + bool setNativeBusMix(std::uint64_t ep,std::uint64_t rev, + ChannelId id,float gain,float pan) { + assert(ep==9007199254740993ULL&&rev==3); + assert(id.value==18&&near(gain,.5f)&&near(pan,0.f)); + ++liveMixes;return true; + } + Report setNativePrimaryOutput(std::uint64_t ep,std::uint64_t pcm, + std::uint64_t roster,ChannelId src,ChannelId dst) { + assert(ep==9007199254740993ULL&&pcm==3&&roster==4); + assert(src.value==20&&dst.value==18); + ++nativeWireRoutes;return {true,{},4,5,""}; + } + Report applyNativeWireTransaction(std::uint64_t ep, + std::uint64_t pcm,std::uint64_t roster, + std::span changes) { + assert(ep==9007199254740993ULL&&pcm==3&&roster==4); + assert(changes.size()==2); + assert(changes[0].kind==WireChange::Kind::remove); + assert(changes[0].from.value==20&&changes[0].edgeId==77); + assert(changes[1].kind==WireChange::Kind::connect); + assert(changes[1].from.value==20&&changes[1].to.value==18); + assert(near(changes[1].gain,.5f)); + ++nativeWireBatches; + return {true,{},4,5,""}; + } + Report editNativeBus(std::uint64_t ep,std::uint64_t pcm, + std::uint64_t roster,ChannelRole role, + std::span selected, + const std::string& name,float gain,ChannelId remove) { + assert(ep==9007199254740993ULL); + assert(pcm==3 && roster==4); + assert(role==ChannelRole::group && remove.value==0); + assert(selected.size()==1 && selected[0].value==1); + assert(name=="VOCALS"&&near(gain,.25f)); + ++commits; + return {true,{19},4,5,""}; + } + } busControl; + + // Control-thread test: no vendor VST3 effect required for routing. + const auto routeBusIntent=[&](const juce::var& intent) { + return bridge.processNativeBusIntent(intent,snap,busControl,false, + [](const juce::String&,ChannelId,const juce::var&, + std::uint64_t,std::uint64_t,std::uint64_t) + ->BusControl::Report { return {}; }); + }; + const auto makeBusIntent=[&](const juce::String& req) { + auto command=std::make_unique(); + command->setProperty("requestId",req); + command->setProperty("deviceEpoch","9007199254740993"); + command->setProperty("legacyRoutingRevision","77"); + command->setProperty("nativeGraphRevision","3"); + command->setProperty("nativeRosterRevision","4"); + command->setProperty("operation","NATIVE_CREATE_GROUP_SELECTED"); + auto payload=std::make_unique(); + payload->setProperty("name","VOCALS"); + payload->setProperty("sendGain",.25); + juce::Array selection;selection.add("1"); + payload->setProperty("selectedChannelIds",juce::var(selection)); + command->setProperty("payload",juce::var(payload.release())); + return juce::var(command.release()); + }; + // Real installed bridge functions must compile against mock control writer: + // native ChannelId input creation, physical source patch and bounded + // scalar controls each preserve opaque request IDs and accepted rev. + auto create=makeBusIntent("native:ch11:1"); + create.getDynamicObject()->setProperty("operation","NATIVE_CREATE_CHANNEL"); + auto inputPayload=std::make_unique(); + inputPayload->setProperty("name","CH11"); + inputPayload->setProperty("format","MONO"); + create.getDynamicObject()->setProperty( + "payload",juce::var(inputPayload.release())); + auto inputAck=routeBusIntent(create); + assert(inputAck.getProperty("status","").toString()=="ACCEPTED"); + assert(inputAck.getProperty("createdChannelId","").toString()=="20"); + assert(busControl.nativeInputCreates==1); + auto patch=makeBusIntent("native:ch11:2"); + patch.getDynamicObject()->setProperty("operation","NATIVE_PATCH_CHANNEL"); + patch.getDynamicObject()->setProperty("targetChannelId","20"); + auto patchPayload=std::make_unique(); + patchPayload->setProperty("physicalLeft",2); + patchPayload->setProperty("physicalRight",-1); + patchPayload->setProperty("sourceFormat","MONO"); + patch.getDynamicObject()->setProperty("payload",juce::var(patchPayload.release())); + inputAck=routeBusIntent(patch); + assert(inputAck.getProperty("status","").toString()=="ACCEPTED"); + assert(busControl.nativeInputPatches==1); + auto inputMix=makeBusIntent("native:ch11:3"); + inputMix.getDynamicObject()->setProperty("operation","NATIVE_SET_CHANNEL_MIX"); + inputMix.getDynamicObject()->setProperty("targetChannelId","20"); + auto controlPayload=std::make_unique(); + controlPayload->setProperty("gain",.5); + controlPayload->setProperty("pan",0.0); + inputMix.getDynamicObject()->setProperty( + "payload",juce::var(controlPayload.release())); + inputAck=routeBusIntent(inputMix); + assert(inputAck.getProperty("status","").toString()=="ACCEPTED"); + assert(busControl.nativeInputMixes==1); + auto inputToggle=makeBusIntent("native:ch11:4"); + inputToggle.getDynamicObject()->setProperty( + "operation","NATIVE_SET_CHANNEL_MUTE_SOLO"); + inputToggle.getDynamicObject()->setProperty("targetChannelId","20"); + auto togglePayload=std::make_unique(); + togglePayload->setProperty("mute",true);togglePayload->setProperty("solo",false); + inputToggle.getDynamicObject()->setProperty( + "payload",juce::var(togglePayload.release())); + inputAck=routeBusIntent(inputToggle); + assert(inputAck.getProperty("status","").toString()=="ACCEPTED"); + assert(busControl.nativeInputToggles==1); + auto nativeAck=routeBusIntent( + makeBusIntent("native:bus:1")); + assert(nativeAck.getProperty("status","").toString()=="ACCEPTED"); + assert(nativeAck.getProperty("graphRevision","").toString()=="0"); + assert(nativeAck.getProperty("nativeGraphRevision","").toString()=="4"); + assert(nativeAck.getProperty("nativeRosterRevision","").toString()=="5"); + assert(nativeAck.getProperty("createdChannelId","").toString()=="19"); + assert(busControl.commits==1); + nativeAck=routeBusIntent( + makeBusIntent("native:bus:1")); + assert(nativeAck.getProperty("errorCode","").toString()=="DUPLICATE_REQUEST_ID"); + assert(busControl.commits==1); + auto staleBus=makeBusIntent("native:bus:2"); + staleBus.getDynamicObject()->setProperty("nativeGraphRevision","2"); + nativeAck=routeBusIntent(staleBus); + assert(nativeAck.getProperty("status","").toString()=="REJECTED"); + assert(busControl.commits==1); + + auto wireIntent=makeBusIntent("native:wire:1"); + wireIntent.getDynamicObject()->setProperty("operation","NATIVE_SET_PRIMARY_OUT"); + wireIntent.getDynamicObject()->setProperty("targetChannelId","20"); + auto wirePayload=std::make_unique(); + wirePayload->setProperty("destinationId","18"); + wireIntent.getDynamicObject()->setProperty( + "payload",juce::var(wirePayload.release())); + const auto wireAck=routeBusIntent(wireIntent); + assert(wireAck.getProperty("status","").toString()=="ACCEPTED"); + assert(busControl.nativeWireRoutes==1); + // Same existing native bridge -> exact batch -> post-publication ACK. + // Legacy M4 revision remains separate; no false universal LIVE claim. + auto batch=makeBusIntent("native:wire:batch:1"); + batch.getDynamicObject()->setProperty( + "operation","NATIVE_APPLY_WIRE_TRANSACTION"); + juce::Array changes; + auto unplug=std::make_unique(); + unplug->setProperty("op","REMOVE"); + unplug->setProperty("from","20"); + unplug->setProperty("edgeId","77"); + changes.add(juce::var(unplug.release())); + auto connect=std::make_unique(); + connect->setProperty("op","CONNECT"); + connect->setProperty("from","20"); + connect->setProperty("to","18"); + connect->setProperty("tap","POST_FADER"); + connect->setProperty("gainLinear",.5); + changes.add(juce::var(connect.release())); + auto transaction=std::make_unique(); + transaction->setProperty("changes",juce::var(changes)); + batch.getDynamicObject()->setProperty( + "payload",juce::var(transaction.release())); + auto batchAck=routeBusIntent(batch); + assert(batchAck.getProperty("status","").toString()=="ACCEPTED"); + assert(batchAck.getProperty("nativeGraphRevision","").toString()=="4"); + assert(batchAck.getProperty("nativeRosterRevision","").toString()=="5"); + assert(busControl.nativeWireBatches==1); + batchAck=routeBusIntent(batch); + assert(batchAck.getProperty("errorCode","").toString()=="DUPLICATE_REQUEST_ID"); + assert(busControl.nativeWireBatches==1); + auto invalidBatch=makeBusIntent("native:wire:bad:2"); + invalidBatch.getDynamicObject()->setProperty( + "operation","NATIVE_APPLY_WIRE_TRANSACTION"); + auto malformed=std::make_unique(); + juce::Array badChanges; + auto bad=std::make_unique(); + bad->setProperty("op","REMOVE");bad->setProperty("from","020"); + bad->setProperty("edgeId","77"); + badChanges.add(juce::var(bad.release())); + malformed->setProperty("changes",juce::var(badChanges)); + invalidBatch.getDynamicObject()->setProperty( + "payload",juce::var(malformed.release())); + batchAck=routeBusIntent(invalidBatch); + assert(batchAck.getProperty("status","").toString()=="REJECTED"); + assert(batchAck.getProperty("errorCode","").toString()=="INVALID_NATIVE_WIRE_SOURCE"); + assert(busControl.nativeWireBatches==1); + auto liveMixIntent=makeBusIntent("native:mix:1"); + liveMixIntent.getDynamicObject()->setProperty( + "operation","NATIVE_SET_BUS_MIX"); + liveMixIntent.getDynamicObject()->setProperty("targetChannelId","18"); + auto mixPayload=std::make_unique(); + mixPayload->setProperty("gain",.5); + mixPayload->setProperty("pan",0.0); + liveMixIntent.getDynamicObject()->setProperty( + "payload",juce::var(mixPayload.release())); + const auto mixAck=routeBusIntent( + liveMixIntent); + assert(mixAck.getProperty("status","").toString()=="ACCEPTED"); + assert(busControl.liveMixes==1&&busControl.commits==1); + // Canonical public v8 operation uses the SAME installed ChannelId + // publisher and ACK revisions, never a WebView/legacy owned PCM graph. + const auto v8Route=live.getProperty("dryRoutingLab",{}); + const auto v8Bus=v8Route.getProperty("nativeBus",{}); + auto* v8BusObject=v8Bus.getDynamicObject(); + assert(v8BusObject); + const auto v8Rows=v8Bus.getProperty("channels",{}); + // Make the synthetic fixture structurally complete: partial native + // rows must not advertise accepted ChannelId support. + auto makeNativeRow=[](const char* id,const char* role) { + auto view=std::make_unique(); + view->setProperty("id",id);view->setProperty("role",role); + view->setProperty("name",role);view->setProperty("format","STEREO"); + view->setProperty("primaryOutput","0"); + view->setProperty("fader",1.);view->setProperty("pan",0.); + view->setProperty("mute",false);view->setProperty("solo",false); + view->setProperty("inserts",juce::var(juce::Array{})); + view->setProperty("peakL",.25);view->setProperty("peakR",.2); + return juce::var(view.release()); + }; + v8Rows.getArray()->clear(); + auto nativeInput=makeNativeRow("20","INPUT"); + nativeInput.getDynamicObject()->setProperty("primaryOutput","18"); + v8Rows.getArray()->add(nativeInput); + v8Rows.getArray()->add(makeNativeRow("18","MAIN")); + juce::Array v8Edges; + auto v8Edge=std::make_unique(); + v8Edge->setProperty("edgeId","77"); + v8Edge->setProperty("from","20"); + v8Edge->setProperty("to","18"); + v8Edge->setProperty("tap","POST_FADER"); + v8Edge->setProperty("gainLinear",.5); + v8Edge->setProperty("primaryOutput",true); + v8Edges.add(juce::var(v8Edge.release())); + v8BusObject->setProperty("edges",juce::var(v8Edges)); + juce::Array v8InstalledOps; + v8InstalledOps.add(juce::var(juce::String("NATIVE_APPLY_WIRE_TRANSACTION"))); + v8BusObject->setProperty("supportedOps",juce::var(v8InstalledOps)); + const auto acceptedV8=Bridge::snapshot(live); + const auto acceptedV8Graph=acceptedV8.getProperty("graph",{}); + const auto acceptedV8Caps=acceptedV8Graph.getProperty("capabilities",{}); + assert(!static_cast(acceptedV8.getProperty("productionCallbackLive",true))); + assert(acceptedV8Graph.getProperty("revision","").toString()=="3"); + assert(acceptedV8Graph.getProperty("rosterRevision","").toString()=="4"); + assert(acceptedV8Graph.getProperty("channels",{}).getArray()->size()==2); + assert(acceptedV8Graph.getProperty("mainChannelId","").toString()=="18"); + const auto publicChannel=acceptedV8Graph.getProperty("channels",{}) + .getArray()->getReference(0); + assert(publicChannel.getProperty("processingFormat","").toString()=="STEREO"); + assert(publicChannel.getProperty("controls",{}).getProperty("faderDb",{}).isDouble()); + assert(acceptedV8Graph.getProperty("edges",{}).getArray()->size()==1); + assert(acceptedV8Graph.getProperty("edges",{}).getArray()->getReference(0) + .getProperty("signalKind","").toString()=="AUDIO"); + assert(acceptedV8Graph.getProperty("edges",{}).getArray()->getReference(0) + .getProperty("edgeId","").toString()=="77"); + assert(static_cast(acceptedV8Caps.getProperty("callbackOwnsChannelIds",false))); + assert(acceptedV8Caps.getProperty("supportedOps",{}).getArray()->contains( + juce::var(juce::String("APPLY_WIRE_TRANSACTION")))); + auto v8IntentObject=std::make_unique(); + v8IntentObject->setProperty("requestId","v8:wire:1"); + v8IntentObject->setProperty("deviceEpoch","9007199254740993"); + v8IntentObject->setProperty("baseGraphRevision","3"); + v8IntentObject->setProperty("baseRosterRevision","4"); + v8IntentObject->setProperty("operation","APPLY_WIRE_TRANSACTION"); + v8IntentObject->setProperty("targetChannelId","20"); + v8IntentObject->setProperty("payload",batch.getProperty("payload",{})); + const auto v8WireIntent=juce::var(v8IntentObject.release()); + const auto applyV8=[&](const juce::var& command,const juce::var& snapshot) { + return bridge.processNativeBusIntent(command,snapshot,busControl,false, + [](const juce::String&,ChannelId,const juce::var&, + std::uint64_t,std::uint64_t,std::uint64_t) + ->BusControl::Report {return {};}); + }; + auto v8Reply=applyV8(v8WireIntent,acceptedV8); + assert(v8Reply.getProperty("status","").toString()=="ACCEPTED"); + assert(v8Reply.getProperty("graphRevision","").toString()=="4"); + assert(v8Reply.getProperty("rosterRevision","").toString()=="5"); + assert(busControl.nativeWireBatches==2); + assert(applyV8(v8WireIntent,acceptedV8) + .getProperty("errorCode","").toString()=="DUPLICATE_REQUEST_ID"); + auto staleV8=juce::JSON::parse(juce::JSON::toString(v8WireIntent,false)); + staleV8.getDynamicObject()->setProperty("requestId","v8:wire:stale"); + staleV8.getDynamicObject()->setProperty("baseGraphRevision","2"); + assert(applyV8(staleV8,acceptedV8).getProperty("status","").toString()=="REJECTED"); + assert(busControl.nativeWireBatches==2); + // A focused MAIN plug cannot modify another admitted channel's wire + // even if its edge ID is otherwise syntactically valid. + auto wrongFocus=juce::JSON::parse(juce::JSON::toString(v8WireIntent,false)); + wrongFocus.getDynamicObject()->setProperty("requestId","v8:wire:wrong-focus"); + wrongFocus.getDynamicObject()->setProperty("targetChannelId","18"); + const auto rejectedFocus=applyV8(wrongFocus,acceptedV8); + assert(rejectedFocus.getProperty("status","").toString()=="REJECTED"); + assert(rejectedFocus.getProperty("errorCode","").toString()== + "UNIVERSAL_WIRE_UNFOCUSED_SOURCE"); + assert(busControl.nativeWireBatches==2); + // Subsequent native producer snapshot must match the acknowledged graph + // and roster revision before GUI may paint an accepted WIRE cable. + v8BusObject->setProperty("graphRevision","4"); + v8BusObject->setProperty("rosterRevision","5"); + const auto afterV8=Bridge::snapshot(live); + assert(afterV8.getProperty("graph",{}).getProperty("revision","") + .toString()==v8Reply.getProperty("graphRevision","").toString()); + assert(afterV8.getProperty("graph",{}).getProperty("rosterRevision","") + .toString()==v8Reply.getProperty("rosterRevision","").toString()); + // C2 native integration: public v8 ACK is exercised against the REAL + // accepted PCM graph, not the mock authorizing the bridge above. + // Direct + nested routes must change sample amplitudes on the SAME + // sample index after the focused MAIN cable is actually unplugged. + { + constexpr std::uint64_t pcmEpoch=9007199254740993ULL; + DynamicAcceptedSession pcm; + DynamicGraphRequest patch; + patch.physicalInputs=1;patch.maxFrames=64; + const auto createRow=[](std::size_t position,ChannelRole role, + const char* name,ProcessingFormat width) { + ChannelEdit e;e.kind=ChannelEdit::Kind::add; + e.position=position;e.role=role;e.text=name;e.format=width; + return e; + }; + const std::array create{ + createRow(0,ChannelRole::input,"PCM SOURCE",ProcessingFormat::mono), + createRow(1,ChannelRole::input,"PCM VIA",ProcessingFormat::stereo), + createRow(2,ChannelRole::main,"PCM MAIN",ProcessingFormat::stereo) + }; + auto admission=pcm.edit(0,0,create,patch,pcmEpoch,pcmEpoch,true); + assert(admission.ok()&&admission.edit.createdIds.size()==3); + const auto src=admission.edit.createdIds[0]; + const auto via=admission.edit.createdIds[1]; + const auto sink=admission.edit.createdIds[2]; + patch.sources={{src,0,-1,false}}; + ChannelEdit direct;direct.kind=ChannelEdit::Kind::setPrimaryOutput; + direct.id=src;direct.target=sink; + ChannelEdit viaOut=direct;viaOut.id=via; + const std::array mains{direct,viaOut}; + admission=pcm.edit(1,1,mains,patch,pcmEpoch,pcmEpoch,true); + assert(admission.ok()&&pcm.acceptedGraphRevision()==2); + WireChange intermediate;intermediate.kind=WireChange::Kind::connect; + intermediate.from=src;intermediate.to=via; + const std::array toVia{intermediate}; + const auto linked=pcm.wireTransaction( + 2,2,toVia,patch,pcmEpoch,pcmEpoch,false); + assert(linked.ok()&&pcm.acceptedGraphRevision()==3); + const auto* acceptedPcm=pcm.acceptedRouting(pcmEpoch,3); + assert(acceptedPcm&&acceptedPcm->edges.size()==3); + std::uint64_t directId=0; + for(const auto& edge:acceptedPcm->edges) + if(edge.from==src&&edge.to==sink)directId=edge.edgeId; + assert(directId!=0); + std::array impulse{},left{},right{}; + impulse[11]=.3f; + const float* capture[]{impulse.data()}; + const auto noFx=+[](ChannelId,float*,float*,int) noexcept {}; + const auto renderPcm=[&] { + return pcm.render(pcmEpoch,capture,1,left.data(),right.data(), + 64,false,noFx); + }; + assert(renderPcm()); + const float parallelValue=left[11]; + assert(parallelValue>.1f); + assert(near(left[10],0.f)&&near(left[12],0.f)); + + // The existing Console nativeBus is only a *view*; reproject it + // from the actual tested accepted session and its stable IDs. + auto admittedBus=live.getProperty("dryRoutingLab",{}) + .getProperty("nativeBus",{}); + auto* busObject=admittedBus.getDynamicObject(); + assert(busObject); + const auto projectNativePcm=[&](std::uint64_t rev) { + const auto* accepted=pcm.acceptedRouting(pcmEpoch,rev); + assert(accepted); + juce::Array rows,edges; + for(const auto& row:accepted->channels) { + auto view=std::make_unique(); + view->setProperty("id",juce::String(std::to_string(row.id.value))); + view->setProperty("role",row.role==ChannelRole::main?"MAIN":"INPUT"); + view->setProperty("name",juce::String(row.name)); + view->setProperty("format",row.format==ProcessingFormat::mono?"MONO":"STEREO"); + view->setProperty("primaryOutput", + juce::String(std::to_string(row.primaryOutput.value))); + const auto* admitted=pcm.acceptedRoster().find(row.id); + assert(admitted); + view->setProperty("fader",static_cast(admitted->faderLinear)); + view->setProperty("pan",static_cast(admitted->pan)); + view->setProperty("mute",admitted->mute); + view->setProperty("solo",admitted->solo); + view->setProperty("inserts",juce::var(juce::Array{})); + view->setProperty("peakL",.3);view->setProperty("peakR",.3); + rows.add(juce::var(view.release())); + } + for(const auto& edge:accepted->edges) { + auto view=std::make_unique(); + view->setProperty("edgeId",juce::String(std::to_string(edge.edgeId))); + view->setProperty("from",juce::String(std::to_string(edge.from.value))); + view->setProperty("to",juce::String(std::to_string(edge.to.value))); + view->setProperty("tap",edge.preFader?"PRE_FADER":"POST_FADER"); + view->setProperty("gainLinear",static_cast(edge.gainLinear)); + view->setProperty("primaryOutput",edge.primaryOutput); + edges.add(juce::var(view.release())); + } + busObject->setProperty("graphRevision", + juce::String(std::to_string(rev))); + busObject->setProperty("rosterRevision", + juce::String(std::to_string( + pcm.acceptedRosterRevision()))); + busObject->setProperty("channels",juce::var(rows)); + busObject->setProperty("edges",juce::var(edges)); + return Bridge::snapshot(live); + }; + const auto nativeBefore=projectNativePcm(3); + assert(nativeBefore.getProperty("graph",{}).getProperty("edges",{}) + .getArray()->size()==3); + // Derive from the real session rather than mocking the APPLY result. + struct ActualPcmControl final:BusControl { + DynamicAcceptedSession& session; + DynamicGraphRequest admitted; + ActualPcmControl(DynamicAcceptedSession& s, + const DynamicGraphRequest& p) + :session(s),admitted(p){} + Report applyNativeWireTransaction(std::uint64_t ep, + std::uint64_t graphRev,std::uint64_t rosterRev, + std::span edits) { + const auto result=session.wireTransaction( + rosterRev,graphRev,edits,admitted,ep,ep,false); + return {result.ok(),{},session.acceptedGraphRevision(), + session.acceptedRosterRevision(), + result.ok()?"":"NATIVE_PCM_REJECTED"}; + } + } nativePcmControl(pcm,patch); + auto userIntent=std::make_unique(); + userIntent->setProperty("requestId","v8:pcm:unplug:1"); + userIntent->setProperty("deviceEpoch",juce::String(std::to_string(pcmEpoch))); + userIntent->setProperty("baseGraphRevision","3"); + userIntent->setProperty("baseRosterRevision","3"); + userIntent->setProperty("operation","APPLY_WIRE_TRANSACTION"); + userIntent->setProperty("targetChannelId", + juce::String(std::to_string(src.value))); + auto unplug=std::make_unique(); + unplug->setProperty("op","REMOVE"); + unplug->setProperty("from",juce::String(std::to_string(src.value))); + unplug->setProperty("edgeId",juce::String(std::to_string(directId))); + juce::Array edits;edits.add(juce::var(unplug.release())); + auto payload=std::make_unique(); + payload->setProperty("changes",juce::var(edits)); + userIntent->setProperty("payload",juce::var(payload.release())); + const auto change=juce::var(userIntent.release()); + const auto response=bridge.processNativeBusIntent( + change,nativeBefore,nativePcmControl,false, + [](const juce::String&,ChannelId,const juce::var&, + std::uint64_t,std::uint64_t,std::uint64_t) + ->ActualPcmControl::Report {return {};}); + assert(response.getProperty("status","").toString()=="ACCEPTED"); + assert(response.getProperty("graphRevision","").toString()=="4"); + assert(response.getProperty("rosterRevision","").toString()=="4"); + assert(pcm.acceptedGraphRevision()==4); + assert(renderPcm()); + assert(left[11]>.05f&&left[11]size()==2); + assert(nativeBefore.getProperty("graph",{}) + .getProperty("revision","").toString()=="3"); + // Stale intent and exact edge replay must not remove any other MAIN. + auto staleChange=juce::JSON::parse(juce::JSON::toString(change,false)); + staleChange.getDynamicObject()->setProperty("requestId","v8:pcm:stale"); + const auto staleResponse=bridge.processNativeBusIntent( + staleChange,nativeAfter,nativePcmControl,false, + [](const juce::String&,ChannelId,const juce::var&, + std::uint64_t,std::uint64_t,std::uint64_t) + ->ActualPcmControl::Report {return {};}); + assert(staleResponse.getProperty("status","").toString()=="REJECTED"); + assert(pcm.acceptedGraphRevision()==4); + assert(renderPcm()&&left[11]setProperty("topologyFault",true); + const auto stale=Bridge::snapshot(live).getProperty("legacyM4",{}); + assert(stale.getProperty("supportedOps",{}).isVoid()); + assert(stale.getProperty("acceptedChannels",{}).isVoid()); + // No request above mutates the genuinely accepted M4 hardware route. + assert(static_cast(live.getProperty("dryRoutingLab",{}).getProperty("revision",0))==77); +} + +// G1 physical First Sound: one enabled callback pin becomes a MONO +// production source in ONE native mutation. No fabricated stereo IN1/IN1, +// no accidental modification of the last accepted M4 request on failure. +static void verifyFirstSoundOnePinNativeSourceDraft() { + using armix::mixer::NativeVerifiedSourcePatch; + auto command=std::make_unique(); + command->setProperty("deviceEpoch",juce::int64(17)); + command->setProperty("revision",juce::int64(8)); + juce::Array sources; + for(int c=0;c<10;++c) { + auto ch=std::make_unique(); + ch->setProperty("mode","NONE"); + ch->setProperty("left",-1); + ch->setProperty("right",-1); + ch->setProperty("gain",.25); + ch->setProperty("pan",0.0); + sources.add(juce::var(ch.release())); + } + command->setProperty("channels",juce::var(sources)); + const auto accepted=juce::var(command.release()); + const std::array physical{{5}}; + juce::var candidate; + assert(NativeVerifiedSourcePatch::prepare(accepted,6,"MONO",5,-1, + physical,17,9,candidate).isEmpty()); + const auto draftChannels=candidate.getProperty("channels",juce::var()); + const auto sourceBefore=accepted.getProperty("channels",juce::var()); + const auto* acceptedChannels=sourceBefore.getArray(); + const auto* changed=draftChannels.getArray(); + assert(changed && changed->size()==10 && acceptedChannels && + acceptedChannels->size()==10); + assert(changed->getReference(6).getProperty("mode","").toString()=="MONO"); + assert(static_cast(changed->getReference(6).getProperty("left",-1))==5); + assert(static_cast(changed->getReference(6).getProperty("right",0))==-1); + assert(acceptedChannels->getReference(6).getProperty("mode","").toString()=="NONE"); + assert(candidate.getProperty("revision",{}).toString()=="9"); + candidate=juce::var(); + assert(NativeVerifiedSourcePatch::prepare(accepted,6,"STEREO",5,5, + physical,17,9,candidate).isNotEmpty()); + assert(candidate.isVoid()); + assert(NativeVerifiedSourcePatch::prepare(accepted,6,"STEREO",5,7, + physical,17,9,candidate).isNotEmpty()); + assert(NativeVerifiedSourcePatch::prepare(accepted,6,"MONO",4,-1, + physical,17,9,candidate).isNotEmpty()); + assert(NativeVerifiedSourcePatch::prepare(accepted,6,"MONO",5,-1, + physical,18,9,candidate).isNotEmpty()); + assert(acceptedChannels->getReference(6).getProperty("mode","").toString()=="NONE"); + const std::array stereoPhysical{{5,7}}; + assert(NativeVerifiedSourcePatch::prepare(accepted,2,"STEREO",5,7, + stereoPhysical,17,9,candidate).isEmpty()); + const auto stereoRows=candidate.getProperty("channels",juce::var()); + assert(stereoRows.getArray()->getReference(2).getProperty("mode","").toString()=="STEREO"); + + // Real production route schema v2: distinguish physical SOURCE from + // channel PROCESSING width, and compile the accepted plan on the same + // NativeDryRouteCommand path used by LiveDryRoutingLab::apply(). + auto typed=juce::JSON::parse(juce::JSON::toString(accepted,false)); + typed.getDynamicObject()->setProperty("schemaVersion",2); + const auto typedSource=typed.getProperty("channels",{}); + for(auto& value:*typedSource.getArray()) { + auto* obj=value.getDynamicObject(); + assert(obj); + obj->setProperty("sourceKind","NONE"); + obj->setProperty("sourceFormat","NONE"); + obj->setProperty("channelFormat","STEREO"); + obj->setProperty("main",true); + obj->setProperty("mute",false); + obj->setProperty("solo",false); + } + juce::var typedNew; + assert(NativeVerifiedSourcePatch::prepare(typed,6,"MONO",5,-1, + physical,17,9,typedNew).isEmpty()); + const auto newRows=typedNew.getProperty("channels",{}); + const auto newCh=newRows.getArray()->getReference(6); + assert(newCh.getProperty("sourceKind","").toString()=="PHYSICAL"); + assert(newCh.getProperty("sourceFormat","").toString()=="MONO"); + assert(newCh.getProperty("channelFormat","").toString()=="STEREO"); + assert(static_cast(newCh.getProperty("right",0))==-1); + armix::mixer::NativeDryRouteCommand decoded; + juce::String error; + assert(armix::mixer::NativeDryRouteCommand::decode(typedNew,decoded,error)); + assert(decoded.channels.stripsAndMaster.strips[6].source== + armix::mixer::SourceMode::mono); + assert(decoded.channels.formats[6]==armix::mixer::ChannelFormat::stereo); + armix::mixer::ChannelRoutingPlan routed; + armix::mixer::LayoutError issue; + assert(armix::mixer::ChannelRoutingPlan::compile( + decoded.channels,physical,routed,issue)); + assert(routed.base.strips[6].inputA==0); + assert(routed.effectiveFormats[6]==armix::mixer::ChannelFormat::stereo); + const std::array mic{{.25f,.5f,.75f,1.f}}; + const float* nativePins[]{mic.data()}; + std::array routedL{},routedR{}; + assert(routed.base.extractSource(6,nativePins,1, + routedL.data(),routedR.data(),4)); + assert(routedL==mic && routedR==mic); + + // The *installed M4 native PCM renderer*, not DynamicPreparedMixerBlock: + // actual physical IN5 callback[0] -> independent CH07 -> stereo MAIN. + // Exercise the same LiveChannelFxGraph::process invoked by + // LiveDryRoutingLab::process from the sole JUCE hardware callback. + armix::mixer::PreparedRenderGraph prepared; + armix::mixer::RenderError renderError; + assert(armix::mixer::PreparedRenderGraph::compile( + decoded.channels,physical,decoded.sends,prepared,renderError,decoded.aux)); + armix::mixer::LiveChannelFxGraph production(prepared,64,64); + assert(production.setMainOutputPair(0,1,2)); + std::array mainL{},mainR{}; + armix::mixer::RenderLevels levels; + const auto beforeCallback=heapCalls.load(std::memory_order_relaxed); + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeCallback); + assert(mainL[0] > 0.f && mainR[0] > 0.f && + std::isfinite(mainL[0]) && std::isfinite(mainR[0])); + assert(near(mainL[0],mainR[0])); + assert(levels.channelPeak[6] > 0.f); + assert(levels.channelPeak[1] == 0.f); // CH02 unpatched, no fake PCM. + // The real strip deliberately de-clicks MUTE over up to 64 frames: + // a transition is NOT an immediate memset. Verify sample-by-sample + // monotonic fade and that steady muted blocks are truly silent. + assert(production.setStripControl(6,.25f,0.f,true,true,false)); + mainL.fill(1.f);mainR.fill(1.f); + const auto beforeMute=heapCalls.load(std::memory_order_relaxed); + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeMute); + assert(mainL[0]>0.f && mainR[0]>0.f); + // RAW physical microphone samples increase across the test block. + // Compare actual per-frame GAIN envelope after removing input amplitude, + // otherwise a correct fade is incorrectly rejected as nonmonotonic. + assert(mainL[0]/mic[0]>mainL[1]/mic[1] && + mainL[1]/mic[1]>mainL[2]/mic[2]); + assert(mainR[0]/mic[0]>mainR[1]/mic[1] && + mainR[1]/mic[1]>mainR[2]/mic[2]); + assert(mainL[3]>0.f && mainR[3]>0.f); // 4/64 frames, not a hard mute + // Sixteen small callback blocks complete EXACTLY the same 64-sample + // ramp as one 64-frame callback, without RT heap allocations. + float previousTail=mainL[3]/mic[3]; + for(int blockIndex=1;blockIndex<16;++blockIndex) { + const auto heapBefore=heapCalls.load(std::memory_order_relaxed); + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + assert(heapCalls.load(std::memory_order_relaxed)==heapBefore); + const float normalizedTail=mainL[3]/mic[3]; + assert(normalizedTail<=previousTail+1.e-5f); + previousTail=normalizedTail; + } + assert(near(mainL[3],0.f) && near(mainR[3],0.f)); + mainL.fill(1.f);mainR.fill(1.f); + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + for(int n=0;n<4;++n)assert(mainL[n]==0.f && mainR[n]==0.f); + assert(levels.channelPeak[6]==0.f); + assert(production.setStripControl(6,.25f,0.f,true,false,false)); + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + assert(mainL[0]>0.f&&mainR[0]>0.f); + assert(mainL[3]>mainL[0]); // unmute ramps, never spikes to unity + for(int k=1;k<16;++k) + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + assert(mainL[3]>0.f); + // A rapid re-MUTE in the middle of an unmute envelope does not + // interpolate from stale unity or introduce a discontinuity. + assert(production.setStripControl(6,.25f,0.f,true,true,false)); + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + assert(mainL[0]>0.f); + juce::var denied; + assert(NativeVerifiedSourcePatch::prepare(typed,6,"STEREO",5,5, + physical,17,9,denied).isNotEmpty()); + assert(denied.isVoid()); + assert(typedSource.getArray()->getReference(6) + .getProperty("sourceKind","").toString()=="NONE"); + + // SOURCE STEREO can be folded into MONO processing independently. + auto typedFold=juce::JSON::parse(juce::JSON::toString(typed,false)); + auto foldedRows=typedFold.getProperty("channels",{}); + foldedRows.getArray()->getReference(2).getDynamicObject() + ->setProperty("channelFormat","MONO"); + juce::var stereoFold; + assert(NativeVerifiedSourcePatch::prepare(typedFold,2,"STEREO",5,7, + stereoPhysical,17,9,stereoFold).isEmpty()); + assert(armix::mixer::NativeDryRouteCommand::decode( + stereoFold,decoded,error)); + assert(armix::mixer::ChannelRoutingPlan::compile( + decoded.channels,stereoPhysical,routed,issue)); + assert(routed.effectiveFormats[2]==armix::mixer::ChannelFormat::mono); + assert(routed.foldStereoToMono[2]); + + // SOURCE/VST3 lifecycle migration at production M4 graph granularity: + // both verified physical pins belong to one unchanged device epoch. + // Selecting another MONO pin must preserve the very SAME prepared + // JUCE processor (state/editor/tail identity), not silently rebuild it. + juce::var beforeSwap; + assert(NativeVerifiedSourcePatch::prepare( + typed,6,"MONO",5,-1,stereoPhysical,17,9,beforeSwap).isEmpty()); + armix::mixer::NativeDryRouteCommand oldCommand; + assert(armix::mixer::NativeDryRouteCommand::decode( + beforeSwap,oldCommand,error)); + armix::mixer::PreparedRenderGraph oldPlan; + assert(armix::mixer::PreparedRenderGraph::compile( + oldCommand.channels,stereoPhysical,oldCommand.sends,oldPlan, + renderError,oldCommand.aux)); + auto firstFxGraph=std::make_unique( + oldPlan,64,64); + auto nativeFx=std::make_unique(2.f); + nativeFx->prepareToPlay(48000,64); + assert(firstFxGraph->install(6,std::move(nativeFx), + "CH07 native vendor FX","ch07-stable-vendor-id")); + const auto* originalInstance=firstFxGraph->instanceProcessor(6); + assert(originalInstance!=nullptr); + const std::array secondPin{{.1f,.2f,.3f,.4f}}; + const float* twoNativeInputs[]{mic.data(),secondPin.data()}; + std::array oldMainL{},oldMainR{}; + const auto beforeOldRender=heapCalls.load(std::memory_order_relaxed); + assert(firstFxGraph->process(twoNativeInputs,2,oldMainL.data(), + oldMainR.data(),4)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeOldRender); + assert(oldMainL[0]>0.f && oldMainR[0]>0.f); + juce::var afterSwap; + assert(NativeVerifiedSourcePatch::prepare( + beforeSwap,6,"MONO",7,-1,stereoPhysical,17,10,afterSwap).isEmpty()); + armix::mixer::NativeDryRouteCommand switchedCommand; + assert(armix::mixer::NativeDryRouteCommand::decode( + afterSwap,switchedCommand,error)); + armix::mixer::PreparedRenderGraph switchedPlan; + assert(armix::mixer::PreparedRenderGraph::compile( + switchedCommand.channels,stereoPhysical,switchedCommand.sends, + switchedPlan,renderError,switchedCommand.aux)); + auto secondFxGraph=std::make_unique( + switchedPlan,64,64); + assert(secondFxGraph->reuseAt(6,0,*firstFxGraph,0,"ch07-stable-vendor-id")); + assert(secondFxGraph->instanceProcessor(6)==originalInstance); + firstFxGraph.reset(); // old control graph retired; vendor must stay alive + assert(secondFxGraph->instanceProcessor(6)==originalInstance); + std::array newMainL{},newMainR{}; + const auto beforeNewRender=heapCalls.load(std::memory_order_relaxed); + assert(secondFxGraph->process(twoNativeInputs,2,newMainL.data(), + newMainR.data(),4)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeNewRender); + assert(newMainL[0]>0.f && newMainR[0]>0.f); + // Exactly one FX call and one real new source: 0.1 / 0.25 amplitude. + assert(near(newMainL[0]/oldMainL[0],.4f)); + assert(near(newMainR[0]/oldMainR[0],.4f)); + assert(typedSource.getArray()->getReference(6) + .getProperty("mode","").toString()=="NONE"); +} + +// V8 S0: a C++ fixture, built with the SAME header serializer installed in +// JUCE WebView, never hand-maintained by GUI/FAT. No real audio device exists +// for this UNREADY fixture and it intentionally has no dynamic capabilities. +static void verifyNativePuzzleV8FixtureAndWire() { + using namespace armix::console; + PuzzleV8Snapshot fixtureSource; + fixtureSource.epoch="1"; + PuzzleV8Ack rejected; + rejected.requestId="native-fixture-session:1"; + rejected.deviceEpoch=fixtureSource.epoch; + const auto expected=PuzzleV8Wire::fixture(fixtureSource,rejected); + const auto fixtureFile=std::filesystem::path(__FILE__).parent_path()/ + "fixtures"/"console-v8-native-unready.json"; + std::ifstream source(fixtureFile,std::ios::binary); + assert(source.is_open()); + const std::string checked((std::istreambuf_iterator(source)), + std::istreambuf_iterator()); + // Git on Windows can checkout a one-line JSON fixture with CRLF. + // The native stdout generator deliberately emits canonical LF; accept + // only the OS newline conversion, never changed JSON data. + std::string canonical=checked; + if(canonical.size()==expected.size()+1 && + canonical.size()>=2 && canonical.substr(canonical.size()-2)=="\r\n") + canonical.erase(canonical.size()-2,1); + assert(expected==canonical); + const auto parsed=juce::JSON::parse(juce::String::fromUTF8(expected.c_str())); + assert(parsed.isObject()); + const auto events=parsed.getProperty("events",{}); + assert(events.getArray()&&events.getArray()->size()==4); + const auto snap=events.getArray()->getReference(0).getProperty("payload",{}); + const auto device=snap.getProperty("device",{}); + const auto graph=snap.getProperty("graph",{}); + const auto telem=snap.getProperty("telemetry",{}); + const auto cmd=events.getArray()->getReference(1).getProperty("payload",{}); + const auto ack=events.getArray()->getReference(2).getProperty("payload",{}); + const auto repeated=events.getArray()->getReference(3).getProperty("payload",{}); + assert(cmd.getProperty("requestId","").toString()== + ack.getProperty("requestId","").toString()); + assert(cmd.getProperty("deviceEpoch","").toString()=="1"); + assert(juce::JSON::toString(snap)==juce::JSON::toString(repeated)); + // The same installed JUCE bridge must produce this UNREADY event state. + const auto native=armix::console::LiveConsoleBridgeV6::snapshot(juce::var()); + assert(juce::JSON::toString(snap)==juce::JSON::toString(native)); + armix::console::LiveConsoleBridgeV6 runtime; + const auto realAck=runtime.rejectUnsupportedIntent(cmd,native); + assert(juce::JSON::toString(ack)==juce::JSON::toString(realAck)); + assert(static_cast(snap.getProperty("schemaVersion",0))==6); + assert(!static_cast(snap.getProperty("productionCallbackLive",true))); + assert(device.getProperty("enabledInputs",{}).getArray()->isEmpty()); + assert(device.getProperty("epoch","").toString()=="1"); + assert(device.getProperty("enabledOutputs",{}).getArray()->isEmpty()); + assert(device.getProperty("inputEndpoints",{}).getArray()->isEmpty()); + assert(device.getProperty("outputEndpoints",{}).getArray()->isEmpty()); + assert(device.getProperty("sampleRate",{}).isVoid()); + assert(graph.getProperty("channels",{}).getArray()->isEmpty()); + assert(graph.getProperty("capabilities",{}) + .getProperty("supportedOps",{}).getArray()->isEmpty()); + assert(!static_cast(telem.getProperty("mainPcmPresent",true))); + assert(ack.getProperty("requestId","").toString()=="native-fixture-session:1"); + assert(ack.getProperty("status","").toString()=="REJECTED"); + PuzzleV8Snapshot withPins; + withPins.inputs.push_back({5,0,"Mic \"1\"\n",true,.25}); + withPins.outputs.push_back({7,0,"PHYS OUT8",false,0.}); + const auto physical=juce::JSON::parse(juce::String::fromUTF8( + PuzzleV8Wire::snapshot(withPins).c_str())); + const auto physicalDev=physical.getProperty("device",{}); + const auto inputMask=physicalDev.getProperty("enabledInputs",{}); + const auto outputMask=physicalDev.getProperty("enabledOutputs",{}); + assert(inputMask.getArray()->size()==1 && + static_cast(inputMask.getArray()->getReference(0))==5); + assert(outputMask.getArray()->size()==1 && + static_cast(outputMask.getArray()->getReference(0))==7); + const auto in=physicalDev.getProperty("inputEndpoints",{}); + assert(in.getArray()->getReference(0).getProperty("label","").toString()== + "Mic \"1\"\n"); + assert(in.getArray()->getReference(0).getProperty("id","").toString()=="in:5"); + assert(static_cast(in.getArray()->getReference(0).getProperty("active",false))); + assert(static_cast(in.getArray()->getReference(0) + .getProperty("rawPeak",0.))==.25); +} + +// E2: native JUCE VST3 stays audible through a serial GROUP edit; a missing +// successor FX owner rejects atomically rather than deleting hosted processing. +static void verifyChannelIdGroupPreservesHostedFx() { + using Bank=DynamicChannelFxLeaseBank; + using Pub=DynamicNativeSessionPublisher; + constexpr std::uint64_t epoch=1007; + constexpr float center=.7071067811865475f; + DynamicAcceptedSession live; + DynamicGraphRequest route;route.physicalInputs=1;route.maxFrames=32; + ChannelEdit micCreate;micCreate.kind=ChannelEdit::Kind::add; + micCreate.position=0;micCreate.role=ChannelRole::input; + micCreate.format=ProcessingFormat::mono;micCreate.text="VOICE"; + ChannelEdit mainCreate=micCreate;mainCreate.position=1; + mainCreate.role=ChannelRole::main; + mainCreate.format=ProcessingFormat::stereo;mainCreate.text="MAIN"; + const std::array creates{micCreate,mainCreate}; + const auto created=live.edit(0,0,creates,route,epoch,epoch,true); + assert(created.ok()&&created.edit.createdIds.size()==2); + const auto voice=created.edit.createdIds[0],main=created.edit.createdIds[1]; + route.sources={{voice,0,-1,false}}; + ChannelEdit link;link.kind=ChannelEdit::Kind::setPrimaryOutput; + link.id=voice;link.target=main; + const std::array routeEdit{link}; + auto gain=std::make_unique(2.f); + gain->prepareToPlay(48000.,32); + Bank::Assignment assignment;assignment.id=voice; + assignment.format=ProcessingFormat::mono; + assignment.inserts.push_back(std::make_shared( + std::move(gain),"voice-gain","voice-gain",32)); + const auto token=assignment.inserts[0]->instanceId; + const std::array assignments{assignment}; + auto bank=std::make_shared(); + assert(Bank::prepare(epoch,2,assignments,*bank)==Bank::Fault::none); + const auto plan=[&](std::shared_ptr owner,std::uint64_t rev) { + Pub::FxPlan fx;fx.owner=std::static_pointer_cast(owner); + fx.context=owner.get(); + fx.render=+[](void* p,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(p))(id,l,r,n); + }; + fx.deviceEpoch=epoch;fx.graphRevision=rev;return fx; + }; + assert(live.edit(1,1,routeEdit,route,epoch,epoch,true,plan(bank,2)).ok()); + std::array input{},l{},rr{};input.fill(.2f); + const float* pins[]{input.data()}; + int fallbackCalls=0; + const auto noFallback=[&](ChannelId,float*,float*,int) noexcept { + ++fallbackCalls; + }; + const auto render=[&]() { + return live.render(epoch,pins,1,l.data(),rr.data(),32,false,noFallback); + }; + auto heapBefore=heapCalls.load(std::memory_order_relaxed); + assert(render()&&near(l[31],.2f*2.f*center)); + assert(heapCalls.load(std::memory_order_relaxed)==heapBefore); + const std::array selected{voice}; + const auto denied=live.createBusForSelected(2,2,selected,"VOCALS", + ChannelRole::group,route,epoch,epoch,true); + assert(!denied.ok()&&denied.edit.createdIds.empty()); + assert(denied.native.fault==Pub::Fault::invalidCandidate); + assert(live.acceptedGraphRevision()==2); + assert(render()&&near(l[31],.2f*2.f*center)); + auto nextBank=std::make_shared(); + assert(Bank::reuseRevision(epoch,3,*bank,*nextBank)==Bank::Fault::none); + assert(Bank::reuseRevision(epoch,2,*bank,*nextBank)==Bank::Fault::invalidEpoch); + assert((*nextBank->ownerForControl(voice,0))->instanceId==token); + const int pluginCount=GainFx::living; + const auto group=live.createBusForSelected(2,2,selected,"VOCALS", + ChannelRole::group,route,epoch,epoch,true,.25f,plan(nextBank,3)); + assert(group.ok()&&group.edit.createdIds.size()==1); + assert(live.acceptedGraphRevision()==3); + assert(live.acceptedRouting(epoch,3)->find(voice)->primaryOutput== + group.edit.createdIds.front()); + heapBefore=heapCalls.load(std::memory_order_relaxed); + assert(render()&&near(l[31],.2f*2.f*center)); + assert(heapCalls.load(std::memory_order_relaxed)==heapBefore); + assert(GainFx::living==pluginCount&&fallbackCalls==0); + assert(!live.setLiveMix(epoch,2,voice,0.f,0.f)); + live.unpublish();live.pollRetirement(); +} + +int main(int argc,char** argv) { + if(argc==2 && std::string(argv[1])=="--emit-console-s0-json") { + verifyNativePuzzleV8FixtureAndWire(); + armix::console::PuzzleV8Snapshot s; + armix::console::PuzzleV8Ack ack; + ack.requestId="native-fixture-session:1"; + ack.deviceEpoch=s.epoch; + std::cout<.3f); } + // Run M5 AFTER the legacy suite: older M4 tests use absolute global + // GainFx::living/released counters as their own lifetime oracle. Running + // M5 before them changes those historical baseline counts, not DSP. + // M5 additionally asserts zero heap and valid vendor leases itself. + verifyUniversalChannelIdFxLeaseAndLivePcm(); + verifyMU1LegacyM4FxFullMigrationAndMonitorPcm(); + verifyOccupiedExternalCh1Owner(); + verifySourceFormatIndependentPanPcmParity(); + verifyNativeConsoleWireRejectsUnsupportedM4AndPreservesEpoch(); + verifyFirstSoundOnePinNativeSourceDraft(); + verifyNativePuzzleV8FixtureAndWire(); + verifyChannelIdGroupPreservesHostedFx(); // Tests above use a real JUCE AudioProcessor processing seam. Vendor // VST3 formats and sound quality require separate Windows hardware FAT. } diff --git a/tests/live_graph_contract_test.mjs b/tests/live_graph_contract_test.mjs index 594c641cf..6edcd12f1 100644 --- a/tests/live_graph_contract_test.mjs +++ b/tests/live_graph_contract_test.mjs @@ -28,6 +28,22 @@ test('preset UI reflects callback-acknowledged state not queued state',()=>{ assert.match(m,/arMixNativePresetLoaded/); assert.match(b,/RECALL LIVE/); }); +test('single engine production selection forbids old VST processing in diagnostic fallback',()=>{ + const authority=readFileSync(new URL('../engine/core/NativeRenderAuthority.h',import.meta.url),'utf8'); + assert.match(authority,/enum class NativeRenderOwner/); + assert.match(authority,/failSilentUnpatched/); + assert.match(authority,/acceptedM4Session/); + assert.match(authority,/isolatedDiagnostic/); + assert.match(e,/NativeRenderAuthority::select\(/); + assert.match(e,/NativeRenderOwner::acceptedM4Session/); + const start=e.indexOf('// The only remaining stereo renderer is DIAGNOSTIC'); + const end=e.indexOf('const auto elapsedUs = clockMicros() - beginUs',start); + assert.ok(start>0 && end>start,'explicit diagnostic-only tail must exist'); + const fallback=e.slice(start,end); + assert.doesNotMatch(fallback,/processor->processBlock|MidiBuffer midi|make_unique|make_shared/, + 'no second legacy stereo FX chain may be executed from diagnostics'); +}); + test('ADD/REMOVE remain guarded while MOVE publishes physical-slot order',()=>{ assert.match(e,/fxMovePhase_\.load/); assert.match(e,/FxOrderPlan::moved/); @@ -36,13 +52,26 @@ test('ADD/REMOVE remain guarded while MOVE publishes physical-slot order',()=>{ assert.doesNotMatch(move,/detach\(|attach\(/); }); -test('bypass is sample-smoothed on audio callback without control-thread CPU work',()=>{ +test('bypass is sample-smoothed by one original CH1 DSP owner for M4 and native ChannelId',()=>{ assert.match(e,/bypassEnvelope/); - assert.match(e,/bypass\.request\(cycle\.graph->bypassFlags/); - assert.match(e,/bypass\.transitioning\(\)/); - assert.match(e,/dryScratch_\.setSize \(2, maxFrames/); - assert.match(e,/bypass\.next\(\)/); - assert.match(e,/bypass\.shouldProcessWet\(\)/); + const start=e.indexOf('static void renderOriginalChannelOneGraph('); + const legacy=e.indexOf('static void processLegacyChannelOne(',start); + const native=e.indexOf('static void processOwnedChannelOne(',legacy); + const end=e.indexOf('void audioDeviceIOCallbackWithContext',native); + assert.ok(start>=0&&legacy>start&&native>legacy&&end>native, + 'native and M4 must share the original CH1 sample-accurate DSP owner'); + const originalDSP=e.slice(start,legacy); + const adapters=e.slice(legacy,end); + assert.match(originalDSP,/bypass\.request\(graph\.bypassFlags/); + assert.match(originalDSP,/slot\.processor->processBlock\(buffer,midi\)/); + assert.match(originalDSP,/bypass\.transitioning\(\)/); + assert.match(originalDSP,/graph\.dryScratch\.getWritePointer\(0\)/); + assert.match(originalDSP,/bypass\.next\(\)/); + assert.match(originalDSP,/bypass\.shouldProcessWet\(\)/); + assert.match(e,/Graph\(\) \{ dryScratch\.setSize\(2,maxFrames,false,true,false\); \}/); + assert.match(adapters,/renderOriginalChannelOneGraph\(\*graph,left,right,frames\)/); + assert.match(adapters,/renderOriginalChannelOneGraph\(\s*\*static_cast\(token\)/); + assert.match(adapters,/fx\.owner=std::static_pointer_cast\(graphOwned_\)/); assert.doesNotMatch(e.slice(e.indexOf('bool setBypass'),e.indexOf('bool removeAt')),/detach\(|prepareToPlay|releaseResources/); }); @@ -52,7 +81,7 @@ test('R0B CH1 MOVE inside routed 10CH graph uses the same callback-boundary de-c assert.match(move,/FxOrderPlan::moved/); assert.match(move,/fxMovePendingOrder_\.store/); assert.doesNotMatch(move,/detach\(|attach\(|prepareToPlay|releaseResources/); - const begin=e.indexOf('if (dryRoutingLab_.active())',e.indexOf('callbackCount_.fetch_add')); + const begin=e.indexOf('if (renderOwner ==',e.indexOf('callbackCount_.fetch_add')); const end=e.indexOf('const bool enabled = monitor_',begin); const routed=e.slice(begin,end); assert.match(routed,/FxMoveRamp::gain\(\s*routedFxMove,i,samples\)/); @@ -79,7 +108,7 @@ test('R0B major milestone: ADD and REMOVE are prepared control-thread transactio assert.match(e,/ownPlugin\s*\(/); assert.match(e,/old\.reset\(\); \/\/ Vendor cleanup only on final CONTROL-owned reference/); assert.match(e,/handoff_\.stage\(stagedOwner_\.get\(\)\)/); - const callback=e.slice(e.indexOf('if (dryRoutingLab_.active())',e.indexOf('callbackCount_.fetch_add')), + const callback=e.slice(e.indexOf('if (renderOwner ==',e.indexOf('callbackCount_.fetch_add')), e.indexOf('const bool enabled = monitor_',e.indexOf('callbackCount_.fetch_add'))); assert.match(callback,/handoff_\.endCycle\(cycle\)/); assert.match(callback,/cycle\.fadeOut/); @@ -103,13 +132,14 @@ test('R0B B3 NORMAL output is fail-silent while FX graph retirement still progre const beginning=e.indexOf('void audioDeviceIOCallbackWithContext'); const fence=e.indexOf('if (!independent_.active()',beginning); const lease=e.indexOf('const auto cycle = handoff_.beginCycle()',beginning); - const failSilent=e.indexOf('if (activeDiagnosticRoute == armix::diagnostics::Route::normal',beginning); + const failSilent=e.indexOf('if (renderOwner ==',lease); const callbackMetrics=e.indexOf('const std::uint64_t beginUs = clockMicros()',beginning); assert.ok(beginning>=0 && fence>beginning && lease>fence && failSilent>lease && callbackMetrics>failSilent, 'DIRECT fence first, then FX cycle lease, then fail-silent native gate'); const gate=e.slice(failSilent,callbackMetrics); - assert.match(gate,/!dryRoutingLab_\.active\(\)/); + assert.match(e,/NativeRenderAuthority::select\(/); + assert.match(gate,/NativeRenderOwner::failSilentUnpatched/); assert.match(gate,/FloatVectorOperations::clear\(outputs\[c\], samples\)/); assert.match(gate,/outputPeakL_\.store\(0\.f/); assert.match(gate,/handoff_\.endCycle\(cycle\)/, diff --git a/tests/live_routing_ui_contract_test.mjs b/tests/live_routing_ui_contract_test.mjs index 7e3f9ac05..454b8e8e9 100644 --- a/tests/live_routing_ui_contract_test.mjs +++ b/tests/live_routing_ui_contract_test.mjs @@ -46,7 +46,7 @@ test("GUI exposes only truthful dry device routes and acknowledged commit",()=>{ }); test("STOP-race is fail closed: all outputs are written to silence without CH1 fallback",()=>{ - const enter=engine.indexOf("if (dryRoutingLab_.active())",engine.indexOf("callbackCount_.fetch_add")); + const enter=engine.indexOf("if (renderOwner ==",engine.indexOf("callbackCount_.fetch_add")); // Bound the entire routed branch by the first statement of the legacy // fallback, not by an informational comment that can change at each R0B slice. const end=engine.indexOf("const bool enabled = monitor_",enter); diff --git a/tests/mixer_routing_plan_test.cpp b/tests/mixer_routing_plan_test.cpp index 19517fb1c..248df8046 100644 --- a/tests/mixer_routing_plan_test.cpp +++ b/tests/mixer_routing_plan_test.cpp @@ -400,7 +400,7 @@ static void verifyDynamicPreparedPcm() { ChannelEdit solo;solo.kind=Kind::setSolo;solo.id=ids[10];solo.enabled=true; assert(bank.edit(bank.revision(),std::span(&solo,1)).ok()); assert(DynamicPreparedMixerBlock::compile(bank,request,renderer,error)); - assert(renderer.activeChannels()==2); // CH11 + MAIN only + assert(renderer.activeChannels()==6); // 5 sources retain VST tails; SOLO gates PCM assert(renderer.process(physical,2,l.data(),r.data(),32,fx)); assert(close(l[0],.4f*center)); solo.enabled=false; @@ -522,7 +522,7 @@ static void verifyDynamicDualBusPcm() { muteMain.enabled=true; assert(bank.edit(bank.revision(),std::span(&muteMain,1)).ok()); assert(DynamicPreparedMixerBlock::compile(bank,req,live,error)); - assert(live.activeChannels()==3); // CH1, CH32 and MONITOR + assert(live.activeChannels()==5); // MAIN mute retains tails; MONITOR stays independent assert(live.process(inputs,3,mainL.data(),mainR.data(),64,fx, monL.data(),monR.data())); assert(mainL[0]==0.f && mainR[0]==0.f); @@ -690,6 +690,50 @@ static void verifyLegacyToDynamicProductionPcmParity() { } + +static void verifyRealtimeFaderRampAcrossShortCallbacks() { + using namespace armix::mixer; + const std::array pins{0,1}; + ChannelRoutingConfig routing; + routing.stripsAndMaster.strips[0]= + {SourceMode::mono,0,-1,1.f,0.f,false,false}; + SendRequest sends; + sends.toMaster[0]=true; + PreparedRenderGraph graph; + RenderError error; + assert(PreparedRenderGraph::compile(routing,pins,sends,graph,error)); + PreparedMixerBlock block(graph,64); + RealtimeStripControls controls; + assert(controls.set(0,1.f,0.f,true,false,false)); + std::array mic{},unused{},left{},right{}; + mic.fill(.8f); + const float* sources[]={mic.data(),unused.data()}; + const auto noFx=[](int,float*,float*,int) noexcept {}; + const auto render=[&](int frames) { + left.fill(0.f);right.fill(0.f); + return block.process(sources,2,left.data(),right.data(),frames, + noFx,nullptr,&controls); + }; + assert(render(4)); + const float baseline=left[0]; + assert(baseline>.01f && close(right[3],baseline)); + assert(controls.set(0,0.f,0.f,true,false,false)); + assert(render(4)); + assert(close(left[3],baseline*60.f/64.f,3.e-5f)); + assert(render(16)); + assert(close(left[15],baseline*44.f/64.f,3.e-5f)); + assert(render(32)); + assert(close(left[31],baseline*12.f/64.f,3.e-5f)); + assert(render(12)); + assert(close(left[11],0.f,3.e-5f)); + // Mid-show fader reversal must not jump to the last requested target. + assert(controls.set(0,1.f,0.f,true,false,false)); + assert(render(4)); + assert(close(left[3],baseline*4.f/64.f,3.e-5f)); + assert(render(60)); + assert(close(left[59],baseline,3.e-5f)); +} + static void verifyRealtimeAuxPostGainWithoutGraphRebuild() { using namespace armix::mixer; const std::array pins{0,1}; @@ -798,8 +842,15 @@ static void verifyRealtimeAuxMasterPcmBothOutputs() { assert(!block.setAuxBusGain(0,std::numeric_limits::quiet_NaN())); assert(close(block.auxBusGain(0),0.f)); assert(close(block.plan().aux.buses[0].gain,1.f)); // topology immutable - // Legacy offline/no-live-control path still uses immutable compiled gain. + // Explicit AUX automation remains live even without a separate strip + // controls object. It MUST NOT silently fall back to stale compiled gain + // because older physical/native paths do not always pass that object. assert(block.process(inputs,2,left.data(),right.data(),64,noFx)); + assert(close(left[0],0.f)); + // A newly prepared graph starts at its own immutable initial gain: + // structural transaction/Show recall does not leak old AUX state. + PreparedMixerBlock freshlyPrepared(graph,64); + assert(freshlyPrepared.process(inputs,2,left.data(),right.data(),64,noFx)); assert(close(left[0],initial)); } @@ -969,6 +1020,7 @@ int main() { verifyDynamicChannelIdLiveControls(); verifyDynamicNativeSessionPublication(); verifyStudioConsoleBusBatchPcm(); + verifyRealtimeFaderRampAcrossShortCallbacks(); verifyRealtimeAuxMasterPcmBothOutputs(); verifyRealtimeAuxPostGainWithoutGraphRebuild(); verifyLegacyToDynamicProductionPcmParity(); diff --git a/tests/native_live_show_capture_test.cpp b/tests/native_live_show_capture_test.cpp index 734e7f625..7e2a250f4 100644 --- a/tests/native_live_show_capture_test.cpp +++ b/tests/native_live_show_capture_test.cpp @@ -104,6 +104,21 @@ int main() { // Never let untrusted or stale UI state replace an accepted capture. const auto prior=Codec::encode(captured); + // Dynamic native GROUP/FX RETURN exists in actual PCM but ShowV2 has + // no such role. Refuse both SAVE and RECALL before mutating either + // accepted routing, file generation or vendor plugin state. + auto withNativeBus=setup(); + auto nativeLab=withNativeBus.getProperty("dryRoutingLab",{}); + set(nativeLab,"nativeBusStructural",true); + const auto busSave=NativeLiveShowCapture::captureDry( + withNativeBus,"Native Bus Show",captured,true); + assert(busSave.contains("GROUP/FX RETURN")); + assert(Codec::encode(captured)==prior); + juce::var rejectedBusRecall; + const auto busRecall=NativeDryShowRecall::prepare( + decoded,withNativeBus,rejectedBusRecall,true); + assert(busRecall.contains("GROUP/FX RETURN")); + assert(rejectedBusRecall.isVoid()); auto armed=setup();set(armed,"monitor",true); assert(NativeLiveShowCapture::captureDry(armed,"Dry Routing Test",captured).isNotEmpty()); assert(Codec::encode(captured)==prior); diff --git a/tests/p0_diagnostic_contract_test.mjs b/tests/p0_diagnostic_contract_test.mjs index 417ebd0a8..f44fd5a20 100644 --- a/tests/p0_diagnostic_contract_test.mjs +++ b/tests/p0_diagnostic_contract_test.mjs @@ -27,7 +27,12 @@ test('audio callback isolates low-amplitude oscillator from input and VST3',()=> assert.match(engine,/const bool captureTest = route == armix::diagnostics::Route::captureOnly/); assert.match(engine,/diagnosticTone_\.next \(audible\)/); assert.match(engine,/if \(!toneTest\)/); - assert.match(engine,/if \(!dry\)/); + const start=engine.indexOf('// The only remaining stereo renderer is DIAGNOSTIC'); + const end=engine.indexOf('const auto elapsedUs = clockMicros() - beginUs',start); + assert.ok(start>0&&end>start,'isolated diagnostics must have an explicit owner'); + assert.doesNotMatch(engine.slice(start,end), + /processor->processBlock|MidiBuffer midi/, + 'test tone and capture-only must never enter a legacy VST processor'); assert.match(osc,/0\.0316227766/); assert.doesNotMatch(osc,/new |malloc\(|std::vector|mutex|lock_guard|fwrite\(/); assert.match(build,/P0DiagnosticTone/); diff --git a/tests/realtime_control_test.cpp b/tests/realtime_control_test.cpp index 0cb920ab9..11d3b5ea0 100644 --- a/tests/realtime_control_test.cpp +++ b/tests/realtime_control_test.cpp @@ -1,5 +1,10 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/core/RealtimeControl.h" +#include "../engine/core/PreparedMixerBlock.h" +#include "../engine/core/RealtimeRenderPermit.h" +#include "../engine/core/RealtimeRoutePublisher.h" +#include "../engine/core/NativeRenderAuthority.h" +#include #include #ifdef NDEBUG #undef NDEBUG @@ -12,6 +17,90 @@ #include using namespace armix::rt; int main(){ + // Production cannot fall through to a second stereo/VST mixer. The + // only old stereo path is explicitly test/diagnostic and disconnected + // from an accepted native M4 route. + using Owner=armix::mixer::NativeRenderOwner; + using Authority=armix::mixer::NativeRenderAuthority; + assert(Authority::select(true,false)==Owner::failSilentUnpatched); + assert(Authority::select(true,true)==Owner::acceptedM4Session); + assert(Authority::select(false,true)==Owner::acceptedM4Session); + assert(Authority::select(false,false)==Owner::isolatedDiagnostic); + assert(!Authority::mayRunDiagnostic( + Authority::select(false,true))); + + // M5 LIVE (the installed M4 callback, not only prepared ChannelId): + // all 4 controls change in ONE atomic, while 2 threads run 200k + // opposing GUI gestures. RT must see either complete gesture A or B; + // no left from A with right/MUTE/SOLO from B. + using Controls=armix::mixer::RealtimeStripControls; + Controls atomicControls; + const auto u=atomicControls.read(2); + assert(std::fabs(u.left-1.f)<1e-6f && std::fabs(u.right-1.f)<1e-6f); + assert(!u.mute && !u.solo); + assert(atomicControls.set(2,.5f,-1.f,false,false,true)); + const auto a=atomicControls.read(2); + assert(std::fabs(a.left-.5f)<1e-6f && std::fabs(a.right)<1e-6f); + assert(!a.mute && a.solo); + assert(atomicControls.set(2,.8f,1.f,false,true,false)); + const auto b=atomicControls.read(2); + assert(std::fabs(b.left)<1e-6f && std::fabs(b.right-.8f)<1e-6f); + assert(b.mute && !b.solo); + std::atomic badMixed{false}; + constexpr int gestures=200000; + std::thread ctl([&]{ + for(int k=0;k gateHeld{false},releaseGate{false}; + std::thread activeRender([&] { + armix::rt::RealtimeRenderPermit permit(renderGate); + assert(static_cast(permit)); + gateHeld.store(true,std::memory_order_release); + while(!releaseGate.load(std::memory_order_acquire)) + std::this_thread::yield(); // TEST thread only; never real AUDIO + }); + while(!gateHeld.load(std::memory_order_acquire)) + std::this_thread::yield(); + for(int i=0;i<20000;++i) { + armix::rt::RealtimeRenderPermit rejected(renderGate); + assert(!static_cast(rejected)); // never wait, render twice, lock + } + releaseGate.store(true,std::memory_order_release); + activeRender.join(); + { + armix::rt::RealtimeRenderPermit reentered(renderGate); + assert(static_cast(reentered)); + } + std::cout<<"PASS: single M4/ChannelId RT renderer, 20000 duplicate callbacks fail closed\\n"; + SpscQueue q; int value=-1; assert(!q.tryPop(value)); @@ -51,6 +140,43 @@ int main(){ checkPan(0.f,0.f,1.f,0.f,1.f); checkPan(0.f,1.f,0.f,1.f,0.f); std::cout<<"PASS: native stereo pan centre, extremes, half-pan and unit-gain dual-mono\n"; + + // M1: retired FX/PCM snapshots remain owned until callbacks release + // their leases; a full bounded queue rejects instead of growing memory. + struct RetireProbe { + std::atomic* counter; + explicit RetireProbe(std::atomic& c):counter(&c){} + ~RetireProbe(){counter->fetch_add(1,std::memory_order_relaxed);} + }; + std::atomic destroyed{0}; + RealtimeRoutePublisher publisher; + const auto publish=[&](std::uint64_t revision) { + auto next=std::make_unique::Snapshot>(); + next->deviceEpoch=7;next->graphRevision=revision; + next->prepared=std::make_unique(destroyed); + return publisher.publish(std::move(next),revision-1,7); + }; + using Result=RealtimeRoutePublisher::Result; + assert(publish(1)==Result::applied); + { + auto lease=publisher.acquire(); + assert(lease.get(7)&&lease.get(7)->graphRevision==1); + assert(publish(2)==Result::applied); + assert(publish(3)==Result::applied); + assert(publisher.pendingRetirements()==2); + assert(publish(4)==Result::retirementFull); + assert(destroyed.load(std::memory_order_relaxed)==1); + assert(lease.get(7)->graphRevision==1); + } + assert(publisher.pollRetirement()); + assert(publisher.pendingRetirements()==0); + assert(destroyed.load(std::memory_order_relaxed)==3); + assert(publish(4)==Result::applied); + publisher.unpublish(); + assert(publisher.pollRetirement()); + // Three accepted snapshots + one rejected admission + final fourth + // accepted snapshot: all five owners are reclaimed (no leak/double free). + assert(destroyed.load(std::memory_order_relaxed)==5); // Runtime contract for the exact RT graph publication helper. struct FakeGraph { int id; }; FakeGraph old{1}, next{2}, third{3}; diff --git a/tests/realtime_ten_channel_controls_test.cpp b/tests/realtime_ten_channel_controls_test.cpp index 63d4fb1b8..0100c1b61 100644 --- a/tests/realtime_ten_channel_controls_test.cpp +++ b/tests/realtime_ten_channel_controls_test.cpp @@ -98,8 +98,11 @@ int main() { { auto lease=publisher.acquire(); assert(lease.get(4)&&lease.get(4)->prepared->identity==42); - assert(near(lease.get(4)->prepared->params.at(3).left.load(),.4f)); // stereo pan +20% reduces LEFT - assert(near(lease.get(4)->prepared->params.at(3).right.load(),.5f)); + // Read the complete accepted M4 GUI control once. Never recover + // independent left/right atomics (which can tear during pan drags). + const auto state=lease.get(4)->prepared->params.read(3); + assert(near(state.left,.4f)); // stereo pan +20% reduces LEFT + assert(near(state.right,.5f) && !state.mute && !state.solo); } publisher.unpublish(); assert(!publisher.updateActiveControl(4,1,update));