From c433830b63d7c48e6803424a6f071fc91962744a Mon Sep 17 00:00:00 2001 From: masarray Date: Wed, 11 Nov 2026 03:00:12 +0700 Subject: [PATCH 1/2] Consolidate logical mixer transactions and restore accepted WIRE impact --- CMakeLists.txt | 1 + .../FEATURE_EXTENSION_PLAYBOOK.md | 2 +- docs/architecture/README.md | 17 +- integration/ApprovedNativeV8Projection.h | 9 + scripts/build_approved_native_gui.py | 2 +- src/ApprovedNativeV8Projection.h | 177 +---------- src/ConsoleLiveBridgeV6.h | 2 +- src/LiveAudioEngine.h | 159 +--------- src/Main.cpp | 290 +++++------------- src/NativeBuiltInFx.h | 69 +++++ src/NativeLogicalMixerControl.h | 200 ++++++++++++ src/NativeMixerSessionFxRestore.h | 93 ++---- src/NativeMixerSessionSaveWorker.h | 30 +- tests/approved_native_m2_contract.test.cjs | 10 +- .../approved_native_offline_logical_smoke.py | 6 + tests/approved_native_v8_projection_test.cpp | 10 + tests/approved_native_wire_gain_smoke.py | 95 +++++- tests/mixer_io_operator_contract_test.mjs | 12 +- tests/native_mixer_session_store_test.cpp | 178 ++++++++++- web/approved-native-bridge.js | 34 +- web/approved-native-contract.js | 3 +- 21 files changed, 755 insertions(+), 644 deletions(-) create mode 100644 src/NativeBuiltInFx.h create mode 100644 src/NativeLogicalMixerControl.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 7d826bbb0..0b77c943f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -425,6 +425,7 @@ if(BUILD_TESTING) target_link_libraries(ARMixDurableMixerSessionTests PRIVATE juce::juce_audio_devices juce::juce_audio_processors juce::juce_cryptography juce::juce_recommended_config_flags) target_compile_features(ARMixDurableMixerSessionTests PRIVATE cxx_std_20) + target_compile_definitions(ARMixDurableMixerSessionTests PRIVATE JUCE_MODAL_LOOPS_PERMITTED=1) add_test(NAME P0DynamicMixerSessionDocumentAndCrashSafeRecovery COMMAND ARMixDurableMixerSessionTests) # Presentation-only native identity; no audio-thread access. juce_add_console_app(ARMixChannelAppearanceTests PRODUCT_NAME "ArSonMix Channel Appearance Tests") diff --git a/docs/architecture/FEATURE_EXTENSION_PLAYBOOK.md b/docs/architecture/FEATURE_EXTENSION_PLAYBOOK.md index a0f793b63..9956f8346 100644 --- a/docs/architecture/FEATURE_EXTENSION_PLAYBOOK.md +++ b/docs/architecture/FEATURE_EXTENSION_PLAYBOOK.md @@ -28,7 +28,7 @@ Status: WORKING PLAYBOOK, v1 2026-11-11. Root [AGENTS.md](../../AGENTS.md) and [ ## Recipe A — new built-in FX -Define catalog identity and stable insert/slot semantics once. Implement DSP as its own processor with deterministic prepare, bounded process, state serialization and bypass/latency reporting. Hook into the existing Factory/FX host registration; preserve the same editor/ACK readback and rack bypass mechanics as EQ/Compressor/Harmonice/Vocal Throw. Channel/BUS routing sees only generic FX lease, not the plugin brand. Verify zero/known latency/PDC, offline state, inserted audio, bypass, reorder/move and device restart. Keep plugin-specific UI ONLY in its editor component, not device setup. +Define catalog identity and stable insert/slot semantics once. Implement DSP as its own processor with deterministic prepare, bounded process, state serialization and bypass/latency reporting. Register compiled processors in `src/NativeBuiltInFx.h` for the generic live insert, offline prepare, restore and native picker. Preserve the same editor/ACK readback and rack bypass mechanics as EQ/Compressor/Harmonice/Vocal Throw. Channel/BUS routing sees only generic FX lease, not the plugin brand. Verify zero/known latency/PDC, offline state, inserted audio, bypass, reorder/move and device restart. Keep plugin-specific UI ONLY in its editor component, not device setup. **Design signal:** needing to modify a large per-plugin switch in Main, engine callback and browser bridge for every new audio processor indicates incomplete M4 host-seam consolidation. Solve shared host responsibility once and remove old branch at the same time. Do not add a new wrapper if only one plugin needs a unique capability. diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 33cbadafc..5c486021d 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -14,6 +14,7 @@ The current path to reason about every feature is: Assembled /preview/ DOM (presentation only) -> web/approved-native-bridge.js + web/approved-native-contract.js -> Native JUCE command transport in src/Main.cpp (MESSAGE/CONTROL thread) + -> src/NativeLogicalMixerControl.h for unbound edits and readback -> accepted logical MixerSessionDocument / ChannelId + EdgeId model -> validated mixer graph & FX lease preparation (CONTROL, not callback) -> engine/core/DynamicNativeSessionPublisher.h + realtime publication @@ -29,26 +30,32 @@ Assembled /preview/ DOM (presentation only) | Concern | Current primary files | Correct responsibility / future direction | | --- | --- | --- | | Application composition / bridge transport | src/Main.cpp; src/ApprovedConsoleNativeTransportV6.h | JUCE app lifecycle, WebView wiring, dispatch only; move domain-heavy control use-cases behind narrow services incrementally | -| Logical mixer & accepted session | src/NativeLogicalMixerWorkspace.h; src/NativeMixerSessionDocument.h; engine/core/DeviceIndependentMixerSession.h; engine/core/DynamicChannelRoster.h | Stable ChannelId/EdgeId, control-authoritative edits, revision guard, logical-only semantics | +| Logical mixer & accepted session | src/NativeLogicalMixerControl.h; src/NativeLogicalMixerWorkspace.h; src/NativeMixerSessionDocument.h; engine/core/DeviceIndependentMixerSession.h; engine/core/DynamicChannelRoster.h | One accepted workspace. The control service validates requests, stages edits, commits through the shared save worker and returns correlated ACKs. The workspace owns stable IDs and logical readback. | | Session persistence | src/NativeMixerSessionStore.h; src/NativeMixerSessionSaveWorker.h; src/NativeMixerSessionFxRestore.h | .smix durable state, rollback, vendor-state retention and explicit schema migration | | Native graph publisher & PCM | engine/core/DynamicNativeSessionPublisher.h; engine/core/RealtimeRoutePublisher.h; engine/core/DynamicPreparedMixerBlock.h | Validated immutable prepared graph, atomic publication, safe retirement, callback render state | | Audio device policy | src/LiveAudioEngine.h; engine/device/**; src/Main.cpp currently applies device | Verified driver/pins, epochs, reopen/rebind, explicit physical output safety; independent from logical session document | | Production audio compatibility | src/LiveDryRoutingLab.h; engine/core/UnifiedLegacyProductionAdmission.h | Retain only proven required M4/FAT migration semantics; never create another render authority | -| Built-in DSP and VST lifecycle | engine/builtin_fx/**; src/FactoryFxRegistry.h; src/PluginCatalog.h; engine/core/DynamicChannelFxLeaseBank.h; src/LiveAudioEngine.h | Per-processor DSP; common host lifecycle, source state, bypass, latency, editor lease and host registration | +| Built-in DSP and VST lifecycle | engine/builtin_fx/**; src/NativeBuiltInFx.h; src/FactoryFxRegistry.h; src/PluginCatalog.h; engine/core/DynamicChannelFxLeaseBank.h; src/LiveAudioEngine.h | Per-processor DSP; one built-in registration for live insert, offline prepare, restore and native picker. Specialized editors and vendor lease remain with their existing owners. | | Player | engine/player/**; src/Main.cpp dispatch | Worker decode / buffered PCM, one native graph virtual input, no independent hardware output callback | -| Native status projection | integration/ApprovedNativeRuntimeSnapshot.h; integration/ApprovedNativeV8Projection.h; src/ApprovedNativeV8Projection.h | Installed / retained / logical-only readback with one semantic contract and no forged output/PCM authority | +| Native status projection | integration/ApprovedNativeRuntimeSnapshot.h; integration/ApprovedNativeV8Projection.h; src/NativeLogicalMixerControl.h | Canonical installed and retained projection, with a forwarding include for old clients. Logical-only readback is separate and cannot admit PCM. | | GUI state, WIRE, device setup | web/approved-native-bridge.js; web/approved-native-contract.js; web/monitor.js; web/mixer-io.js; site/preview-v2/ (internal build input) | Render accepted native states only; one assembled/public/native /preview/; no competing DOM model or JS PCM | | UI build & publishing | scripts/build_pages.py; scripts/build_approved_native_gui.py; site/preview-buttons/ (approved PNG overlay source) | Deterministic single assembled renderer and native bundle provenance, not a second public GUI | | Tests & CI | tests/**; CMakeLists.txt; .github/workflows/{ui-smoke,p1-windows,chat-ci-milestone}.yml | Cheap relevant checks every PR update, deliberate exact-SHA UI or native/FAT milestone; physical FAT separate | +## M1 control events + +- `arMixLogicalIntent` enters the logical control service. It validates the request ID, workspace token and revision, then commits the candidate document and referenced FX state through `NativeMixerSessionSaveWorker`. An `arMixLogicalAck` reports that commit's revision. A later `arMixConsoleSnapshot.logicalMixer` provides independent readback with `LOGICAL_ONLY` authority. +- `arMixConsoleIntent` retains the admitted native control path. The approved bridge waits for `arMixConsoleAck` and matching accepted readback before committing the visible control state. Retained graph readback carries no installed callback authority. A verified socket connection or retarget uses the existing renderer's gravity and impact animation after the accepted graph is drawn. +- `arMixCatalog` carries registered built-in picker metadata alongside verified external catalog entries. One registration in `NativeBuiltInFx.h` supplies the control-side prepare function and limits for a generic built-in insert. An effect with its own editor supplies that editor separately. + ## Verified audit hotspots at main 99f580d76bf20ea994d54f8916098c680897f41d -- src/Main.cpp: 6,499 lines. ConsoleWindow currently owns logical edits, native ACK/status, device selection/apply, built-in FX handlers, plugin editors, Player and UI responsibilities. +- src/Main.cpp: 6,499 lines. Before M1, ConsoleWindow owned logical edits, native ACK/status, device selection/apply, built-in FX handlers, plugin editors, Player and UI responsibilities. - src/LiveAudioEngine.h: 3,564 lines. The single callback shares a class with device lifecycle, legacy routing control, graph/plugin lifecycle, and monitoring policy. - src/LiveDryRoutingLab.h: 3,261 lines. Production ChannelId paths coexist with legacy M4/Lab names/guards. - web/approved-native-bridge.js: 3,646 lines. Many per-domain event/ACK/DOM pathways in one adapter. - web/monitor.js: 2,118 lines; do NOT assume it is entirely in the currently assembled native GUI without checking the build. -- The two ApprovedNativeV8Projection.h headers define identical helper names and different public projection behavior. integration/ApprovedNativeRuntimeSnapshot.h uses the integration version for installed/retained paths; src/ConsoleLiveBridgeV6.h includes the src version. Never delete either without proving all callers and tests. +- Before M1, two ApprovedNativeV8Projection.h headers defined overlapping projections. The canonical integration header now serves both callers, and the src header forwards to it. - tests/ contains large routing, device, source/session and FX test suites. This is a major asset. Some source-text contract tests intentionally assert exact code strings; refactoring may legitimately need to update these *only when behavior-equivalent tests also exist*. - docs/ contains 238 direct entries. The 2026-11-07 Device-Independent ADR says "NOT YET IMPLEMENTED", while merged PR #513 implements *logical-only Milestone A*. This is partially stale wording, not permission to claim hardware binding works. - web/styles.css is dominated in bytes by an embedded base64 font; file size is NOT a maintainability score by itself. diff --git a/integration/ApprovedNativeV8Projection.h b/integration/ApprovedNativeV8Projection.h index 8319b7759..d337d5551 100644 --- a/integration/ApprovedNativeV8Projection.h +++ b/integration/ApprovedNativeV8Projection.h @@ -192,4 +192,13 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, return installedChannelIdCallbackAdmitted && projectNativeGraph(snapshot,bus,NativeGraphProjection::installed); } +// Legacy callers supplied a bus from the installed producer, which exposes +// its WIRE operation. The retained producer supplies an empty operation list. +// New callers must pass admission explicitly from the owning engine status. +inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus) { + const auto supported=bus.getProperty("supportedOps",{}); + const auto* ops=supported.getArray(); + return projectApprovedNativeV8(snapshot,bus, + ops && ops->contains(juce::var("NATIVE_APPLY_WIRE_TRANSACTION"))); +} } // namespace armix::console diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 5dac25f24..9fe40a1ba 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -242,7 +242,7 @@ def accepted_pages_html() -> str: " },\n" " closeNativePicker(){setFastPicker(false);},\n" " colors:COLORS,channelIcons:CHANNEL_ICONS,wireGraph:ArSonWireGraph,\n" - " allocateWireId(){return nextWireId++;},\n" + " allocateWireId(){return nextWireId++;},kickWireSpring,\n" " installGraph(channels,main,edges){\n" " tracks=channels;master=main;wireEdges=edges;\n" " wireWsHistory=[];selectedWireEdgeId=null;\n" diff --git a/src/ApprovedNativeV8Projection.h b/src/ApprovedNativeV8Projection.h index 792d5e291..783d2737f 100644 --- a/src/ApprovedNativeV8Projection.h +++ b/src/ApprovedNativeV8Projection.h @@ -1,178 +1,5 @@ // 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()){ - // Catalog identity selects the vendor binary; instance identity - // addresses the live DSP processor and per-slot bypass/editor. - // They must NEVER be compared as if they were interchangeable. - const auto token=item.getProperty("instanceId",{}),label=item.getProperty("name",{}); - const auto catalog=item.getProperty("id",{}); - const auto bypass=item.getProperty("bypassed",{}); - if(!token.isString()||token.toString().isEmpty()|| - !catalog.isString()||catalog.toString().isEmpty()|| - catalog.toString().getNumBytesAsUTF8()>256|| - !label.isString()||!bypass.isBool())return false; - auto insert=std::make_unique(); - insert->setProperty("id",token);insert->setProperty("catalogId",catalog); - insert->setProperty("name",label); - insert->setProperty("bypassed",bypass); - const auto latency=item.getProperty("latencySamples",{}); - if(latency.isInt())insert->setProperty("latencySamples",latency); - const auto changed=item.getProperty("latencyChanged",{}); - if(changed.isBool())insert->setProperty("latencyChanged",changed); - fx.add(juce::var(insert.release())); - } - ch->setProperty("inserts",juce::var(fx)); - const auto rackBypassed=row.getProperty("fxRackBypassed",{}); - if(!rackBypassed.isVoid()) { - if(!rackBypassed.isBool())return false; - ch->setProperty("fxRackBypassed",rackBypassed); - } - ch->setProperty("sends",juce::var(juce::Array{})); - { // INPUT channels can receive WIRE PCM as well as physical capture. - 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); - const auto latency=bus.getProperty("latencySamples",{}); - if(latency.isInt())g->setProperty("latencySamples",latency); - 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"); - const auto actual=bus.getProperty("supportedOps",{}); - if(const auto* list=actual.getArray()) - if(list->contains(juce::var("NATIVE_SET_WIRE_GAIN")))ops.add("SET_WIRE_GAIN"); - 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 +// Compatibility include for native console clients. The contract is owned by integration. +#include "../integration/ApprovedNativeV8Projection.h" diff --git a/src/ConsoleLiveBridgeV6.h b/src/ConsoleLiveBridgeV6.h index 8db86ac42..996a4eabe 100644 --- a/src/ConsoleLiveBridgeV6.h +++ b/src/ConsoleLiveBridgeV6.h @@ -210,7 +210,7 @@ class LiveConsoleBridgeV6 final { "NATIVE_APPLY_WIRE_TRANSACTION"))) && decodeDecimal(rev,graphId) && graphId && decodeDecimal(roster,rosterId) && rosterId) - (void)projectApprovedNativeV8(actual,bus); + (void)projectApprovedNativeV8(actual,bus,native); // Full product-LIVE remains gated on VST3/Show/monitor // parity and measured hardware FAT (#15). } diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 70b417a45..006d75a64 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -2012,11 +2012,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Native built-in EQ travels through EXACTLY the same ordered FxInstance // lease, ChannelId graph revision, bypass envelope, and PDC as VST3. // It is not the legacy fixed pre-VST EQ bank. - LiveDryRoutingLab::NativeBusResult installNativeBuiltInEq( + LiveDryRoutingLab::NativeBusResult installNativeBuiltInFx( + const armix::builtin_fx::NativeBuiltInFx& fx, std::uint64_t ep,std::uint64_t pcmRevision, std::uint64_t rosterRevision,armix::mixer::ChannelId id) { LiveDryRoutingLab::NativeBusResult fail{}; - fail.error="NATIVE_EQ_HOST_UNAVAILABLE"; + fail.error=fx.hostUnavailable; auto* device=deviceManager_.getCurrentAudioDevice(); if(independent_.active()||!attached_||!device|| !directFence_.permitted()||secondaryOutput_.armed()|| @@ -2025,159 +2026,27 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback diagnosticRoute_.load(std::memory_order_acquire)!= armix::diagnostics::Route::normal)return fail; if(ep!=dryRoutingLab_.epoch()){ - fail.error="NATIVE_EQ_DEVICE_CHANGED";return fail; + fail.error=fx.deviceChanged;return fail; } const auto rate=device->getCurrentSampleRate(); const int frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); - if(!(rate>=8000. && rate<=384000.)|| + if(!(rate>=fx.minimumLiveRate && rate<=fx.maximumLiveRate)|| frames>LiveDryRoutingLab::Block::hardFrameLimit) { - fail.error="NATIVE_EQ_UNSUPPORTED_AUDIO_FORMAT";return fail; + fail.error=fx.unsupportedFormat;return fail; } try { - auto processor=std::make_unique(); - processor->prepareToPlay(rate,frames); - if(!processor->isReady()){ - fail.error="NATIVE_EQ_PREPARE_REJECTED";return fail; - } - auto lease=std::make_shared< - armix::mixer::LiveChannelFxGraph::FxInstance>( - std::move(processor), - juce::String(armix::builtin_fx::ChannelEqProcessor::catalogIdentity), - "Parametric EQ",LiveDryRoutingLab::Block::hardFrameLimit); - return dryRoutingLab_.attachNativeInsert(ep,pcmRevision, - rosterRevision,id, - armix::builtin_fx::ChannelEqProcessor::catalogIdentity, - std::move(lease),true); - } catch(...) { - fail.error="NATIVE_EQ_PREPARE_EXCEPTION";return fail; - } - } - - // Compressor is a first-class ordered ChannelId FX node, exactly like EQ. - // No external VST3, lookahead latency or separate realtime renderer. - LiveDryRoutingLab::NativeBusResult installNativeBuiltInCompressor( - std::uint64_t ep,std::uint64_t pcmRevision, - std::uint64_t rosterRevision,armix::mixer::ChannelId id) { - LiveDryRoutingLab::NativeBusResult fail{}; - fail.error="NATIVE_COMP_HOST_UNAVAILABLE"; - auto* device=deviceManager_.getCurrentAudioDevice(); - if(independent_.active()||!attached_||!device|| - !directFence_.permitted()||secondaryOutput_.armed()|| - 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!=dryRoutingLab_.epoch()){ - fail.error="NATIVE_COMP_DEVICE_CHANGED";return fail; - } - const auto rate=device->getCurrentSampleRate(); - const int frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); - if(!(rate>=8000.&&rate<=384000.)|| - frames>LiveDryRoutingLab::Block::hardFrameLimit) { - fail.error="NATIVE_COMP_UNSUPPORTED_AUDIO_FORMAT";return fail; - } - try { - auto processor=std::make_unique(); - processor->prepareToPlay(rate,frames); - if(!processor->isReady()){ - fail.error="NATIVE_COMP_PREPARE_REJECTED";return fail; - } - auto lease=std::make_shared< - armix::mixer::LiveChannelFxGraph::FxInstance>( - std::move(processor), - juce::String(armix::builtin_fx::ChannelCompressorProcessor::catalogIdentity), - "Compressor",LiveDryRoutingLab::Block::hardFrameLimit); - return dryRoutingLab_.attachNativeInsert(ep,pcmRevision, - rosterRevision,id, - armix::builtin_fx::ChannelCompressorProcessor::catalogIdentity, - std::move(lease),true); - } catch(...) { - fail.error="NATIVE_COMP_PREPARE_EXCEPTION";return fail; - } - } - - // One ChannelId native insert. No private callback, engine or pre-VST bank. - LiveDryRoutingLab::NativeBusResult installNativeBuiltInHarmony( - std::uint64_t ep,std::uint64_t pcmRevision, - std::uint64_t rosterRevision,armix::mixer::ChannelId id) { - LiveDryRoutingLab::NativeBusResult fail{}; - fail.error="NATIVE_HARMONY_HOST_UNAVAILABLE"; - auto* device=deviceManager_.getCurrentAudioDevice(); - if(independent_.active()||!attached_||!device|| - !directFence_.permitted()||secondaryOutput_.armed()|| - 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!=dryRoutingLab_.epoch()) { - fail.error="NATIVE_HARMONY_DEVICE_CHANGED";return fail; - } - const auto rate=device->getCurrentSampleRate(); - const int frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); - if(!(rate>=32000.&&rate<=192000.)|| - frames>LiveDryRoutingLab::Block::hardFrameLimit) { - fail.error="NATIVE_HARMONY_UNSUPPORTED_AUDIO_FORMAT";return fail; - } - try { - auto processor=std::make_unique(); - processor->prepareToPlay(rate,frames); - if(!processor->isReady()|| + auto processor=fx.prepare(rate,frames,nullptr,0); + if(!processor || processor->getLatencySamples()>armix::dsp::StereoLatencyDelay::maximumSamples) { - fail.error="NATIVE_HARMONY_PREPARE_OR_PDC_REJECTED";return fail; + fail.error=fx.prepareRejected;return fail; } auto lease=std::make_shared( - std::move(processor), - juce::String(armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity), - "Harmonice",LiveDryRoutingLab::Block::hardFrameLimit); - return dryRoutingLab_.attachNativeInsert(ep,pcmRevision, - rosterRevision,id, - armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity, - std::move(lease),true); - }catch(...) { - fail.error="NATIVE_HARMONY_PREPARE_EXCEPTION";return fail; - } - } - - // ArSon Vocal Throw: single native PCM graph, same insert leases, bypass, - // ChannelId topology and dry monitoring as EQ/Compressor. - LiveDryRoutingLab::NativeBusResult installNativeBuiltInVocalThrow( - std::uint64_t ep,std::uint64_t pcmRevision, - std::uint64_t rosterRevision,armix::mixer::ChannelId id) { - LiveDryRoutingLab::NativeBusResult fail{}; - fail.error="NATIVE_THROW_HOST_UNAVAILABLE"; - auto* device=deviceManager_.getCurrentAudioDevice(); - if(independent_.active()||!attached_||!device|| - !directFence_.permitted()||secondaryOutput_.armed()|| - 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!=dryRoutingLab_.epoch()){ - fail.error="NATIVE_THROW_DEVICE_CHANGED";return fail; - } - const auto rate=device->getCurrentSampleRate(); - const int frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); - if(!(rate>=8000.&&rate<=192000.)|| - frames>LiveDryRoutingLab::Block::hardFrameLimit) { - fail.error="NATIVE_THROW_UNSUPPORTED_AUDIO_FORMAT";return fail; - } - try { - auto processor=std::make_unique(); - processor->prepareToPlay(rate,frames); - if(!processor->isReady()){ - fail.error="NATIVE_THROW_PREPARE_REJECTED";return fail; - } - auto lease=std::make_shared< - armix::mixer::LiveChannelFxGraph::FxInstance>( - std::move(processor), - juce::String(armix::builtin_fx::VocalThrowProcessor::catalogIdentity), - "ArSon Vocal Throw",LiveDryRoutingLab::Block::hardFrameLimit); - return dryRoutingLab_.attachNativeInsert(ep,pcmRevision, - rosterRevision,id, - armix::builtin_fx::VocalThrowProcessor::catalogIdentity, - std::move(lease),true); + std::move(processor),juce::String(fx.id),fx.name, + LiveDryRoutingLab::Block::hardFrameLimit); + return dryRoutingLab_.attachNativeInsert(ep,pcmRevision,rosterRevision,id, + fx.id,std::move(lease),true); } catch(...) { - fail.error="NATIVE_THROW_PREPARE_EXCEPTION";return fail; + fail.error=fx.prepareException;return fail; } } diff --git a/src/Main.cpp b/src/Main.cpp index 02aa30309..8c24164bf 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -37,7 +37,7 @@ #include "NativeShowSaveWorker.h" #include "NativeChannelAppearanceStore.h" #include "NativeMixerSessionSaveWorker.h" -#include "NativeLogicalMixerWorkspace.h" +#include "NativeLogicalMixerControl.h" #include #include #include @@ -365,7 +365,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr logicalVendorEditor_.reset(); const auto lab=engine_.status().getProperty("dryRoutingLab",{}); if(static_cast(lab.getProperty("nativeChannelIdPcmActive",false)) || - logicalWorkspaceLoaded_) { + logicalMixer_.loaded()) { const auto error=saveMixerSession(resumeMain); if(error.isNotEmpty()) diagnostics_.record("DYNAMIC_MIXER_EXIT_SAVE_REJECTED",error); @@ -396,7 +396,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr armix::storage::StudioBackup::Worker studioBackupWorker_; armix::shows::NativeShowSaveWorker nativeShowWorker_; armix::session::NativeMixerSessionSaveWorker mixerSessionWorker_; - armix::session::NativeLogicalMixerWorkspace logicalWorkspace_; + armix::session::NativeLogicalMixerControl logicalMixer_{ + settingsDirectory(),mixerSessionWorker_,[this](const juce::String& id) { + mixerSessionId_=id; + lastMixerSessionFingerprint_.clear(); + mixerSessionRecoveryPending_=true; + mixerSessionStatus_="LOGICAL_SESSION_SAVED_UNBOUND"; + mixerSessionError_.clear(); + }}; struct LogicalVendorEditor { armix::session::StoredInsert insert; juce::String workspaceToken; @@ -405,8 +412,6 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr }; std::optional logicalVendorEditor_; juce::String lastLogicalFxRequest_,lastLogicalFxInstance_,lastLogicalFxRevision_; - bool logicalWorkspaceLoaded_=false; - bool logicalWorkspaceReadOnly_=false; // damaged HEAD never overwritten juce::String mixerSessionId_,mixerSessionStatus_="NO_SAVED_SESSION"; juce::String mixerSessionError_,lastMixerSessionFingerprint_; bool mixerSessionStartupInspected_=false; @@ -823,8 +828,19 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void emitCatalog() { - if (browser_.loaded) - browser_.emitEventIfBrowserIsVisible ("arMixCatalog", catalog_.snapshot()); + if(!browser_.loaded)return; + auto catalog=catalog_.snapshot(); + juce::Array builtIns; + for(const auto& fx:armix::builtin_fx::nativeBuiltInFx) { + auto entry=std::make_unique(); + entry->setProperty("id",fx.id); + entry->setProperty("name",fx.name); + entry->setProperty("category",fx.category); + entry->setProperty("showInPicker",fx.showInPicker); + builtIns.add(juce::var(entry.release())); + } + catalog.getDynamicObject()->setProperty("builtIns",juce::var(builtIns)); + browser_.emitEventIfBrowserIsVisible("arMixCatalog",catalog); } // Every plugin insert request gets a structured result. A toast behind @@ -1049,48 +1065,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr nativeOrbitInstanceId_.clear();nativeOrbitEpoch_=0; } - // Persistent logical ChannelId state is usable even with NO driver. - // Do not instantiate vendor FX, publish a second PCM graph or ARM output. void ensureLogicalWorkspace() { - if(logicalWorkspaceLoaded_)return; - logicalWorkspaceLoaded_=true; - armix::session::NativeMixerSessionStore store(settingsDirectory()); - if(!store.exists())return; - if(!mixerSessionStartupInspected_)mixerSessionRecoveryPending_=true; - armix::session::MixerSessionDocument doc; - std::vector states; - const auto loadError=store.load(doc,states); - if(loadError.isNotEmpty() || - !logicalWorkspace_.load(std::move(doc),std::move(states))) { - // Keep the fallback logical console visible, but NEVER replace a - // corrupt or cyclic HEAD with a freshly generated default graph. - // Explicit Open can restore a verified .smix file safely. - logicalWorkspaceReadOnly_=true; + const auto [found,error]=logicalMixer_.ensureLoaded(); + if(found && !mixerSessionStartupInspected_) mixerSessionRecoveryPending_=true; - mixerSessionStatus_="DAMAGED_SESSION"; - mixerSessionError_=loadError.isNotEmpty()?loadError: - "Saved logical mixer routing is invalid or cyclic"; - diagnostics_.record("LOGICAL_MIXER_RESTORE_REJECTED", - mixerSessionError_); - } - } - - bool saveLogicalWorkspace(std::shared_ptr candidate, - std::function completion) { - auto safe=juce::Component::SafePointer(this); - return mixerSessionWorker_.save(settingsDirectory(),candidate->document(), - candidate->states(),[safe,candidate,completion=std::move(completion)](juce::String error){ - if(safe==nullptr)return; - if(error.isEmpty()) { - safe->logicalWorkspace_=std::move(*candidate); - safe->mixerSessionId_=safe->logicalWorkspace_.document().id; - safe->lastMixerSessionFingerprint_.clear(); - safe->mixerSessionRecoveryPending_=true; - safe->mixerSessionStatus_="LOGICAL_SESSION_SAVED_UNBOUND"; - safe->mixerSessionError_.clear(); - } - completion(std::move(error)); - }); + if(error.isEmpty())return; + mixerSessionRecoveryPending_=true; + mixerSessionStatus_="DAMAGED_SESSION"; + mixerSessionError_=error; + diagnostics_.record("LOGICAL_MIXER_RESTORE_REJECTED",error); } juce::String prepareLogicalFx(const armix::session::NativeLogicalMixerWorkspace& workspace, @@ -1103,10 +1086,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr insert.channel=channel; insert.slot=slot; insert.catalogId=juce::String(row->insertCatalogIds[slot]); - const bool builtin=insert.catalogId==armix::builtin_fx::ChannelEqProcessor::catalogIdentity || - insert.catalogId==armix::builtin_fx::ChannelCompressorProcessor::catalogIdentity || - insert.catalogId==armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity || - insert.catalogId==armix::builtin_fx::VocalThrowProcessor::catalogIdentity; + const bool builtin=armix::builtin_fx::findNativeBuiltInFx(insert.catalogId)!=nullptr; if(!builtin) { const auto* registered=catalog_.find(insert.catalogId); if(!registered || (saved && (saved->uid!=registered->uid || saved->path!=registered->path))) @@ -1132,20 +1112,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } bool logicalFxTarget(const juce::var& request,std::uint64_t& channel,std::size_t& slot) { - const auto rawSlot=request.getProperty("slot",{}); - const auto index=static_cast(rawSlot); - std::uint64_t revision=0; - if(!rawSlot.isInt() || index<0 || index>=LiveDryRoutingLab::maxFxPerLane || - request.getProperty("deviceEpoch",{}).toString()!="0" || - request.getProperty("workspaceToken","").toString()!=logicalWorkspace_.workspaceToken() || - !armix::session::parseDecimal(request.getProperty("graphRevision",{}),revision) || - revision!=logicalWorkspace_.revision() || - !armix::session::parseDecimal(request.getProperty("channelId",{}),channel) || - !approvedNativeSnapshot().getProperty("logicalMixer",{}).isObject()) - return false; - slot=static_cast(index); - return request.getProperty("instanceId","").toString()== - logicalWorkspace_.fxToken({channel},slot); + return approvedNativeSnapshot().getProperty("logicalMixer",{}).isObject() && + logicalMixer_.matchesFxTarget(request,channel,slot); } std::unique_ptr openLogicalBuiltinFx(const juce::var& request, @@ -1154,15 +1122,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr std::size_t slot=0; std::unique_ptr processor; if(!logicalFxTarget(request,channel,slot))return {}; - const auto* row=logicalWorkspace_.document().roster.find({channel}); + const auto* row=logicalMixer_.workspace().document().roster.find({channel}); if(row && slotinsertCatalogIds.size() && row->insertCatalogIds[slot]==catalogId && - prepareLogicalFx(logicalWorkspace_,{channel},slot,insert,processor).isEmpty()) + prepareLogicalFx(logicalMixer_.workspace(),{channel},slot,insert,processor).isEmpty()) return processor; return {}; } void openLogicalVendorEditor(const juce::var& request) { - if(logicalVendorEditor_ || mixerSessionWorker_.busy() || logicalWorkspaceReadOnly_) { + if(logicalVendorEditor_ || mixerSessionWorker_.busy() || logicalMixer_.readOnly()) { emitNotice("Close the current FX editor or wait for the mixer to finish saving",true); return; } @@ -1173,13 +1141,13 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return; } LogicalVendorEditor prepared; - auto error=prepareLogicalFx(logicalWorkspace_,{channel},slot,prepared.insert,prepared.processor); + auto error=prepareLogicalFx(logicalMixer_.workspace(),{channel},slot,prepared.insert,prepared.processor); if(error.isEmpty()) { try { if(auto* editor=prepared.processor->createEditorIfNeeded()) { prepared.window=std::make_unique( prepared.processor->getName(),editor); - prepared.workspaceToken=logicalWorkspace_.workspaceToken(); + prepared.workspaceToken=logicalMixer_.workspace().workspaceToken(); logicalVendorEditor_=std::move(prepared); return; } @@ -1195,11 +1163,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(!logicalVendorEditor_ || mixerSessionWorker_.busy() || (!shutdown && logicalVendorEditor_->window->isVisible()))return; auto& fx=*logicalVendorEditor_; - if(fx.workspaceToken!=logicalWorkspace_.workspaceToken()) { + if(fx.workspaceToken!=logicalMixer_.workspace().workspaceToken()) { logicalVendorEditor_.reset(); return; } - auto candidate=std::make_shared(logicalWorkspace_); juce::MemoryBlock bytes; try { fx.processor->getStateInformation(bytes); @@ -1208,8 +1175,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(!shutdown)fx.window->setVisible(true); return; } - if(!candidate->saveFx(fx.insert,std::move(bytes)) || - !saveLogicalWorkspace(std::move(candidate),[this](juce::String error){ + if(!logicalMixer_.saveFx(fx.insert,std::move(bytes),[this](juce::String error){ if(error.isEmpty())logicalVendorEditor_.reset(); else { emitNotice("FX settings could not be saved: "+error,true); @@ -1239,7 +1205,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr ack->setProperty("errorCode",error.isEmpty()?"NONE":error); if(safe->browser_.loaded)safe->browser_.emitEventIfBrowserIsVisible(event,juce::var(ack.release())); }; - if(!queued || logicalWorkspaceReadOnly_ || mixerSessionWorker_.busy() || + if(!queued || logicalMixer_.readOnly() || mixerSessionWorker_.busy() || audioDeviceApplyActive_ || nativeShowBusy_ || studioBackupBusy_) return reply("Offline FX settings could not be changed"); // This isolated processor has no publisher or audio consumer. Drain @@ -1248,88 +1214,28 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr typename Processor::Completion applied{}; if(!processor->pollCompletion(applied)||!applied.applied) return reply("Offline FX settings rejected"); - auto candidate=std::make_shared(logicalWorkspace_); juce::MemoryBlock bytes; processor->getStateInformation(bytes); - if(!candidate->saveFx(std::move(insert),std::move(bytes)) || - !saveLogicalWorkspace(std::move(candidate),reply)) + if(!logicalMixer_.saveFx(std::move(insert),std::move(bytes),reply)) reply("Offline FX settings could not be saved"); } - void emitLogicalMixerAck(const juce::String& id, const juce::String& error, - const juce::String& createdId={}) { - auto ack=std::make_unique(); - ack->setProperty("requestId",id); - ack->setProperty("status",error.isEmpty()?"ACCEPTED":"REJECTED"); - ack->setProperty("errorCode",error.isEmpty()?"NONE":error); - ack->setProperty("revision", - juce::String(std::to_string(logicalWorkspace_.revision()))); - if(error.isEmpty())ack->setProperty("createdId",createdId); - ack->setProperty("physicalOutputAdmitted",false); - if(browser_.loaded) - browser_.emitEventIfBrowserIsVisible("arMixLogicalAck", - juce::var(ack.release())); - } - - // Retained PCM still owns opaque processor state after unplug. Visible - // graph equality cannot transfer that ownership to a disk checkpoint. void handleLogicalMixerIntent(const juce::var& request) { - ensureLogicalWorkspace(); - const auto id=request.getProperty("requestId","").toString(); - if(!id.startsWith("logical-") || id.length()>80) - return emitLogicalMixerAck(id,"INVALID_LOGICAL_REQUEST"); - if(acceptedControlRequests_.contains(id)) - return emitLogicalMixerAck(id,"DUPLICATE_LOGICAL_REQUEST"); - if(logicalWorkspaceReadOnly_) - return emitLogicalMixerAck(id,"SAVED_MIXER_RECOVERY_REQUIRED"); - if(audioDeviceApplyActive_ || mixerSessionWorker_.busy() || - nativeShowBusy_ || studioBackupBusy_ || engine_.isGraphSwitchPending()) - return emitLogicalMixerAck(id,"LOGICAL_EDITOR_BUSY"); const auto snapshot=approvedNativeSnapshot(); - if(!snapshot.getProperty("logicalMixer",{}).isObject()) - return emitLogicalMixerAck(id,"PHYSICAL_PCM_AUTHORITY_ACTIVE"); - - const auto operation=request.getProperty("operation","").toString(); - if(logicalVendorEditor_ && - (operation=="REMOVE_FX_REFERENCE" || operation=="DELETE_CHANNEL" || operation=="REMOVE_BUS")) - return emitLogicalMixerAck(id,"Close the vendor FX editor before removing channels or inserts"); - if(operation=="ADD_FX_REFERENCE") { - const auto key=request.getProperty("payload",{}) - .getProperty("catalogId","").toString(); - const bool builtIn=key== - armix::builtin_fx::ChannelEqProcessor::catalogIdentity || - key==armix::builtin_fx::ChannelCompressorProcessor::catalogIdentity || - key==armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity || - key==armix::builtin_fx::VocalThrowProcessor::catalogIdentity; - if(!builtIn && (!catalog_.find(key) || catalog_.busy())) - return emitLogicalMixerAck(id,"UNKNOWN_OR_SCANNING_FX_CATALOG"); - } - - auto candidate=std::make_shared( - logicalWorkspace_); - const auto result=candidate->apply(request); - if(!result.accepted)return emitLogicalMixerAck(id,result.error); - if(request.getProperty("operation","").toString()=="ADD_FX_REFERENCE") { - std::uint64_t channel=0; - const auto oldChannel=armix::session::parseDecimal(request.getProperty("channelId",{}),channel)? - logicalWorkspace_.document().roster.find({channel}):nullptr; - if(!oldChannel)return emitLogicalMixerAck(id,"INVALID_LOGICAL_CHANNEL"); - armix::session::StoredInsert insert; - std::unique_ptr processor; - const auto error=prepareLogicalFx(*candidate,{channel},oldChannel->insertCatalogIds.size(), - insert,processor); - if(error.isNotEmpty())return emitLogicalMixerAck(id,error); - juce::MemoryBlock bytes; - processor->getStateInformation(bytes); - if(!candidate->saveFx(std::move(insert),std::move(bytes))) - return emitLogicalMixerAck(id,"INVALID_FX_STATE"); - } - if(!saveLogicalWorkspace(candidate,[this,id,result](juce::String error){ - emitLogicalMixerAck(id,error,result.createdId); - }))return emitLogicalMixerAck(id,"LOGICAL_EDITOR_BUSY"); - acceptedControlRequests_.add(id); - if(acceptedControlRequests_.size()>512) - acceptedControlRequests_.remove(0); + logicalMixer_.handleIntent(request,{ + audioDeviceApplyActive_ || nativeShowBusy_ || studioBackupBusy_ || + engine_.isGraphSwitchPending(), + snapshot.getProperty("logicalMixer",{}).isObject(), + logicalVendorEditor_.has_value() + },[this](const juce::String& key) { + return armix::builtin_fx::findNativeBuiltInFx(key) || + (!catalog_.busy() && catalog_.find(key)); + },[this](const auto& workspace,auto channel,auto slot,auto& insert,auto& processor) { + return prepareLogicalFx(workspace,channel,slot,insert,processor); + },[this](juce::var ack) { + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible("arMixLogicalAck",std::move(ack)); + }); } juce::var approvedNativeSnapshot (const juce::var& live) @@ -1360,15 +1266,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr !engine_.hasRetainedNativeSession()) { // Separate field: physical graph remains truthful/unadmitted. // Browsers may render this only as an explicitly unbound editor. - auto logical=logicalWorkspace_.snapshot(); - logical.getDynamicObject()->setProperty("readOnly", - logicalWorkspaceReadOnly_); - if(logicalWorkspaceReadOnly_) { - logical.getProperty("graph",{}).getProperty("capabilities",{}) - .getDynamicObject()->setProperty("supportedOps", - juce::var(juce::Array{})); - } - accepted.getDynamicObject()->setProperty("logicalMixer",logical); + accepted.getDynamicObject()->setProperty("logicalMixer",logicalMixer_.readback()); } if(auto* obj=accepted.getDynamicObject()) { obj->setProperty("channelAppearance",channelAppearance_.snapshot(accepted.getProperty("graph",{}))); @@ -1456,19 +1354,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // fallback, secondary DSP or user-visible MONITOR ritual. const auto args=command.getProperty("payload",{}); const auto catalogId=args.getProperty("catalogId","").toString(); - const bool builtInEq=catalogId== - armix::builtin_fx::ChannelEqProcessor::catalogIdentity; - const bool builtInComp=catalogId== - armix::builtin_fx::ChannelCompressorProcessor::catalogIdentity; - const bool builtInHarmony=catalogId== - armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity; - // Built-in DSP is compiled into the native host. Its admit - // path must remain usable even while third-party VST3 metadata - // discovery blocks or scans in the background. External - // plugins still require a fully verified, idle catalog. - const bool builtInThrow=catalogId== - armix::builtin_fx::VocalThrowProcessor::catalogIdentity; - const bool externalCatalog=!builtInEq&&!builtInComp&&!builtInHarmony&&!builtInThrow; + const auto* builtIn=armix::builtin_fx::findNativeBuiltInFx(catalogId); + // Native FX do not depend on third-party catalog scans. + const bool externalCatalog=builtIn==nullptr; const auto* plugin=externalCatalog?catalog_.find(catalogId):nullptr; std::uint64_t ep=0,rev=0,roster=0,target=0; if((externalCatalog&&(!plugin||catalog_.busy()))||nativeShowBusy_|| @@ -1484,18 +1372,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr command.getProperty("targetChannelId",{}),target)) { nativeError="NATIVE_VST3_INVALID_SESSION_ID"; } else { - const auto result=builtInEq? - engine_.installNativeBuiltInEq( - ep,rev,roster,armix::mixer::ChannelId{target}): - builtInComp? - engine_.installNativeBuiltInCompressor( - ep,rev,roster,armix::mixer::ChannelId{target}): - builtInHarmony? - engine_.installNativeBuiltInHarmony( - ep,rev,roster,armix::mixer::ChannelId{target}): - builtInThrow? - engine_.installNativeBuiltInVocalThrow( - ep,rev,roster,armix::mixer::ChannelId{target}): + const auto result=builtIn? + engine_.installNativeBuiltInFx( + *builtIn,ep,rev,roster,armix::mixer::ChannelId{target}): engine_.installNativeVst3( ep,rev,roster,armix::mixer::ChannelId{target}, plugin->path,plugin->uid,plugin->key()); @@ -2793,10 +2672,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr juce::String resolveMixerSessionCatalog(armix::session::MixerSessionDocument& doc, bool captureIdentity) { for(auto& insert:doc.inserts) { - if(insert.catalogId==armix::builtin_fx::ChannelEqProcessor::catalogIdentity || - insert.catalogId==armix::builtin_fx::ChannelCompressorProcessor::catalogIdentity || - insert.catalogId==armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity || - insert.catalogId==armix::builtin_fx::VocalThrowProcessor::catalogIdentity) { + if(armix::builtin_fx::findNativeBuiltInFx(insert.catalogId)) { if(insert.path.isNotEmpty() || insert.uid!=0) return "Saved built-in FX identity was modified"; continue; @@ -2875,9 +2751,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return error; } mixerSessionId_=doc.id; - if(usedPrevious) { - if(logicalWorkspace_.load(doc,states))logicalWorkspaceReadOnly_=false; - } + if(usedPrevious) + (void)logicalMixer_.restoreCheckpoint(doc,states); const bool firstBinding=doc.logicalOnly; if(firstBinding && !engine_.hasPristineStartupMixer()) { mixerSessionRecoveryPending_=true; @@ -2947,7 +2822,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(mixerSessionWorker_.busy()||nativeShowBusy_||studioBackupBusy_|| catalog_.busy()||engine_.isGraphSwitchPending()) return "Mixer is busy. Try again after the current operation."; - if(logicalWorkspaceReadOnly_) + if(logicalMixer_.readOnly()) return "Saved mixer recovery required before writing a new session"; const auto liveState=engine_.status(); const auto live=liveState.getProperty("dryRoutingLab",{}); @@ -2961,10 +2836,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Logical edits and Open already commit HEAD before ACK. if(automatic)return {}; auto safe=juce::Component::SafePointer(this); - if(!mixerSessionWorker_.save(settingsDirectory(),logicalWorkspace_.document(), - logicalWorkspace_.states(),[safe](juce::String error){ + if(!logicalMixer_.exportTo(exportFile,[safe](juce::String error){ if(safe!=nullptr)safe->emitMixerSessionAck("SAVE",error); - },exportFile))return "Mixer session IO worker unavailable"; + }))return "Mixer session IO worker unavailable"; return {}; } if(automatic&&mixerSessionRecoveryPending_) @@ -3052,28 +2926,16 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Open the real .smix into the same stable-ID logical // document. Never demand audio hardware or instantiate VST3 // just to inspect and edit a saved mixer. - safe->ensureLogicalWorkspace(); - const auto id=doc.id; - armix::session::NativeLogicalMixerWorkspace opened; - if(!opened.load(std::move(doc),std::move(states))) - error="Saved logical routing is invalid or cyclic"; - else { - error=armix::session::NativeMixerSessionStore( - settingsDirectory()).commit(opened.document(),opened.states()); - if(error.isEmpty()) { - safe->logicalWorkspace_=std::move(opened); - safe->logicalWorkspaceReadOnly_=false; - safe->logicalWorkspaceLoaded_=true; - safe->mixerSessionId_=id; - safe->mixerSessionRecoveryPending_=true; - safe->lastMixerSessionFingerprint_.clear(); + if(!safe->logicalMixer_.open(std::move(doc),std::move(states), + [safe,file](juce::String openError){ + if(safe==nullptr)return; + if(openError.isEmpty()) { safe->mixerSessionStatus_="LOGICAL_SESSION_OPENED_UNBOUND"; - safe->mixerSessionError_.clear(); safe->lastMixerFile_=file; - safe->emitApprovedNativeSnapshot(); } - } - safe->emitMixerSessionAck("OPEN",error); + safe->emitMixerSessionAck("OPEN",openError); + if(openError.isEmpty())safe->emitApprovedNativeSnapshot(); + }))safe->emitMixerSessionAck("OPEN","Mixer session IO worker unavailable"); return; } if(error.isEmpty())error=safe->materializeLogicalFxForBinding(doc,states); diff --git a/src/NativeBuiltInFx.h b/src/NativeBuiltInFx.h new file mode 100644 index 000000000..2509816a4 --- /dev/null +++ b/src/NativeBuiltInFx.h @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +#include "../engine/builtin_fx/ChannelEqProcessor.h" +#include "../engine/builtin_fx/ChannelCompressorProcessor.h" +#include "../engine/builtin_fx/ChannelHarmonyProcessor.h" +#include "../engine/builtin_fx/VocalThrowProcessor.h" +#include +#include + +namespace armix::builtin_fx { +// Control-side registration shared by live insert, offline edit and restore. +// The descriptor does not own a processor, callback, editor or render graph. +struct NativeBuiltInFx { + using Prepare=std::unique_ptr(*)(double,int,const void*,int); + const char* id; + const char* name; + const char* category; + bool showInPicker; + double minimumLiveRate; + double maximumLiveRate; + const char* hostUnavailable; + const char* deviceChanged; + const char* unsupportedFormat; + const char* prepareRejected; + const char* prepareException; + const char* restoreRejected; + Prepare prepare; +}; + +template +std::unique_ptr prepareNativeBuiltInFx( + double rate,int frames,const void* state,int bytes) { + auto processor=std::make_unique(); + processor->prepareToPlay(rate,frames); + if(!processor->isReady() || (state && !processor->restoreUnpublishedState(state,bytes))) + return {}; + return processor; +} + +inline constexpr std::array nativeBuiltInFx{ + NativeBuiltInFx{ChannelEqProcessor::catalogIdentity,"Parametric EQ","EQ",true,8000.,384000., + "NATIVE_EQ_HOST_UNAVAILABLE","NATIVE_EQ_DEVICE_CHANGED", + "NATIVE_EQ_UNSUPPORTED_AUDIO_FORMAT","NATIVE_EQ_PREPARE_REJECTED", + "NATIVE_EQ_PREPARE_EXCEPTION","Saved native EQ state rejected; graph unchanged", + prepareNativeBuiltInFx}, + NativeBuiltInFx{ChannelCompressorProcessor::catalogIdentity,"Compressor","Dynamics",true,8000.,384000., + "NATIVE_COMP_HOST_UNAVAILABLE","NATIVE_COMP_DEVICE_CHANGED", + "NATIVE_COMP_UNSUPPORTED_AUDIO_FORMAT","NATIVE_COMP_PREPARE_REJECTED", + "NATIVE_COMP_PREPARE_EXCEPTION","Saved native Compressor state rejected; graph unchanged", + prepareNativeBuiltInFx}, + NativeBuiltInFx{ChannelHarmonyProcessor::catalogIdentity,"Harmonice","Utility",true,32000.,192000., + "NATIVE_HARMONY_HOST_UNAVAILABLE","NATIVE_HARMONY_DEVICE_CHANGED", + "NATIVE_HARMONY_UNSUPPORTED_AUDIO_FORMAT","NATIVE_HARMONY_PREPARE_OR_PDC_REJECTED", + "NATIVE_HARMONY_PREPARE_EXCEPTION","Saved native Harmony state rejected; graph unchanged", + prepareNativeBuiltInFx}, + NativeBuiltInFx{VocalThrowProcessor::catalogIdentity,"ArSon Vocal Throw","Utility",false,8000.,192000., + "NATIVE_THROW_HOST_UNAVAILABLE","NATIVE_THROW_DEVICE_CHANGED", + "NATIVE_THROW_UNSUPPORTED_AUDIO_FORMAT","NATIVE_THROW_PREPARE_REJECTED", + "NATIVE_THROW_PREPARE_EXCEPTION","Saved native Vocal Throw state rejected; graph unchanged", + prepareNativeBuiltInFx} +}; + +inline const NativeBuiltInFx* findNativeBuiltInFx(const juce::String& id) { + for(const auto& fx:nativeBuiltInFx) + if(id==fx.id)return &fx; + return nullptr; +} +} // namespace armix::builtin_fx diff --git a/src/NativeLogicalMixerControl.h b/src/NativeLogicalMixerControl.h new file mode 100644 index 000000000..5f5d575f2 --- /dev/null +++ b/src/NativeLogicalMixerControl.h @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +#include "NativeLogicalMixerWorkspace.h" +#include "NativeMixerSessionSaveWorker.h" + +namespace armix::session { +// JUCE message thread. The accepted workspace is replaced only after the +// shared session worker has committed the complete document and FX state. +class NativeLogicalMixerControl final { +public: + using Workspace=NativeLogicalMixerWorkspace; + using Completion=NativeMixerSessionSaveWorker::Completion; + using PrepareFx=std::function&)>; + using EmitAck=std::function; + struct Availability { + bool hostBusy=false; + bool logicalAuthority=false; + bool vendorEditorOpen=false; + }; + + NativeLogicalMixerControl(juce::File studio,NativeMixerSessionSaveWorker& worker, + std::function checkpointSaved) + :studio_(std::move(studio)),worker_(worker), + checkpointSaved_(std::move(checkpointSaved)) {} + + NativeLogicalMixerControl(const NativeLogicalMixerControl&)=delete; + NativeLogicalMixerControl& operator=(const NativeLogicalMixerControl&)=delete; + + struct LoadResult { + bool found=false; + juce::String error; + }; + + LoadResult ensureLoaded() { + if(loaded_)return {}; + loaded_=true; + NativeMixerSessionStore store(studio_); + if(!store.exists())return {}; + MixerSessionDocument document; + std::vector states; + auto error=store.load(document,states); + if(error.isEmpty() && !workspace_.load(std::move(document),std::move(states))) + error="Saved logical mixer routing is invalid or cyclic"; + readOnly_=error.isNotEmpty(); + return {true,std::move(error)}; + } + + bool loaded() const noexcept {return loaded_;} + bool readOnly() const noexcept {return readOnly_;} + const Workspace& workspace() const noexcept {return workspace_;} + + bool restoreCheckpoint(MixerSessionDocument doc,std::vector states) { + if(!workspace_.load(std::move(doc),std::move(states)))return false; + loaded_=true; + readOnly_=false; + return true; + } + + bool open(MixerSessionDocument doc,std::vector states, + Completion completion) { + if(worker_.busy())return false; + auto candidate=std::make_shared(); + if(!candidate->load(std::move(doc),std::move(states))) { + completion("Saved logical routing is invalid or cyclic"); + return true; + } + return commit(std::move(candidate),std::move(completion)); + } + + bool exportTo(const juce::File& file,Completion completion) { + return !readOnly_ && worker_.save(studio_,workspace_.document(), + workspace_.states(),std::move(completion),file); + } + + bool saveFx(StoredInsert insert,juce::MemoryBlock bytes,Completion completion) { + if(readOnly_ || worker_.busy())return false; + auto candidate=std::make_shared(workspace_); + return candidate->saveFx(std::move(insert),std::move(bytes)) && + commit(std::move(candidate),std::move(completion)); + } + + // Authority is determined from the host's admitted/retained readback. + // A logical document can never itself grant physical output admission. + void handleIntent(const juce::var& request,Availability availability, + const std::function& canInsertFx, + const PrepareFx& prepareFx,const EmitAck& emit) { + const auto requestId=request.getProperty("requestId",{}).toString(); + auto reply=[this,requestId,emit](const juce::String& error, + const juce::String& createdId={}) { + auto ack=std::make_unique(); + ack->setProperty("requestId",requestId); + ack->setProperty("status",error.isEmpty()?"ACCEPTED":"REJECTED"); + ack->setProperty("errorCode",error.isEmpty()?"NONE":error); + ack->setProperty("revision",juce::String(std::to_string(workspace_.revision()))); + if(error.isEmpty())ack->setProperty("createdId",createdId); + ack->setProperty("physicalOutputAdmitted",false); + emit(juce::var(ack.release())); + }; + if(!requestId.startsWith("logical-") || requestId.length()>80) + return reply("INVALID_LOGICAL_REQUEST"); + if(requests_.contains(requestId)) + return reply("DUPLICATE_LOGICAL_REQUEST"); + if(readOnly_)return reply("SAVED_MIXER_RECOVERY_REQUIRED"); + if(availability.hostBusy || worker_.busy())return reply("LOGICAL_EDITOR_BUSY"); + if(!availability.logicalAuthority)return reply("PHYSICAL_PCM_AUTHORITY_ACTIVE"); + + const auto operation=request.getProperty("operation","").toString(); + if(availability.vendorEditorOpen && + (operation=="REMOVE_FX_REFERENCE" || operation=="DELETE_CHANNEL" || operation=="REMOVE_BUS")) + return reply("Close the vendor FX editor before removing channels or inserts"); + const bool addFx=operation=="ADD_FX_REFERENCE"; + if(addFx && !canInsertFx(request.getProperty("payload",{}) + .getProperty("catalogId","").toString())) + return reply("UNKNOWN_OR_SCANNING_FX_CATALOG"); + + auto candidate=std::make_shared(workspace_); + const auto result=candidate->apply(request); + if(!result.accepted)return reply(result.error); + if(addFx) { + std::uint64_t channel=0; + if(!parseDecimal(request.getProperty("channelId",{}),channel)) + return reply("INVALID_LOGICAL_CHANNEL"); + const auto* row=workspace_.document().roster.find({channel}); + if(!row)return reply("INVALID_LOGICAL_CHANNEL"); + StoredInsert insert; + std::unique_ptr processor; + try { + const auto error=prepareFx(*candidate,{channel},row->insertCatalogIds.size(), + insert,processor); + if(error.isNotEmpty())return reply(error); + juce::MemoryBlock bytes; + processor->getStateInformation(bytes); + if(!candidate->saveFx(std::move(insert),std::move(bytes))) + return reply("INVALID_FX_STATE"); + } catch(...) { + return reply("INVALID_FX_STATE"); + } + } + if(!commit(std::move(candidate),[reply,createdId=result.createdId](juce::String error){ + reply(error,createdId); + }))return reply("LOGICAL_EDITOR_BUSY"); + requests_.add(requestId); + if(requests_.size()>512)requests_.remove(0); + } + + juce::var readback() const { + auto logical=workspace_.snapshot(); + logical.getDynamicObject()->setProperty("readOnly",readOnly_); + if(readOnly_) { + logical.getProperty("graph",{}).getProperty("capabilities",{}) + .getDynamicObject()->setProperty("supportedOps",juce::var(juce::Array{})); + } + return logical; + } + + bool matchesFxTarget(const juce::var& request,std::uint64_t& channel,std::size_t& slot) const { + const auto rawSlot=request.getProperty("slot",{}); + const auto index=static_cast(rawSlot); + std::uint64_t revision=0; + if(!rawSlot.isInt() || index<0 || + request.getProperty("deviceEpoch",{}).toString()!="0" || + request.getProperty("workspaceToken","").toString()!=workspace_.workspaceToken() || + !parseDecimal(request.getProperty("graphRevision",{}),revision) || + revision!=workspace_.revision() || + !parseDecimal(request.getProperty("channelId",{}),channel)) + return false; + slot=static_cast(index); + const auto* row=workspace_.document().roster.find({channel}); + return row && slotinsertCatalogIds.size() && + request.getProperty("instanceId","").toString()==workspace_.fxToken({channel},slot); + } + +private: + bool commit(std::shared_ptr candidate,Completion completion) { + return worker_.save(studio_,candidate->document(),candidate->states(), + [this,lifetime=std::weak_ptr(lifetime_),candidate, + completion=std::move(completion)](juce::String error) { + if(lifetime.expired())return; + if(error.isEmpty()) { + workspace_=std::move(*candidate); + loaded_=true; + readOnly_=false; + checkpointSaved_(workspace_.document().id); + } + completion(std::move(error)); + }); + } + + const juce::File studio_; + NativeMixerSessionSaveWorker& worker_; + std::function checkpointSaved_; + Workspace workspace_; + juce::StringArray requests_; + bool loaded_=false; + bool readOnly_=false; + std::shared_ptr lifetime_=std::make_shared(0); +}; +} // namespace armix::session diff --git a/src/NativeMixerSessionFxRestore.h b/src/NativeMixerSessionFxRestore.h index 9a2e0f3fe..fe85bc31d 100644 --- a/src/NativeMixerSessionFxRestore.h +++ b/src/NativeMixerSessionFxRestore.h @@ -3,10 +3,7 @@ #include "NativeMixerSessionDocument.h" #include "VstBusLayout.h" #include "Vst3DescriptionCache.h" -#include "../engine/builtin_fx/ChannelEqProcessor.h" -#include "../engine/builtin_fx/ChannelCompressorProcessor.h" -#include "../engine/builtin_fx/ChannelHarmonyProcessor.h" -#include "../engine/builtin_fx/VocalThrowProcessor.h" +#include "NativeBuiltInFx.h" #include #include #include @@ -27,73 +24,29 @@ class NativeMixerSessionFxRestore final { const armix::shows::BinaryState* state, juce::AudioPluginFormatManager& formats,double sampleRate,int frames, std::unique_ptr& out) { - std::unique_ptr processor; - auto* format=formats.getFormat(0); - if(insert.catalogId== - armix::builtin_fx::ChannelEqProcessor::catalogIdentity) { - auto eq=std::make_unique(); - eq->prepareToPlay(sampleRate,frames); - if(!eq->isReady()|| - (state && !eq->restoreUnpublishedState( - state->bytes.getData(), - static_cast(state->bytes.getSize())))) - return "Saved native EQ state rejected; graph unchanged"; - processor=std::move(eq); - } else if(insert.catalogId== - armix::builtin_fx::ChannelCompressorProcessor::catalogIdentity) { - auto comp=std::make_unique(); - comp->prepareToPlay(sampleRate,frames); - if(!comp->isReady()|| - (state && !comp->restoreUnpublishedState( - state->bytes.getData(), - static_cast(state->bytes.getSize())))) - return "Saved native Compressor state rejected; graph unchanged"; - processor=std::move(comp); - } else if(insert.catalogId== - armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity) { - auto harmony=std::make_unique(); - harmony->prepareToPlay(sampleRate,frames); - if(!harmony->isReady()|| - (state && !harmony->restoreUnpublishedState( - state->bytes.getData(),static_cast(state->bytes.getSize())))) - return "Saved native Harmony state rejected; graph unchanged"; - processor=std::move(harmony); - } else if(insert.catalogId== - armix::builtin_fx::VocalThrowProcessor::catalogIdentity) { - auto throwFx=std::make_unique(); - throwFx->prepareToPlay(sampleRate,frames); - if(!throwFx->isReady()|| - (state && !throwFx->restoreUnpublishedState( - state->bytes.getData(), - static_cast(state->bytes.getSize())))) - return "Saved native Vocal Throw state rejected; graph unchanged"; - processor=std::move(throwFx); - } else { - if(!format|| - !format->fileMightContainThisPluginType(insert.path)) - return "Saved VST3 unavailable: "+insert.catalogId; - const auto chosen=armix::vst::DescriptionCache::resolve( - *format,insert.path,insert.uid); - if(!chosen)return "Saved VST3 identity not found: "+insert.catalogId; - juce::String pluginError; - processor=formats.createPluginInstance(*chosen,sampleRate,frames,pluginError); - if(!processor) - return "VST3 instance unavailable: "+pluginError; - const auto layout=armix::vst::prepareStereoEffectLayout(*processor); - if(layout.isNotEmpty()) - return "Saved VST3 stereo layout rejected: "+layout; - processor->prepareToPlay(sampleRate,frames); + if(const auto* builtIn=armix::builtin_fx::findNativeBuiltInFx(insert.catalogId)) { + auto processor=builtIn->prepare(sampleRate,frames, + state?state->bytes.getData():nullptr, + state?static_cast(state->bytes.getSize()):0); + // An explicitly supplied empty blob was rejected before the + // registry was introduced, even though its data pointer is null. + if(!processor || (state && state->bytes.isEmpty()))return builtIn->restoreRejected; + out=std::move(processor); + return {}; } - if(state && insert.catalogId!= - armix::builtin_fx::ChannelEqProcessor::catalogIdentity && - insert.catalogId!= - armix::builtin_fx::ChannelCompressorProcessor::catalogIdentity && - insert.catalogId!= - armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity && - insert.catalogId!= - armix::builtin_fx::VocalThrowProcessor::catalogIdentity) - processor->setStateInformation(state->bytes.getData(), - static_cast(state->bytes.getSize())); + auto* format=formats.getFormat(0); + if(!format || !format->fileMightContainThisPluginType(insert.path)) + return "Saved VST3 unavailable: "+insert.catalogId; + const auto chosen=armix::vst::DescriptionCache::resolve(*format,insert.path,insert.uid); + if(!chosen)return "Saved VST3 identity not found: "+insert.catalogId; + juce::String pluginError; + auto processor=formats.createPluginInstance(*chosen,sampleRate,frames,pluginError); + if(!processor)return "VST3 instance unavailable: "+pluginError; + const auto layout=armix::vst::prepareStereoEffectLayout(*processor); + if(layout.isNotEmpty())return "Saved VST3 stereo layout rejected: "+layout; + processor->prepareToPlay(sampleRate,frames); + if(state)processor->setStateInformation(state->bytes.getData(), + static_cast(state->bytes.getSize())); out=std::move(processor); return {}; } diff --git a/src/NativeMixerSessionSaveWorker.h b/src/NativeMixerSessionSaveWorker.h index 6586ec205..80c58bfbe 100644 --- a/src/NativeMixerSessionSaveWorker.h +++ b/src/NativeMixerSessionSaveWorker.h @@ -74,17 +74,29 @@ class NativeMixerSessionSaveWorker final : private juce::Thread { } auto alive=alive_; const auto serial=serial_; - juce::MessageManager::callAsync([this,alive,error,serial]() mutable { - if(!alive->load(std::memory_order_acquire)||serial!=serial_)return; - busy_.store(false,std::memory_order_release); - auto callback=std::move(done_); - done_={}; - auto readCallback=std::move(readDone_); - readDone_={}; - if(readCallback)readCallback(std::move(error),std::move(doc_),std::move(states_)); - else if(callback)callback(std::move(error)); + juce::MessageManager::callAsync([this,alive,error,serial] { + if(alive->load(std::memory_order_acquire))completeOnControl(error,serial); }); } + + void completeOnControl(juce::String error,unsigned serial) { + if(serial!=serial_)return; + // Open chains a file read into a durable HEAD commit on this worker. + // The message can arrive just before JUCE retires the thread handle. + if(isThreadRunning()) { + juce::Timer::callAfterDelay(1,[this,alive=alive_,error,serial] { + if(alive->load(std::memory_order_acquire))completeOnControl(error,serial); + }); + return; + } + busy_.store(false,std::memory_order_release); + auto callback=std::move(done_); + done_={}; + auto readCallback=std::move(readDone_); + readDone_={}; + if(readCallback)readCallback(std::move(error),std::move(doc_),std::move(states_)); + else if(callback)callback(std::move(error)); + } juce::File studio_,exportFile_; MixerSessionDocument doc_; std::vector states_; diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 1ce224db8..245391ffa 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -384,7 +384,7 @@ test("P0 first Add FX discovers real local VST3 lazily without an audio-thread s // The approved picker publishes real compiled-in FX independently of // external scanner state; the verified VST3 library follows those entries. assert.match(bridge,/const presentFxCatalog=\(\)=>scope\?\.setNativeCatalog\?\.\(/); - assert.ok(bridge.includes('[...nativeBuiltins,...nativeCatalog.values()]')); + assert.ok(bridge.includes('[...nativeBuiltins.filter(fx=>fx.showInPicker!==false),...nativeCatalog.values()]')); // Neither startup nor audio callback can trigger a surprise system scan. assert.doesNotMatch(bridge.slice(0,bridge.indexOf("function discoverFxOnFirstPickerOpen")), /action:"scanVst3"/); @@ -1275,16 +1275,16 @@ test("P0 native built-in FX appear before vendor scan and remain after catalog r "armix.builtin.channel-compressor.v1", "armix.builtin.arson-harmony.v1"]) assert.ok(bridge.includes('id:"'+id+'"')); - assert.ok(bridge.includes('[...nativeBuiltins,...nativeCatalog.values()]')); + assert.ok(bridge.includes('[...nativeBuiltins.filter(fx=>fx.showInPicker!==false),...nativeCatalog.values()]')); assert.ok(bridge.includes('presentFxCatalog(); // compiled native FX')); assert.ok(builder.includes("x.format==='Native'?'Native':'VST3'")); assert.ok(!bridge.includes('scope?.setNativeCatalog?.([])')); }); test("P0 built-in EQ/Compressor/Harmony load independent of slow external VST3 catalog scan",()=>{ const cpp=read("src/Main.cpp"); - const gate=cpp.slice(cpp.indexOf('const bool builtInEq=catalogId=='), - cpp.indexOf('const auto result=builtInEq?',cpp.indexOf('const bool builtInEq=catalogId=='))); - assert.ok(gate.includes('const bool externalCatalog=!builtInEq&&!builtInComp&&!builtInHarmony')); + const gate=cpp.slice(cpp.indexOf('const auto* builtIn=armix::builtin_fx::findNativeBuiltInFx(catalogId)'), + cpp.indexOf('const auto result=builtIn?')); + assert.ok(gate.includes('const bool externalCatalog=builtIn==nullptr')); assert.ok(gate.includes('externalCatalog&&(!plugin||catalog_.busy())')); assert.ok(!gate.includes('||catalog_.busy()||nativeShowBusy_'), 'third-party metadata discovery must not disable compiled-in FX'); diff --git a/tests/approved_native_offline_logical_smoke.py b/tests/approved_native_offline_logical_smoke.py index 2f73aad93..0bf4d3a2e 100644 --- a/tests/approved_native_offline_logical_smoke.py +++ b/tests/approved_native_offline_logical_smoke.py @@ -135,8 +135,14 @@ def main(): e.payload?.action==='logicalVendorFxEditor')?.payload""") assert vendor["instanceId"]=="logical-vendor" and vendor["deviceEpoch"]=="0" assert not page.locator("#fastPicker").is_visible() + emit(page, "arMixCatalog", {"items": [], "builtIns": [ + {"id": "armix.builtin.fixture.v1", "name": "Fixture processor", "category": "Utility"}, + {"id": "armix.builtin.hidden.v1", "name": "Hidden processor", "showInPicker": False}, + ]}) rack.locator('[data-action="openPlugin"][data-slot="2"]').click() assert page.locator("#fastPicker").is_visible() + assert page.locator('[data-fast-id="armix.builtin.fixture.v1"]').is_visible() + assert page.locator('[data-fast-id="armix.builtin.hidden.v1"]').count() == 0 page.locator("#fastClose").click() # The approved mixer virtualizes/banks strips. Count native-owned # model channels, not only the currently mounted DOM bank. diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index 576c4386a..c513da207 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // M3-B CONTROL-thread projection regression. No mock PCM is installed. #include "../integration/ApprovedNativeV8Projection.h" +#include "../src/ApprovedNativeV8Projection.h" #include "../integration/ApprovedNativeControlIntent.h" #include "../integration/ApprovedNativeRuntimeSnapshot.h" #include "../integration/FirstSoundSignalEvidence.h" @@ -89,6 +90,15 @@ static void nativeInsertCatalogInstanceProjectionRegression() { ->setProperty("fxRackBypassed",true); auto snapshot=canonicalSnapshot(); assert(projectApprovedNativeV8(snapshot,source,true)); + auto legacy=canonicalSnapshot(); + const auto beforeLegacy=juce::JSON::toString(legacy,true); + assert(!projectApprovedNativeV8(legacy,source)); // shape alone grants no legacy admission + assert(juce::JSON::toString(legacy,true)==beforeLegacy); + juce::Array installedOps; + installedOps.add("NATIVE_APPLY_WIRE_TRANSACTION"); + source.getDynamicObject()->setProperty("supportedOps",juce::var(installedOps)); + assert(projectApprovedNativeV8(legacy,source)); + assert(juce::JSON::toString(legacy,true)==juce::JSON::toString(snapshot,true)); const auto live=snapshot.getProperty("graph",{}) .getProperty("channels",{})[0].getProperty("inserts",{})[0]; assert(live.getProperty("id","").toString()=="vst3-instance-unique-7"); diff --git a/tests/approved_native_wire_gain_smoke.py b/tests/approved_native_wire_gain_smoke.py index 23880055c..d848aaa02 100644 --- a/tests/approved_native_wire_gain_smoke.py +++ b/tests/approved_native_wire_gain_smoke.py @@ -52,6 +52,96 @@ def ack(page, state, intent): "graphRevision": state["graph"]["revision"], "rosterRevision": state["graph"]["rosterRevision"]}) +def verify_socket_impact(page, out): + page.add_init_script("""window.__nativeListeners=new Map();window.__nativeIntents=[]; + window.__JUCE__={backend:{ + emitEvent(name,payload){if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload);}, + addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") + page.goto((out / "index.html").as_uri()) + page.wait_for_function("()=>window.__ARMIX_NATIVE_M2__?.enabled") + state = snapshot() + accepted_edge = state["graph"]["edges"].pop(1) + emit(page, "arMixConsoleSnapshot", state) + if "collapsed-send" in (page.locator(".console-body").get_attribute("class") or ""): + page.locator('.section-rail [data-section="send"]').click() + source = page.locator('#tracks .strip[data-id="1"] .wire-node-out') + receiver = page.locator('#tracks .strip[data-id="2"] .wire-node-in') + def center(jack): + box = jack.bounding_box() + assert box + return box["x"] + box["width"]/2, box["y"] + box["height"]/2 + selector = '#wireLayer path.wire-outgoing-line[data-cable-key="1-2"]' + page.evaluate("""selector=>{ + window.__wireImpact=[]; + new MutationObserver(records=>{ + for(const {target} of records){ + const d=target.getAttribute('d'); + if(target.matches(selector)&&d?.includes(' L ')&&window.__wireImpact.at(-1)!==d) + window.__wireImpact.push(d); + } + }).observe(document.getElementById('wireLayer'), + {attributes:true,attributeFilter:['d'],subtree:true}); + }""", selector) + def drag(): + x0, y0 = center(source) + x1, y1 = center(receiver) + page.mouse.move(x0, y0) + page.mouse.down() + page.mouse.move(x1, y1, steps=8) + assert "is-snap-target" in receiver.get_attribute("class") + page.mouse.up() + page.mouse.move(x1, y1+65) + + drag() + page.wait_for_function("()=>window.__nativeIntents.length===1") + intent = page.evaluate("()=>window.__nativeIntents.at(-1)") + assert intent["operation"] == "APPLY_WIRE_TRANSACTION" + rejected = {"requestId": intent["requestId"], "status": "REJECTED", + "errorCode": "TEST_REJECTION", "deviceEpoch": state["device"]["epoch"], + "graphRevision": "2", "rosterRevision": "2"} + emit(page, "arMixConsoleAck", rejected) + emit(page, "arMixConsoleSnapshot", state) + assert page.locator(selector).count() == 0 + assert page.evaluate("()=>window.__wireImpact.length") == 0 + + drag() + page.wait_for_function("()=>window.__nativeIntents.length===2") + intent = page.evaluate("()=>window.__nativeIntents.at(-1)") + change = intent["payload"]["changes"][0] + assert change["from"] == SOURCE and change["to"] == RECEIVER + after = copy.deepcopy(state) + after["graph"]["revision"] = "3" + after["mixerSession"]["routeRevision"] = "3" + if change["op"] == "ROUTE_ONLY": + after["graph"]["edges"].pop(0) + after["graph"]["channels"][0]["primaryOutId"] = RECEIVER + accepted_edge.update(primaryOutput=True, gainLinear=1) + else: + assert change["op"] == "CONNECT" + accepted_edge["gainLinear"] = change["gainLinear"] + after["graph"]["edges"].append(accepted_edge) + ack(page, after, intent) + assert page.locator(selector).count() == 0, "ACK alone drew a cable" + emit(page, "arMixConsoleSnapshot", after) + page.wait_for_function("()=>window.__wireImpact.length>=6", timeout=3500) + cable = page.locator(selector) + page.wait_for_function("selector=>document.querySelector(selector)?.getAttribute('d')?.includes(' C ')",arg=selector) + settled = cable.get_attribute("d") + # The settled cubic hangs below the jacks. The impact moves the path, + # while its endpoints stay identical through all sampled animation frames. + geometry = cable.evaluate("""path=>{ + const length=path.getTotalLength(); + return [path.getPointAtLength(0).y,path.getPointAtLength(length).y, + path.getPointAtLength(length/2).y]; + }""") + assert geometry[2] > max(geometry[:2]) + 5, geometry + frames = page.evaluate("()=>window.__wireImpact") + assert all(d.split()[:3] == settled.split()[:3] and + d.split()[-2:] == settled.split()[-2:] for d in frames) + emit(page, "arMixConsoleSnapshot", after) + assert cable.get_attribute("d") == settled, "telemetry replay retriggered impact" + + def main(): spec = importlib.util.spec_from_file_location("native_bundle", ROOT / "scripts/build_approved_native_gui.py") bundle = importlib.util.module_from_spec(spec) @@ -61,6 +151,9 @@ def main(): bundle.stage(out) with sync_playwright() as p: browser = p.chromium.launch(headless=True) + impact = browser.new_page(viewport={"width": 1366, "height": 768}) + verify_socket_impact(impact, out) + impact.close() for width, height in [(1366, 768), (1680, 900), (1920, 1080)]: page = browser.new_page(viewport={"width": width, "height": height}) errors = [] @@ -147,7 +240,7 @@ def main(): page.screenshot(path=f"native-wire-gain-{width}.png") page.close() browser.close() - print("PASS native WIRE gain: real keyboard, coalesced ACK/readback, stable DOM, INPUT OUT, 3 viewports (UI only)") + print("PASS native WIRE socket impact and gain: real drag and keyboard, coalesced ACK/readback, stable DOM, INPUT OUT, 3 viewports (UI only)") if __name__ == "__main__": diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index a8b728c60..e6601d109 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -661,13 +661,15 @@ test('ASIO restart cannot strand MAIN off after temporary graph readiness faults }); test('offline checkpoints stay protected until verified native restore',()=>{ - const edit=main.slice(main.indexOf('bool saveLogicalWorkspace('), - main.indexOf('juce::var approvedNativeSnapshot (')); - const open=main.slice(main.indexOf('armix::session::NativeLogicalMixerWorkspace opened;'), + const edit=main.slice(main.indexOf('NativeLogicalMixerControl logicalMixer_'), + main.indexOf('struct LogicalVendorEditor')); + const open=main.slice(main.indexOf('logicalMixer_.open(std::move(doc),'), main.indexOf('if(error.isEmpty())error=safe->materializeLogicalFxForBinding(doc,states);')); const save=main.slice(main.indexOf('juce::String saveMixerSession('), main.indexOf('void openMixerFile(')); - assert.match(edit,/mixerSessionRecoveryPending_=true;\s*safe->mixerSessionStatus_="LOGICAL_SESSION_SAVED_UNBOUND"/); - assert.match(open,/mixerSessionRecoveryPending_=true;[\s\S]*?"LOGICAL_SESSION_OPENED_UNBOUND"/); + assert.match(edit,/mixerSessionRecoveryPending_=true;\s*mixerSessionStatus_="LOGICAL_SESSION_SAVED_UNBOUND"/); + assert.match(open,/if\(openError.isEmpty\(\)\)[\s\S]*?"LOGICAL_SESSION_OPENED_UNBOUND"/); + const control=read('src/NativeLogicalMixerControl.h'); + assert.match(control,/workspace_=std::move\(\*candidate\);[\s\S]*?checkpointSaved_\(workspace_.document\(\).id\)/); assert.match(save,/if\(automatic&&mixerSessionRecoveryPending_\)[\s\S]*?return "[^"]+";[\s\S]*?captureNativeMixerSession/); }); diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index 2009a692d..926d24fcf 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -7,7 +7,7 @@ #include "../src/NativeMixerSessionStore.h" #include "../src/LiveDryRoutingLab.h" #include "../src/NativeMixerSessionFxRestore.h" -#include "../src/NativeLogicalMixerWorkspace.h" +#include "../src/NativeLogicalMixerControl.h" using namespace armix::mixer; using namespace armix::session; @@ -826,7 +826,183 @@ static void verifyLegacyHarmoniceSessionName(){ assert(saved.inserts.front().name=="ArSon Harmony"); assert((*lease)->processor->getLatencySamples()==1536); } +static void verifyLogicalControlTransactions() { + juce::ScopedJuceInitialiser_GUI juce; + const auto folder=juce::File::getSpecialLocation(juce::File::tempDirectory) + .getNonexistentChildFile("armix-logical-control-","",false); + assert(folder.createDirectory().wasOk()); + NativeMixerSessionSaveWorker worker; + int commits=0; + NativeLogicalMixerControl control(folder,worker,[&](const juce::String& id){ + assert(id.isNotEmpty()); + ++commits; + }); + assert(control.ensureLoaded().error.isEmpty()); + auto command=[&](const char* requestId,const char* operation, + const juce::String& id={},juce::var payload={},juce::var value={}) { + auto request=std::make_unique(); + const auto before=control.readback(); + request->setProperty("requestId",requestId); + request->setProperty("operation",operation); + request->setProperty("channelId",id); + request->setProperty("baseRevision",before.getProperty("revision",{})); + request->setProperty("workspaceToken",before.getProperty("workspaceToken",{})); + request->setProperty("payload",std::move(payload)); + request->setProperty("value",std::move(value)); + return juce::var(request.release()); + }; + juce::Array acks; + const auto submit=[&](const juce::var& request, + NativeLogicalMixerControl::Availability access={false,true,false}) { + control.handleIntent(request,access, + [](const juce::String& id){return armix::builtin_fx::findNativeBuiltInFx(id)!=nullptr;}, + [](const auto& workspace,ChannelId channel,std::size_t slot,auto& insert,auto& processor){ + insert.channel=channel; + insert.slot=slot; + insert.catalogId=juce::String(workspace.document().roster.find(channel) + ->insertCatalogIds[slot]); + juce::AudioPluginFormatManager formats; + const auto error=NativeMixerSessionFxRestore::prepareProcessor( + insert,nullptr,formats,48000.,256,processor); + if(error.isEmpty())insert.name=processor->getName(); + return error; + },[&](juce::var ack){acks.add(std::move(ack));}); + }; + const auto waitForIO=[&]{ + const auto deadline=juce::Time::getMillisecondCounter()+10000; + while(worker.busy() && juce::Time::getMillisecondCounter()runDispatchLoopUntil(10); + assert(!worker.busy()); + }; + const auto reject=[&](const char* reason){ + const auto ack=acks.getLast(); + assert(ack.getProperty("status",{}).toString()=="REJECTED"); + assert(ack.getProperty("errorCode",{}).toString()==reason); + assert(ack.getProperty("revision",{})==control.readback().getProperty("revision",{})); + }; + const auto accept=[&](const juce::var& request){ + const auto before=control.readback().getProperty("revision",{}); + const int count=acks.size(); + submit(request); + assert(acks.size()==count && worker.busy()); + assert(control.readback().getProperty("revision",{})==before); + waitForIO(); + assert(acks.size()==count+1); + const auto ack=acks.getLast(); + assert(ack.getProperty("requestId",{})==request.getProperty("requestId",{})); + assert(ack.getProperty("status",{}).toString()=="ACCEPTED"); + const auto after=control.readback(); + assert(ack.getProperty("revision",{})==after.getProperty("revision",{})); + assert(after.getProperty("revision",{})!=before); + assert(after.getProperty("authority",{}).toString()=="LOGICAL_ONLY"); + assert(!static_cast(ack.getProperty("physicalOutputAdmitted",true))); + assert(!static_cast(after.getProperty("graph",{}).getProperty("capabilities",{}) + .getProperty("callbackOwnsChannelIds",true))); + return ack.getProperty("createdId",{}).toString(); + }; + auto create=command("logical-create","CREATE_CHANNEL",{}, + juce::JSON::parse(R"({"name":"Lead"})")); + submit(create,{false,false,false}); + reject("PHYSICAL_PCM_AUTHORITY_ACTIVE"); + auto stale=command("logical-stale","CREATE_GROUP"); + const auto channel=accept(create); + submit(create); + reject("DUPLICATE_LOGICAL_REQUEST"); + submit(stale); + reject("STALE_LOGICAL_REVISION"); + const auto bus=accept(command("logical-bus","CREATE_GROUP",{}, + juce::JSON::parse(R"({"name":"Vocals"})"))); + auto wire=juce::JSON::parse(R"({"changes":[{"op":"ROUTE_ONLY"}]})"); + auto* wireChange=wire.getProperty("changes",{})[0].getDynamicObject(); + wireChange->setProperty("from",channel); + wireChange->setProperty("to",bus); + accept(command("logical-wire","WIRE_TRANSACTION",channel,wire)); + accept(command("logical-rename","RENAME_CHANNEL",channel, + juce::JSON::parse(R"({"name":"Lead Vox"})"))); + for(const auto& fx:armix::builtin_fx::nativeBuiltInFx) { + auto payload=std::make_unique(); + payload->setProperty("catalogId",fx.id); + accept(command((juce::String("logical-fx-")+fx.id).toRawUTF8(), + "ADD_FX_REFERENCE",bus,juce::var(payload.release()))); + } + accept(command("logical-bypass","SET_FX_SLOT_BYPASS",bus, + juce::JSON::parse(R"({"slot":1,"enabled":true})"))); + accept(command("logical-rack","SET_FX_RACK_BYPASS",bus,{},true)); + const auto file=folder.getChildFile("concert.smix"); + assert(control.exportTo(file,[](juce::String error){assert(error.isEmpty());})); + waitForIO(); + MixerSessionDocument saved; + std::vector states; + assert(NativeMixerSessionStore::readFile(file,saved,states).isEmpty()); + assert(saved.logicalOnly && saved.request.physicalInputs==0); + const ChannelId trackId{static_cast(channel.getLargeIntValue())}; + const ChannelId busId{static_cast(bus.getLargeIntValue())}; + assert(saved.roster.find(trackId)->name=="Lead Vox"); + assert(saved.roster.find(trackId)->sends.front().destination==busId); + assert(saved.inserts.size()==armix::builtin_fx::nativeBuiltInFx.size()); + assert(saved.inserts[1].bypass && saved.rackBypassed.front()==busId); + juce::AudioPluginFormatManager formats; + for(const auto& insert:saved.inserts) { + const auto state=std::find_if(states.begin(),states.end(),[&](const auto& blob){ + return blob.sha256==insert.sha256; + }); + assert(state!=states.end()); + std::unique_ptr restored; + assert(NativeMixerSessionFxRestore::prepareProcessor( + insert,&*state,formats,48000.,256,restored).isEmpty()); + assert(restored && restored->getName()==insert.name); + } + + // A second request while an actual commit is queued sees the old model + // and rejects. Force the next disk promotion to fail at PREVIOUS, while + // HEAD still points to the last accepted and independently readable state. + auto remove=command("logical-remove","REMOVE_FX_REFERENCE",bus, + juce::JSON::parse(R"({"slot":0})")); + submit(remove); + submit(command("logical-busy","DELETE_CHANNEL",channel)); + reject("LOGICAL_EDITOR_BUSY"); + waitForIO(); + assert(acks.getLast().getProperty("status",{}).toString()=="ACCEPTED"); + const auto oldReadback=juce::JSON::toString(control.readback(),true); + const int oldCommits=commits; + const auto previous=folder.getChildFile("MixerSession").getChildFile("PREVIOUS"); + assert(previous.deleteFile()); + assert(previous.createDirectory().wasOk()); + assert(previous.getChildFile("sentinel").replaceWithText("force failed pointer write")); + submit(command("logical-failed","DELETE_CHANNEL",channel)); + waitForIO(); + const auto failed=acks.getLast(); + assert(failed.getProperty("requestId",{}).toString()=="logical-failed"); + assert(failed.getProperty("status",{}).toString()=="REJECTED"); + assert(juce::JSON::toString(control.readback(),true)==oldReadback); + assert(commits==oldCommits); + MixerSessionDocument head; + std::vector headStates; + assert(NativeMixerSessionStore(folder).load(head,headStates).isEmpty()); + assert(head.acceptedRevision==control.workspace().revision()); + assert(head.roster.find(trackId) && head.inserts.size()==saved.inserts.size()-1); + assert(previous.deleteRecursively()); + + accept(command("logical-delete","DELETE_CHANNEL",channel)); + accept(command("logical-remove-bus","REMOVE_BUS",bus)); + bool opened=false; + assert(worker.load(file,[&](juce::String error,MixerSessionDocument document, + std::vector binary){ + assert(error.isEmpty()); + assert(control.open(std::move(document),std::move(binary),[&](juce::String openError){ + assert(openError.isEmpty()); + opened=true; + })); + })); + waitForIO(); + assert(opened); + assert(control.workspace().document().roster.find(trackId)); + assert(control.workspace().document().roster.find(busId)); + assert(folder.deleteRecursively()); +} + int main(){ + verifyLogicalControlTransactions(); verifyLegacyHarmoniceSessionName(); verifyOfflineLogicalSessionAndFile(); verifyProductionPlayerFirstSoundWithSourceOnly(); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 853c6bcff..7497dc6ed 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1166,16 +1166,18 @@ let pendingFxInsert=null,fxRequestSerial=0,nativeCatalog=new Map(); // Native JUCE processors: these are real compiled DSP, not demo effects, // scanned VST binaries, a JS renderer or placeholder library entries. - const nativeBuiltins=Object.freeze([ + let nativeBuiltins=Object.freeze([ Object.freeze({id:"armix.builtin.channel-eq.v1",name:"Parametric EQ", vendor:"ArSonMix",category:"EQ",format:"Native",source:"builtin"}), Object.freeze({id:"armix.builtin.channel-compressor.v1",name:"Compressor", vendor:"ArSonMix",category:"Dynamics",format:"Native",source:"builtin"}), Object.freeze({id:"armix.builtin.arson-harmony.v1",name:"Harmonice", - vendor:"ArSonMix",category:"Utility",format:"Native",source:"builtin"}) + vendor:"ArSonMix",category:"Utility",format:"Native",source:"builtin"}), + Object.freeze({id:"armix.builtin.vocal-throw.v1",name:"ArSon Vocal Throw", + vendor:"ArSonMix",category:"Utility",format:"Native",source:"builtin",showInPicker:false}) ]); const presentFxCatalog=()=>scope?.setNativeCatalog?.( - [...nativeBuiltins,...nativeCatalog.values()]); + [...nativeBuiltins.filter(fx=>fx.showInPicker!==false),...nativeCatalog.values()]); let nativeFxDiscoveryRequested=false,nativeFxCatalogScanning=false; // Lazy USER-triggered discovery: the first Add FX opens immediately and // starts real JUCE VST3 scanning on its dedicated non-audio worker. Never @@ -2441,7 +2443,14 @@ controller.subscribe(); },8000); } - function onNativeReadback(next) { + function playAcceptedWireImpact(changes) { + const plug=changes?.find(change=>["CONNECT","ROUTE_ONLY","RETARGET"].includes(change.op)); + if(!plug)return; + const from=uiByNativeId.get(plug.from),to=uiByNativeId.get(plug.to); + if(from===undefined||to===undefined||to===scope?.master?.id)return; + scope?.kickWireSpring?.(from,to); + } + function onNativeReadback(next,confirmed) { scope?.syncNativeWireGains?.([]); // flush accepted paint after pointer release appearanceFromNative(next); updateHardwarePanel(next); @@ -2467,7 +2476,7 @@ identity:"logical:"+offline.workspaceToken+":"+offline.revision,logical:true, readOnly:offline.readOnly===true, admitted:false,retained:false,productLive:false,telemetry:{}}; - let revealCreatedId=null; + let revealCreatedId=null,wireImpact=null; if(pendingLogical && pendingLogical.workspaceToken!==offline.workspaceToken) pendingLogical=null; if(pendingLogical) { @@ -2481,6 +2490,8 @@ return; } pendingLogical=null; + if(p.operation==="WIRE_TRANSACTION"&&offline.revision===p.ackRevision) + wireImpact=p.payload.changes; if((p.operation==="CREATE_CHANNEL"||p.operation==="CREATE_GROUP") && p.createdId)revealCreatedId=p.createdId; if(logicalRenameId===p.channelId&&p.operation==="RENAME_CHANNEL") { @@ -2502,6 +2513,7 @@ } lastPaintedSignature=signature; } + if(wireImpact)playAcceptedWireImpact(wireImpact); if(revealCreatedId) { const local=uiByNativeId.get(revealCreatedId); const strip=scope?.tracks?.find(t=>t.id===local); @@ -2617,6 +2629,8 @@ flags.productionCallbackLive=next.productLive;flags.acceptedGraphConnected=true; syncMonitorButton(next.device); lastPaintedSignature=signature;stopDemo();paintNativeMeters(next); + if(confirmed?.operation==="APPLY_WIRE_TRANSACTION") + playAcceptedWireImpact(confirmed.payload.changes); finishNativeTrack(next);finishNativeTrackDelete(next); if(pendingFxInsert?.authority==="CHANNEL_ID"){ const p=pendingFxInsert; @@ -2909,6 +2923,10 @@ nativeCatalog=new Map(catalog.items.filter(p=> p&&typeof p.id==="string"&&p.id.length>0&& typeof p.name==="string"&&p.name.length>0).map(p=>[p.id,p])); + if(Array.isArray(catalog.builtIns)) + nativeBuiltins=catalog.builtIns.filter(fx=>fx && typeof fx.id==="string" && + typeof fx.name==="string" && fx.id.length && fx.name.length) + .map(fx=>({...fx,vendor:"ArSonMix",format:"Native",source:"builtin"})); presentFxCatalog(); if(nativeFxDiscoveryRequested&&!nativeFxCatalogScanning&&nativeCatalog.size===0) status("Built-in FX ready · import VST3 to add more effects"); @@ -3405,11 +3423,7 @@ return true; } if(pendingFxInsert){status("FX INSERT · wait for previous native ACK");return true;} - const plugin=nativeCatalog.get(id) || - (id==='armix.builtin.channel-eq.v1'?{id,name:'Parametric EQ'}: - id==='armix.builtin.channel-compressor.v1'?{id,name:'Compressor'}: - id==='armix.builtin.arson-harmony.v1'?{id,name:'Harmonice'}: - id==='armix.builtin.vocal-throw.v1'?{id,name:'ArSon Vocal Throw'}:null); + const plugin=nativeCatalog.get(id) || nativeBuiltins.find(fx=>fx.id===id); const track=scope?.tracks?.find(x=>x.id===target?.channelId)|| (scope?.master?.id===target?.channelId?scope.master:null); const channel=m4Index(track),slot=Number(target?.slot); diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index 1da1ea8d0..26a2dc267 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -313,8 +313,9 @@ pending=null;lastError="ACK_READBACK_EFFECT_MISMATCH"; subscribe();notify();return false; } + const confirmed=pending; pending=null;lastError="ACCEPTED_READBACK"; - current=next;onAccepted(next); + current=next;onAccepted(next,confirmed); notify();return true; } else if (cmp(next.graph.revision,ack.graphRevision) > 0 || (cmp(next.graph.revision,ack.graphRevision) === 0 && From e3f7f627c81a4c2dafb75165a230a66186b31eec Mon Sep 17 00:00:00 2001 From: masarray Date: Wed, 11 Nov 2026 03:02:50 +0700 Subject: [PATCH 2/2] Follow shared FX registry in Harmony assembly guard --- tests/native_harmony_assembly_test.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/native_harmony_assembly_test.py b/tests/native_harmony_assembly_test.py index 84d68a3f7..2e14b2503 100644 --- a/tests/native_harmony_assembly_test.py +++ b/tests/native_harmony_assembly_test.py @@ -38,12 +38,12 @@ def test_native_catalog_bridge_and_editor(self): self.assertIn("t.fx[slot]='Harmonice'",self.html) self.assertIn("t.fx[index]==='Harmonice'||t.fx[index]==='ArSon Harmony'",self.html) self.assertIn('id:"armix.builtin.arson-harmony.v1",name:"Harmonice"',self.bridge) - self.assertIn("id==='armix.builtin.arson-harmony.v1'?{id,name:'Harmonice'}",self.bridge) + self.assertIn("nativeBuiltins.find(fx=>fx.id===id)",self.bridge) processor=(ROOT/"engine/builtin_fx/ChannelHarmonyProcessor.h").read_text("utf-8") - audio=(ROOT/"src/LiveAudioEngine.h").read_text("utf-8") + registry=(ROOT/"src/NativeBuiltInFx.h").read_text("utf-8") self.assertIn('catalogIdentity="armix.builtin.arson-harmony.v1"',processor) self.assertIn('getName() const override {return "Harmonice";}',processor) - self.assertIn('"Harmonice",LiveDryRoutingLab::Block::hardFrameLimit',audio) + self.assertIn('NativeBuiltInFx{ChannelHarmonyProcessor::catalogIdentity,"Harmonice"',registry) self.assertIn("window.ArSonMixNativeHarmony.insert(activeFxTarget)",self.html) self.assertIn("arMixBuiltinHarmonyQueue",self.ui) self.assertIn("arMixBuiltinHarmonyAck",self.ui)