From 3f3ab707189f4d3583cf4042618e9903d3027a8c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 06:23:45 +0700 Subject: [PATCH 1/6] feat(p2): native VST3 plugin catalog, persistent scan and real FX rack chain --- .github/workflows/p1-windows.yml | 10 +- CMakeLists.txt | 6 +- README.md | 6 + docs/P2_NATIVE_FX_RACK.md | 34 +++ src/LiveAudioEngine.h | 343 +++++++++++++++++++------------ src/Main.cpp | 269 +++++++++++++++++------- src/PluginCatalog.h | 249 ++++++++++++++++++++++ web/bridge.js | 325 +++++++++++++++++++++++------ 8 files changed, 971 insertions(+), 271 deletions(-) create mode 100644 docs/P2_NATIVE_FX_RACK.md create mode 100644 src/PluginCatalog.h diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 57729036c..099d359bc 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -1,7 +1,7 @@ -name: P1 Windows First Sound +name: Windows Native VST3 Host on: push: - branches: [ main, feature/p1-first-sound-windows ] + branches: [ main, feature/p1-first-sound-windows, feature/p2-native-vst-catalog-fx-rack ] pull_request: workflow_dispatch: @@ -42,13 +42,13 @@ jobs: Where-Object { $_.Name -like "*AR*Mix*" -and $_.FullName -match 'Release' } | Select-Object -First 1 if (-not $exe) { throw "ARMixConsole EXE not found" } - Copy-Item $exe.FullName "dist/AR-MIX-Studio-P1.exe" + Copy-Item $exe.FullName "dist/AR-MIX-Studio-P2.exe" Copy-Item README.md "dist/README.md" - "P1 experimental: output muted until MONITOR ON; do not use during a public livestream without hardware tests." | + "P2 experimental: output muted until MONITOR ON; do not use during a public livestream without hardware tests." | Out-File -FilePath dist/FIRST_SOUND_README.txt -Encoding utf8 - uses: actions/upload-artifact@v4 with: - name: AR-MIX-Studio-P1-Windows-x64 + name: AR-MIX-Studio-P2-Windows-x64 path: dist/ if-no-files-found: error retention-days: 14 diff --git a/CMakeLists.txt b/CMakeLists.txt index 2609019ab..08286650e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.22) -project(ARMixConsole VERSION 0.4.0 LANGUAGES C CXX) +project(ARMixConsole VERSION 0.5.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -19,7 +19,7 @@ juce_add_gui_app(ARMixConsole juce_add_binary_data(ARMixAssets SOURCES web/index.html web/styles.css web/app.js web/bridge.js) -target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h) +target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/PluginCatalog.h) target_compile_definitions(ARMixConsole PRIVATE JUCE_WEB_BROWSER=1 JUCE_USE_WIN_WEBVIEW2=1 @@ -27,7 +27,7 @@ target_compile_definitions(ARMixConsole PRIVATE JUCE_ASIO=1 JUCE_PLUGINHOST_VST3=1 JUCE_APPLICATION_NAME_STRING="AR MIX Studio" - JUCE_APPLICATION_VERSION_STRING="0.4.0-p1") + JUCE_APPLICATION_VERSION_STRING="0.5.0-p2") target_link_libraries(ARMixConsole PRIVATE ARMixAssets juce::juce_gui_extra diff --git a/README.md b/README.md index 648346ab7..8f9ed3ffc 100644 --- a/README.md +++ b/README.md @@ -52,3 +52,9 @@ Code in this trial is authored for the project and provided under AGPL-3.0-only The new P1 native EXE provides actual microphone passthrough through one VST3 effect, ASIO/WASAPI device selector, bypass, monitor arm/mute, master gain and real callback meter. The old FX rack and channels 2–12 are **still UI previews** (do not confuse demo plugin inserts with native VST3). Output starts muted for hearing/feedback safety. See [P1 trial instructions](docs/P1_FIRST_SOUND.md). GitHub Actions: [Windows First Sound builds](https://github.com/masarray/arsonmix/actions/workflows/p1-windows.yml). Download the artifact only after the run is GREEN. JUCE 8.0.15 is pinned by CI and includes GPLv3 ASIO SDK sources; this repository uses AGPLv3. Plugin compatibility and low latency must still be verified with real hardware. + +## P2 Native VST3 Catalog and FX Rack + +The native Windows host supports **Scan VST3**, **Add Plugin Folder**, **Import VST3** and a persistent plugin catalog in user app-data. The FX Rack inside WebView2 now controls the **one native stereo audio path** with up to 8 real VST3 effects: add, bypass, reorder, remove and open plugin UI. The Windows audio setup dialog is also native, with saved device configuration. + +All remaining UI preview channels and factory vocal presets are still visual; do not infer that they are running live audio. Legacy VST2 `.dll` is **not** supported or automatically treated as VST3. Plugin scanning uses a worker, but not yet a crash-isolated subprocess; avoid unknown plugins during a livestream. Read [P2 Hardware Trial](docs/P2_NATIVE_FX_RACK.md). diff --git a/docs/P2_NATIVE_FX_RACK.md b/docs/P2_NATIVE_FX_RACK.md new file mode 100644 index 000000000..b4aec8ffc --- /dev/null +++ b/docs/P2_NATIVE_FX_RACK.md @@ -0,0 +1,34 @@ +# AR MIX Studio P2 — Native VST3 Catalog and FX Rack (Experimental) + +## Try on Windows +1. Open the GitHub Actions build artifact `AR-MIX-Studio-P2-Windows-x64` from the successful workflow. +2. Unzip, open `AR-MIX-Studio-P2.exe`. Audio monitoring is OFF at startup. +3. In **SETUP**, choose **OPEN ASIO / WASAPI DEVICE SETTINGS**, select an input+output interface, 48 kHz, and 128/256 samples to start. +4. In **FX RACK**, click **RESCAN VST3** to search system VST3 locations, **ADD PLUGIN FOLDER** for an additional installation directory, or **IMPORT VST3 FILE** for an individual `.vst3` file/bundle. +5. Results appear in the persistent native catalog. Search by plugin name or vendor. Click **+ ADD** to insert the plugin into the actual audio chain. Repeat up to 8 plugins. +6. **EDIT** opens the plugin's native UI; **ON/OFF** bypasses; arrows change order; **×** removes. Changes pause the callback briefly, so do not perform them on-air. +7. With headphones and low hardware volume, click **MONITOR ON**. Confirm audible change between plugin ON/OFF and watch real input/master meters. + +## What P2 actually implements +- Windows ASIO/WASAPI using JUCE AudioDeviceManager and native selector. +- Settings persisted to user app-data `AR-MIX-Studio/audio-devices.xml`. +- Native VST3 catalog persisted to `AR-MIX-Studio/plugin-catalog.json`. +- Recursive scan of default/custom folders, direct import of one `.vst3` file/bundle, cached display between sessions. +- Single live microphone/stereo audio path with maximum eight native VST3 inserts, native plugin UI, order, bypass, removal. +- Low-allocation host callback. UI and scanning are outside the callback. + +## Explicit exclusions / safety +- **VST2 DLL** is not a VST3 module; raw DLL import is intentionally rejected. VST2 would require a separate, vetted SDK/licensing strategy. +- **Scanning is on a worker thread, not a crash-isolated subprocess**. Broken plugins may still crash or hang the host. This is experimental. +- The other 11 mixer channels and their visual presets are still a concept. Native FX chain applies only to channel 1. +- Real plugin state preset/save/restore, sidechain routing, bridge to OBS and round-trip measurement are not finished. +- VST3 processBlock code belongs to third-party plugins. Host-side callback design alone cannot guarantee zero allocations, x-runs or crashes. +- Plugins that do not support stereo effect layout may be rejected. Missing/invalid libraries are reported to the user. +- Do not infer audio reliability from successful GitHub Actions compilation. Validate with ASIO and WASAPI on physical hardware. + +## Acceptance +- GitHub Actions release x64 build GREEN and artifact uploaded. +- Scan actual VST3 installation, catalog populated and survives restart. +- Add/remove/bypass/edit/reorder two real plugins and verify audible routing. +- Save/restart audio device settings and verify the same device is selected. +- Test repeatedly with headphones, 48 kHz / 128 samples then 64 only after stable result. diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index d340aaf50..a94d08e79 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -2,20 +2,31 @@ #pragma once #include #include +#include #include #include #include -// P1: single stereo microphone -> one VST3 -> master output. -// Structural mutations happen on the message thread ONLY after detaching the -// audio callback. No plugin load/scan/IO/mutex/logging/heap allocation by host -// code inside audioDeviceIOCallbackWithContext. +// One live stereo input path and up to 8 actual VST3 processors. +// The audio callback never scans files, creates plugins, mutates the chain, +// enters UI code, locks host mutexes, logs, or changes device settings. +// Chain edits detach audio callback first (brief intentional dropout in P2). class LiveAudioEngine final : private juce::AudioIODeviceCallback { public: + static constexpr int maxFx = 8; + + struct Slot + { + std::unique_ptr processor; + juce::String name, catalogId; + bool bypass = false; + int latency = 0; + }; + LiveAudioEngine() { - formatManager_.addFormat (std::make_unique()); + formats_.addFormat (std::make_unique()); scratch_.setSize (2, maxFrames, false, true, false); } @@ -23,187 +34,267 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::AudioDeviceManager& devices() noexcept { return deviceManager_; } - juce::String start() + juce::String start (const juce::XmlElement* savedSettings = nullptr) { - // Disarmed on launch to prevent acoustic feedback with open microphones. - monitorEnabled_.store (false); - const auto error = deviceManager_.initialise (1, 2, nullptr, true); - if (error.isNotEmpty()) - return error; + monitor_.store (false); + const auto error = deviceManager_.initialise (1, 2, savedSettings, true); + if (error.isNotEmpty()) return error; deviceManager_.addAudioCallback (this); - callbackAttached_ = true; + attached_ = true; return {}; } void stop() { - if (callbackAttached_) - { - deviceManager_.removeAudioCallback (this); - callbackAttached_ = false; - } - if (plugin_ != nullptr) + detach(); + for (int i = 0; i < count_; ++i) { - plugin_->releaseResources(); - plugin_.reset(); + if (slots_[i].processor) slots_[i].processor->releaseResources(); + slots_[i] = Slot {}; } + count_ = 0; deviceManager_.closeAudioDevice(); } - void setMonitorEnabled (bool enabled) noexcept { monitorEnabled_.store (enabled); } - bool isMonitorEnabled() const noexcept { return monitorEnabled_.load(); } - void setBypassed (bool bypassed) noexcept { bypassed_.store (bypassed); } - bool isBypassed() const noexcept { return bypassed_.load(); } - void setMasterGainDb (float db) noexcept + void setMonitorEnabled (bool value) noexcept { monitor_.store (value); } + bool isMonitorEnabled() const noexcept { return monitor_.load(); } + void setMasterGainDb (float value) noexcept { - if (std::isfinite (db)) - linearGain_.store (std::pow (10.0f, juce::jlimit (-60.0f, 10.0f, db) / 20.0f)); + if (std::isfinite (value)) masterGain_.store (juce::Decibels::decibelsToGain (juce::jlimit (-60.f, 10.f, value))); } - - // Message-thread operation. VST3 code is untrusted and may hang or crash; - // sandboxed scanning/hosting is deliberately a later milestone. - juce::String loadVst3 (const juce::File& path) + void setChannelGainDb (float value) noexcept { - if (! path.exists() || ! path.hasFileExtension (".vst3")) - return "Choose an installed .vst3 module or bundle"; + if (std::isfinite (value)) channelGain_.store (juce::Decibels::decibelsToGain (juce::jlimit (-60.f, 10.f, value))); + } + void setChannelMuted (bool value) noexcept { channelMute_.store (value); } + + int chainSize() const noexcept { return count_; } - auto* format = formatManager_.getFormat (0); - if (format == nullptr || ! format->fileMightContainThisPluginType (path.getFullPathName())) - return "Not a recognised VST3 module"; + juce::AudioPluginInstance* pluginAt (int index) noexcept + { + return index >= 0 && index < count_ ? slots_[index].processor.get() : nullptr; + } - juce::OwnedArray descriptions; - format->findAllTypesForFile (descriptions, path.getFullPathName()); - if (descriptions.isEmpty()) - return "No VST3 effect found in the selected module"; + juce::var chainState() const + { + juce::Array nodes; + for (int i = 0; i < count_; ++i) + { + auto node = std::make_unique(); + node->setProperty ("index", i); + node->setProperty ("name", slots_[i].name); + node->setProperty ("id", slots_[i].catalogId); + node->setProperty ("bypass", slots_[i].bypass); + node->setProperty ("latency", slots_[i].latency); + nodes.add (juce::var (node.release())); + } + return juce::var (nodes); + } + juce::String addVst3 (const juce::String& filename, int uid, + const juce::String& catalogId) + { + if (count_ >= maxFx) return "FX Rack is full (maximum 8 VST3 effects)"; auto* device = deviceManager_.getCurrentAudioDevice(); - if (device == nullptr) - return "Configure a working audio device first"; + if (device == nullptr) return "Configure a working audio input/output device first"; + auto* fmt = formats_.getFormat (0); + if (fmt == nullptr || ! fmt->fileMightContainThisPluginType (filename)) + return "VST3 module not found: " + filename; + + juce::OwnedArray descs; + fmt->findAllTypesForFile (descs, filename); + juce::PluginDescription* chosen = nullptr; + for (auto* d : descs) + if (d != nullptr && d->uniqueId == uid && !d->isInstrument) + { + chosen = d; + break; + } + if (chosen == nullptr) + return "Effect not found inside VST3 module. Rescan the catalog."; juce::String error; - auto candidate = formatManager_.createPluginInstance ( - *descriptions[0], device->getCurrentSampleRate(), + auto instance = formats_.createPluginInstance ( + *chosen, device->getCurrentSampleRate(), juce::jmax (32, device->getCurrentBufferSizeSamples()), error); - if (candidate == nullptr) - return "VST3 load failed: " + error; - - juce::AudioProcessor::BusesLayout stereo; - stereo.inputBuses.add (juce::AudioChannelSet::stereo()); - stereo.outputBuses.add (juce::AudioChannelSet::stereo()); - if (! candidate->setBusesLayout (stereo)) - return "P1 accepts stereo input/stereo output effects only"; - - // Detach waits for in-flight callbacks, then reattach after publish. - // The temporary silence is explicit P1 behaviour, not seamless hot swap. - if (callbackAttached_) - deviceManager_.removeAudioCallback (this); - if (plugin_ != nullptr) - plugin_->releaseResources(); - plugin_ = std::move (candidate); - pluginName_ = descriptions[0]->name; - bypassed_.store (false); - if (callbackAttached_) - deviceManager_.addAudioCallback (this); + if (! instance) + return "Failed to instantiate VST3: " + error; + + juce::AudioProcessor::BusesLayout layout; + layout.inputBuses.add (juce::AudioChannelSet::stereo()); + layout.outputBuses.add (juce::AudioChannelSet::stereo()); + if (! instance->setBusesLayout (layout)) + return "P2 accepts stereo-in/stereo-out effects; plugin bus layout is incompatible"; + + detach(); + Slot node; + node.name = chosen->name; + node.catalogId = catalogId; + node.processor = std::move (instance); + slots_[count_++] = std::move (node); + attach(); return {}; } - void unloadPlugin() + bool setBypass (int index, bool value) { - if (callbackAttached_) - deviceManager_.removeAudioCallback (this); - if (plugin_ != nullptr) - plugin_->releaseResources(); - plugin_.reset(); - pluginName_.clear(); - if (callbackAttached_) - deviceManager_.addAudioCallback (this); + if (index < 0 || index >= count_) return false; + // Message-thread writes under a detached callback; no data race. + detach(); + slots_[index].bypass = value; + attach(); + return true; + } + + bool removeAt (int index) + { + if (index < 0 || index >= count_) return false; + detach(); + if (slots_[index].processor) + slots_[index].processor->releaseResources(); + for (int i = index; i + 1 < count_; ++i) + slots_[i] = std::move (slots_[i + 1]); + slots_[--count_] = Slot {}; + attach(); + return true; + } + + bool moveSlot (int from, int to) + { + if (from < 0 || from >= count_ || to < 0 || to >= count_ || from == to) + return false; + detach(); + auto moved = std::move (slots_[from]); + if (from < to) + for (int i = from; i < to; ++i) slots_[i] = std::move (slots_[i + 1]); + else + for (int i = from; i > to; --i) slots_[i] = std::move (slots_[i - 1]); + slots_[to] = std::move (moved); + attach(); + return true; } - juce::var status() const + juce::var status() { - auto object = std::make_unique(); + auto o = std::make_unique(); auto* d = deviceManager_.getCurrentAudioDevice(); - object->setProperty ("connected", d != nullptr); - object->setProperty ("driver", deviceManager_.getCurrentAudioDeviceType()); - object->setProperty ("device", d != nullptr ? d->getName() : "No audio device"); - object->setProperty ("rate", d != nullptr ? d->getCurrentSampleRate() : 0.0); - object->setProperty ("buffer", d != nullptr ? d->getCurrentBufferSizeSamples() : 0); - object->setProperty ("plugin", pluginName_); - object->setProperty ("pluginLatencySamples", plugin_ != nullptr ? plugin_->getLatencySamples() : 0); - object->setProperty ("monitor", monitorEnabled_.load()); - object->setProperty ("bypass", bypassed_.load()); - object->setProperty ("peak", peak_.load (std::memory_order_relaxed)); - object->setProperty ("note", "P1: input stereo -> optional VST3 -> output; CH1 + master only"); - return juce::var (object.release()); + o->setProperty ("connected", d != nullptr); + o->setProperty ("driver", deviceManager_.getCurrentAudioDeviceType()); + o->setProperty ("device", d ? d->getName() : "No device"); + o->setProperty ("rate", d ? d->getCurrentSampleRate() : 0.0); + o->setProperty ("buffer", d ? d->getCurrentBufferSizeSamples() : 0); + o->setProperty ("monitor", monitor_.load()); + o->setProperty ("inputPeak", inputPeak_.load()); + o->setProperty ("peak", outputPeak_.load()); + o->setProperty ("latencySamples", totalLatency_.load()); + o->setProperty ("chainCount", count_); + return juce::var (o.release()); } private: static constexpr int maxFrames = 8192; juce::AudioDeviceManager deviceManager_; - juce::AudioPluginFormatManager formatManager_; - std::unique_ptr plugin_; + juce::AudioPluginFormatManager formats_; + std::array slots_; + int count_ = 0; + bool attached_ = false; juce::AudioBuffer scratch_; - juce::String pluginName_; - bool callbackAttached_ = false; - std::atomic monitorEnabled_ { false }, bypassed_ { false }; - std::atomic linearGain_ { 1.0f }, peak_ { 0.0f }; + std::atomic monitor_ { false }, channelMute_ { false }; + std::atomic masterGain_ { 1.f }, channelGain_ { 1.f }; + std::atomic inputPeak_ { 0.f }, outputPeak_ { 0.f }; + std::atomic totalLatency_ { 0 }; + + void detach() + { + if (attached_) + { + deviceManager_.removeAudioCallback (this); + attached_ = false; + } + } + void attach() + { + if (! attached_ && deviceManager_.getCurrentAudioDevice() != nullptr) + { + deviceManager_.addAudioCallback (this); + attached_ = true; + } + } - void audioDeviceAboutToStart (juce::AudioIODevice* device) override + void audioDeviceAboutToStart (juce::AudioIODevice* d) override { - if (plugin_ != nullptr) + int latency = 0; + for (int i = 0; i < count_; ++i) { - plugin_->releaseResources(); - plugin_->prepareToPlay (device->getCurrentSampleRate(), - juce::jmax (32, device->getCurrentBufferSizeSamples())); + auto& slot = slots_[i]; + if (slot.processor) + { + slot.processor->releaseResources(); + slot.processor->prepareToPlay (d->getCurrentSampleRate(), + juce::jmax (32, d->getCurrentBufferSizeSamples())); + slot.latency = slot.processor->getLatencySamples(); + if (!slot.bypass) latency += slot.latency; + } } - peak_.store (0.0f, std::memory_order_relaxed); + totalLatency_.store (latency); + inputPeak_.store (0.f); + outputPeak_.store (0.f); } - void audioDeviceStopped() override { peak_.store (0.0f, std::memory_order_relaxed); } + void audioDeviceStopped() override + { + inputPeak_.store (0.f); + outputPeak_.store (0.f); + } void audioDeviceIOCallbackWithContext ( - const float* const* inputs, int numInputs, float* const* outputs, - int numOutputs, int samples, - const juce::AudioIODeviceCallbackContext&) override - { - const bool enabled = monitorEnabled_.load (std::memory_order_relaxed); - const bool bypass = bypassed_.load (std::memory_order_relaxed); - const float gain = linearGain_.load (std::memory_order_relaxed); - float peak = 0.0f; + const float* const* inputs, int inputChannels, float* const* outputs, + int outputChannels, int samples, const juce::AudioIODeviceCallbackContext&) override + { + const bool enabled = monitor_.load (std::memory_order_relaxed); + const bool muted = channelMute_.load (std::memory_order_relaxed); + const float gain = masterGain_.load (std::memory_order_relaxed) + * channelGain_.load (std::memory_order_relaxed); + float inPeak = 0.f, outPeak = 0.f; for (int offset = 0; offset < samples; offset += maxFrames) { const int frames = juce::jmin (maxFrames, samples - offset); - // Scratch memory was allocated at startup: avoidReallocating=true. scratch_.setSize (2, frames, false, false, true); - for (int ch = 0; ch < 2; ++ch) + for (int c = 0; c < 2; ++c) { - float* dst = scratch_.getWritePointer (ch); - const float* src = numInputs > ch ? inputs[ch] - : numInputs > 0 ? inputs[0] : nullptr; - if (src != nullptr) + float* dst = scratch_.getWritePointer (c); + const float* src = inputChannels > c ? inputs[c] + : inputChannels > 0 ? inputs[0] : nullptr; + if (src) juce::FloatVectorOperations::copy (dst, src + offset, frames); else juce::FloatVectorOperations::clear (dst, frames); + for (int i = 0; i < frames; ++i) + inPeak = juce::jmax (inPeak, std::abs (dst[i])); } - if (plugin_ != nullptr && ! bypass) + // MIDI capacity is empty unless the plugin itself changes it. + juce::MidiBuffer midi; + for (int fx = 0; fx < count_; ++fx) { - juce::MidiBuffer midi; - plugin_->processBlock (scratch_, midi); + auto& slot = slots_[fx]; + if (slot.processor && ! slot.bypass) + slot.processor->processBlock (scratch_, midi); + midi.clear(); } - for (int ch = 0; ch < numOutputs; ++ch) + for (int c = 0; c < outputChannels; ++c) { - if (outputs[ch] == nullptr) - continue; - float* out = outputs[ch] + offset; - const float* source = scratch_.getReadPointer (juce::jmin (ch, 1)); + if (!outputs[c]) continue; + const float* src = scratch_.getReadPointer (juce::jmin (c, 1)); + float* dst = outputs[c] + offset; for (int i = 0; i < frames; ++i) { - const float x = enabled ? source[i] * gain : 0.0f; - out[i] = x; - peak = juce::jmax (peak, std::abs (x)); + const float value = (enabled && !muted) ? src[i] * gain : 0.f; + dst[i] = value; + outPeak = juce::jmax (outPeak, std::abs (value)); } } } - peak_.store (juce::jmin (1.0f, peak), std::memory_order_relaxed); + inputPeak_.store (juce::jmin (1.f, inPeak), std::memory_order_relaxed); + outputPeak_.store (juce::jmin (1.f, outPeak), std::memory_order_relaxed); } }; diff --git a/src/Main.cpp b/src/Main.cpp index 1f4c3e51d..44ca81b7c 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1,14 +1,23 @@ // SPDX-License-Identifier: AGPL-3.0-only -// P1 native Windows first-sound host: mic -> one VST3 -> master output. -// The desktop HTML remains a presentation layer, never the audio callback. +// Native VST3 FX catalog, plugin rack and audio-device bridge. +// Audio runs exclusively in JUCE AudioIODeviceCallback; WebView is control only. #include #include #include #include "LiveAudioEngine.h" +#include "PluginCatalog.h" #include #include +#include + +namespace +{ +juce::File settingsDirectory() +{ + return juce::File::getSpecialLocation ( + juce::File::userApplicationDataDirectory).getChildFile ("AR-MIX-Studio"); +} -namespace { std::optional assetFor (const juce::String& path) { const char* data = nullptr; @@ -22,30 +31,45 @@ std::optional assetFor (const juce::String& { data = BinaryData::app_js; size = BinaryData::app_jsSize; mime = "text/javascript"; } else if (path == "/bridge.js") { data = BinaryData::bridge_js; size = BinaryData::bridge_jsSize; mime = "text/javascript"; } - else - return std::nullopt; - - juce::WebBrowserComponent::Resource result; - result.data.resize (static_cast (size)); - std::memcpy (result.data.data(), data, static_cast (size)); - result.mimeType = mime; - return result; + else return std::nullopt; + + juce::WebBrowserComponent::Resource resource; + resource.data.resize (static_cast (size)); + std::memcpy (resource.data.data(), data, static_cast (size)); + resource.mimeType = mime; + return resource; } class Browser final : public juce::WebBrowserComponent { public: - explicit Browser (Options opts) : juce::WebBrowserComponent (std::move (opts)) {} - bool ready = false; - void pageFinishedLoading (const juce::String&) override { ready = true; } + explicit Browser (Options options) : WebBrowserComponent (std::move (options)) {} + bool loaded = false; + void pageFinishedLoading (const juce::String&) override { loaded = true; } +}; + +class PluginEditorWindow final : public juce::DocumentWindow +{ +public: + PluginEditorWindow (const juce::String& title, juce::AudioProcessorEditor* editor) + : DocumentWindow (title, juce::Colour (0xff14212a), allButtons) + { + setUsingNativeTitleBar (true); + setContentOwned (editor, true); + setResizable (true, true); + centreWithSize (juce::jmax (380, editor->getWidth()), juce::jmax (300, editor->getHeight())); + setVisible (true); + } + void closeButtonPressed() override { setVisible (false); } }; class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer { public: ConsoleWindow() - : juce::DocumentWindow ("AR MIX Studio — P1 FIRST SOUND", - juce::Colour (0xff101921), allButtons), + : DocumentWindow ("AR MIX Studio — Native VST3 FX Host", + juce::Colour (0xff101921), allButtons), + catalog_ (settingsDirectory()), browser_ (juce::WebBrowserComponent::Options{} .withBackend (juce::WebBrowserComponent::Options::Backend::webview2) .withWinWebView2Options ( @@ -59,99 +83,197 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer .withEventListener ("arMixAction", [this] (juce::var args) { onAction (args); }) .withResourceProvider (assetFor)) { + settingsDirectory().createDirectory(); + catalog_.onChanged = [this] { emitCatalog(); }; setUsingNativeTitleBar (true); setResizable (true, true); setResizeLimits (1100, 650, 3840, 2160); setContentNonOwned (&browser_, false); centreWithSize (1650, 930); setVisible (true); - startupError_ = engine_.start(); + + auto saved = juce::XmlDocument::parse (settingsDirectory().getChildFile ("audio-devices.xml")); + startupError_ = engine_.start (saved.get()); browser_.goToURL (juce::WebBrowserComponent::getResourceProviderRoot()); - startTimerHz (15); + startTimerHz (12); + if (catalog_.entries().empty()) + catalog_.scanDefaults(); } ~ConsoleWindow() override { stopTimer(); - browser_.setVisible (false); + catalog_.onChanged = nullptr; + editorWindow_.reset(); engine_.stop(); + browser_.setVisible (false); } - void closeButtonPressed() override - { - juce::JUCEApplication::getInstance()->systemRequestedQuit(); - } + void closeButtonPressed() override { juce::JUCEApplication::getInstance()->systemRequestedQuit(); } private: - // Engine is constructed before and destroyed after Browser. LiveAudioEngine engine_; + PluginCatalog catalog_; Browser browser_; std::unique_ptr chooser_; - juce::String startupError_; + std::unique_ptr editorWindow_; + juce::String startupError_, lastAudioXml_; + + void emitNotice (const juce::String& message, bool error = false) + { + auto o = std::make_unique(); + o->setProperty ("text", message); + o->setProperty ("error", error); + if (browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixNotice", juce::var (o.release())); + } + + void emitCatalog() + { + if (browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixCatalog", catalog_.snapshot()); + } + + void emitChain() + { + if (browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixChain", engine_.chainState()); + } void onParameter (const juce::var& args) { - // Events from WebView2 arrive on the message thread, not RT. const auto name = args.getProperty ("parameter", {}).toString(); - const auto channel = static_cast (args.getProperty ("channel", -2)); + const int channel = static_cast (args.getProperty ("channel", -2)); const auto value = args.getProperty ("value", {}); - if (name == "masterGain" && value.isDouble()) - engine_.setMasterGainDb (static_cast (double (value))); - else if (name == "masterGain" && value.isInt()) - engine_.setMasterGainDb (static_cast (int (value))); - else if (name == "masterMute" && value.isBool() && bool (value)) - engine_.setMonitorEnabled (false); - // P1 explicitly ignores channels 2-12, demo FX chain, and generic FX - // parameters. Future typed graph routing will map their IDs. - juce::ignoreUnused (channel); + const auto valueNumber = static_cast (static_cast (value)); + if (name == "masterGain" && (value.isDouble() || value.isInt())) + engine_.setMasterGainDb (valueNumber); + else if (name == "faderDb" && channel == 1 && (value.isDouble() || value.isInt())) + engine_.setChannelGainDb (valueNumber); + else if (name == "mute" && channel == 1 && value.isBool()) + engine_.setChannelMuted (bool (value)); + } + + void showDeviceSetup() + { + juce::DialogWindow::LaunchOptions opts; + opts.dialogTitle = "AR MIX — ASIO / WASAPI Audio Setup"; + opts.dialogBackgroundColour = juce::Colour (0xff14212a); + auto* selector = new juce::AudioDeviceSelectorComponent ( + engine_.devices(), 1, 2, 1, 2, false, false, false, false); + selector->setSize (720, 560); + opts.content.setOwned (selector); + opts.useNativeTitleBar = true; + opts.resizable = true; + opts.launchAsync(); + } + + void chooseImport() + { + chooser_ = std::make_unique ( + "Import an individual VST3 module or bundle", juce::File{}, "*", true); + chooser_->launchAsync ( + juce::FileBrowserComponent::openMode | + juce::FileBrowserComponent::canSelectFiles | + juce::FileBrowserComponent::canSelectDirectories, + [this] (const juce::FileChooser& f) + { + const auto file = f.getResult(); + if (file == juce::File{}) return; + if (file.hasFileExtension (".dll")) + { + emitNotice ("Legacy VST2 DLL cannot be imported as VST3. Select a .vst3 module.", true); + return; + } + catalog_.importVst3 (file); + emitCatalog(); + }); + } + + void chooseFolder() + { + chooser_ = std::make_unique ( + "Add a VST3 plugin folder to your catalog", juce::File{}, "*", true); + chooser_->launchAsync ( + juce::FileBrowserComponent::openMode | + juce::FileBrowserComponent::canSelectDirectories, + [this] (const juce::FileChooser& f) + { + const auto folder = f.getResult(); + if (folder != juce::File{}) + catalog_.addDirectory (folder); + }); } void onAction (const juce::var& args) { const auto action = args.getProperty ("action", {}).toString(); - if (action == "audioSetup") + const auto value = args.getProperty ("value", {}); + const int slot = static_cast (args.getProperty ("slot", -1)); + + if (action == "audioSetup") showDeviceSetup(); + else if (action == "scanVst3") catalog_.scanDefaults(); + else if (action == "addScanFolder") chooseFolder(); + else if (action == "importVst3") chooseImport(); + else if (action == "addCatalog") { - juce::DialogWindow::LaunchOptions opt; - opt.dialogTitle = "AR MIX — Windows Audio Device Setup"; - opt.dialogBackgroundColour = juce::Colour (0xff14212a); - auto* selector = new juce::AudioDeviceSelectorComponent ( - engine_.devices(), 1, 2, 1, 2, false, false, false, false); - selector->setSize (650, 520); - opt.content.setOwned (selector); - opt.useNativeTitleBar = true; - opt.resizable = true; - opt.launchAsync(); + const auto* plugin = catalog_.find (args.getProperty ("id", {}).toString()); + if (!plugin) + return emitNotice ("Plugin not found in catalog. Rescan your VST3 folders.", true); + editorWindow_.reset(); + const auto error = engine_.addVst3 (plugin->path, plugin->uid, plugin->key()); + if (error.isNotEmpty()) emitNotice (error, true); + else { emitChain(); emitNotice (plugin->name + " inserted into the LIVE FX chain."); } } - else if (action == "chooseVst3") + else if (action == "fxRemove") { - chooser_ = std::make_unique ( - "Load VST3 effect", juce::File{}, "*.vst3", true); - chooser_->launchAsync ( - juce::FileBrowserComponent::openMode | - juce::FileBrowserComponent::canSelectFiles, - [this] (const juce::FileChooser& chooser) - { - const auto file = chooser.getResult(); - if (file == juce::File{}) - return; - const auto error = engine_.loadVst3 (file); - if (error.isNotEmpty()) - juce::AlertWindow::showMessageBoxAsync ( - juce::MessageBoxIconType::WarningIcon, "VST3 Load", error); - }); + editorWindow_.reset(); + if (engine_.removeAt (slot)) emitChain(); + } + else if (action == "fxMove") + { + editorWindow_.reset(); + if (engine_.moveSlot (slot, slot + static_cast (value))) emitChain(); + } + else if (action == "fxBypass") + { + if (value.isBool() && engine_.setBypass (slot, bool (value))) emitChain(); + } + else if (action == "fxEditor") + { + editorWindow_.reset(); + if (auto* processor = engine_.pluginAt (slot)) + { + if (auto* editor = processor->createEditorIfNeeded()) + editorWindow_ = std::make_unique ( + processor->getName(), editor); + else + emitNotice ("This VST3 does not expose a graphical editor.", true); + } + } + else if (action == "monitor" && value.isBool()) + engine_.setMonitorEnabled (bool (value)); + else if (action == "refreshState") + { + emitCatalog(); + emitChain(); } - else if (action == "unloadVst3") - engine_.unloadPlugin(); - else if (action == "monitor" && args.getProperty ("value", {}).isBool()) - engine_.setMonitorEnabled (bool (args.getProperty ("value", false))); - else if (action == "bypass" && args.getProperty ("value", {}).isBool()) - engine_.setBypassed (bool (args.getProperty ("value", false))); } void timerCallback() override { - if (! browser_.ready || ! browser_.isVisible()) - return; + if (!browser_.loaded) return; + + // Audio-device preferences are saved on the message thread only. + if (auto xml = engine_.devices().createStateXml()) + { + const auto text = xml->toString(); + if (text != lastAudioXml_) + { + lastAudioXml_ = text; + settingsDirectory().getChildFile ("audio-devices.xml").replaceWithText (text); + } + } auto state = engine_.status(); if (startupError_.isNotEmpty()) state.getDynamicObject()->setProperty ("error", startupError_); @@ -163,12 +285,11 @@ class ConsoleApp final : public juce::JUCEApplication { public: const juce::String getApplicationName() override { return "AR MIX Studio"; } - const juce::String getApplicationVersion() override { return "0.4.0-p1"; } + const juce::String getApplicationVersion() override { return "0.5.0-native-catalog"; } void initialise (const juce::String&) override { window_ = std::make_unique(); } void shutdown() override { window_.reset(); } private: std::unique_ptr window_; }; -} // namespace - +} START_JUCE_APPLICATION (ConsoleApp) diff --git a/src/PluginCatalog.h b/src/PluginCatalog.h new file mode 100644 index 000000000..55e9084b0 --- /dev/null +++ b/src/PluginCatalog.h @@ -0,0 +1,249 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include +#include + +// All callbacks run on JUCE's message thread. The scanner performs filesystem +// enumeration and plugin metadata discovery on a dedicated non-audio thread. +struct CatalogEntry +{ + juce::String path, name, vendor, category; + int uid = 0; + int variant = 0; + + juce::String key() const { return path + "|" + juce::String (uid) + "|" + juce::String (variant); } + + juce::var toVar() const + { + auto o = std::make_unique(); + o->setProperty ("id", key()); + o->setProperty ("path", path); + o->setProperty ("name", name); + o->setProperty ("vendor", vendor); + o->setProperty ("category", category); + o->setProperty ("uid", uid); + o->setProperty ("variant", variant); + return juce::var (o.release()); + } + + static CatalogEntry fromVar (const juce::var& v) + { + CatalogEntry e; + e.path = v.getProperty ("path", {}).toString(); + e.name = v.getProperty ("name", {}).toString(); + e.vendor = v.getProperty ("vendor", {}).toString(); + e.category = v.getProperty ("category", {}).toString(); + e.uid = static_cast (v.getProperty ("uid", 0)); + e.variant = static_cast (v.getProperty ("variant", 0)); + return e; + } +}; + +class PluginCatalog final +{ +public: + using Callback = std::function; + explicit PluginCatalog (juce::File dataFolder) + : dataFolder_ (std::move (dataFolder)), worker_ (*this) + { + dataFolder_.createDirectory(); + load(); + } + + ~PluginCatalog() + { + alive_.store (false); + worker_.signalThreadShouldExit(); + // Scanning cannot be forcibly cancelled inside a third-party scanner. + // Never detach a worker that still references this object. + worker_.stopThread (-1); + } + + const std::vector& entries() const noexcept { return entries_; } + bool busy() const noexcept { return scanning_.load(); } + juce::String scanMessage() const { return scanMessage_; } + Callback onChanged; + + void addDirectory (const juce::File& folder) + { + if (! folder.isDirectory() || busy()) + return; + const auto p = folder.getFullPathName(); + if (! customFolders_.contains (p)) + { + customFolders_.add (p); + save(); + } + scan ({ p }); + } + + void scanDefaults() + { + juce::VST3PluginFormat format; + juce::StringArray paths; + const auto defaults = format.getDefaultLocationsToSearch(); + for (int i = 0; i < defaults.getNumPaths(); ++i) + paths.addIfNotAlreadyThere (defaults[i].getFullPathName()); + for (const auto& p : customFolders_) + paths.addIfNotAlreadyThere (p); + scan (paths); + } + + // Direct VST3 file/bundle import (no forced recursive system scan). + // Native .dll is legacy VST2 and is deliberately not mislabeled as VST3. + void importVst3 (const juce::File& file) + { + if (busy()) return; + if (! file.exists() || ! file.hasFileExtension (".vst3")) + { + scanMessage_ = "Choose a .vst3 file or bundle. Legacy VST2 .dll is not supported."; + if (onChanged) onChanged(); + return; + } + scan (juce::StringArray { file.getFullPathName() }); + } + + const CatalogEntry* find (const juce::String& id) const + { + for (const auto& entry : entries_) + if (entry.key() == id) + return &entry; + return nullptr; + } + + juce::var snapshot() const + { + auto o = std::make_unique(); + juce::Array list; + for (const auto& entry : entries_) + list.add (entry.toVar()); + o->setProperty ("items", juce::var (list)); + o->setProperty ("scanning", busy()); + o->setProperty ("message", scanMessage_); + o->setProperty ("count", static_cast (entries_.size())); + return juce::var (o.release()); + } + +private: + struct Scanner final : juce::Thread + { + explicit Scanner (PluginCatalog& owner) : juce::Thread ("AR MIX VST3 Scanner"), owner_ (owner) {} + PluginCatalog& owner_; + juce::StringArray requested_; + + void run() override + { + #if JUCE_WINDOWS + const auto hr = CoInitializeEx (nullptr, COINIT_APARTMENTTHREADED); + #endif + std::vector found; + juce::VST3PluginFormat format; + for (const auto& requested : requested_) + { + if (threadShouldExit()) break; + const juce::File file (requested); + juce::StringArray candidates; + if (file.isDirectory() && ! file.hasFileExtension (".vst3")) + { + juce::FileSearchPath search; + search.add (file); + candidates = format.searchPathsForPlugins (search, true, false); + } + else if (file.hasFileExtension (".vst3")) + candidates.add (requested); + + for (const auto& path : candidates) + { + if (threadShouldExit()) break; + if (! format.fileMightContainThisPluginType (path)) continue; + juce::OwnedArray descriptions; + format.findAllTypesForFile (descriptions, path); + for (int i = 0; i < descriptions.size(); ++i) + { + const auto* desc = descriptions[i]; + if (desc == nullptr || desc->isInstrument) continue; + found.push_back ({ desc->fileOrIdentifier, desc->name, + desc->manufacturerName, desc->category, + desc->uniqueId, i }); + } + } + } + #if JUCE_WINDOWS + if (SUCCEEDED (hr)) CoUninitialize(); + #endif + // Completion is delivered by a SafePointer owned by the UI host, + // so destruction cannot dereference the window after shutdown. + juce::MessageManager::callAsync ([&owner = owner_, results = std::move (found)]() mutable + { + if (! owner.alive_.load()) return; + for (const auto& e : results) + { + const auto iter = std::find_if (owner.entries_.begin(), owner.entries_.end(), + [&e] (const CatalogEntry& old) { return old.key() == e.key(); }); + if (iter == owner.entries_.end()) + owner.entries_.push_back (e); + else + *iter = e; + } + std::sort (owner.entries_.begin(), owner.entries_.end(), + [] (const CatalogEntry& a, const CatalogEntry& b) + { return a.name.compareIgnoreCase (b.name) < 0; }); + owner.scanMessage_ = "Scan complete: " + juce::String (results.size()) + " plugin variants inspected"; + owner.scanning_.store (false); + owner.save(); + if (owner.onChanged) owner.onChanged(); + }); + } + }; + + void scan (const juce::StringArray& paths) + { + if (busy()) return; + scanning_.store (true); + scanMessage_ = "Scanning VST3 metadata (background)..."; + if (onChanged) onChanged(); + worker_.requested_ = paths; + worker_.startThread(); + } + + void load() + { + auto json = juce::JSON::parse (dataFolder_.getChildFile ("plugin-catalog.json")); + if (auto* items = json.getProperty ("items", {}).getArray()) + for (const auto& item : *items) + { + auto entry = CatalogEntry::fromVar (item); + if (entry.path.isNotEmpty()) + entries_.push_back (std::move (entry)); + } + if (auto* folders = json.getProperty ("folders", {}).getArray()) + for (const auto& folder : *folders) + customFolders_.addIfNotAlreadyThere (folder.toString()); + scanMessage_ = "Ready - " + juce::String (entries_.size()) + " cached VST3 effects"; + } + + void save() + { + auto o = std::make_unique(); + juce::Array list, folders; + for (const auto& entry : entries_) list.add (entry.toVar()); + for (const auto& folder : customFolders_) folders.add (folder); + o->setProperty ("schemaVersion", 1); + o->setProperty ("items", juce::var (list)); + o->setProperty ("folders", juce::var (folders)); + auto temporary = dataFolder_.getChildFile ("plugin-catalog.json.tmp"); + if (temporary.replaceWithText (juce::JSON::toString (juce::var (o.release()), true))) + temporary.moveFileTo (dataFolder_.getChildFile ("plugin-catalog.json")); + } + + juce::File dataFolder_; + std::vector entries_; + juce::StringArray customFolders_; + std::atomic alive_ { true }, scanning_ { false }; + juce::String scanMessage_ = "Ready"; + Scanner worker_; +}; diff --git a/web/bridge.js b/web/bridge.js index c78ca3bad..de5b776c6 100644 --- a/web/bridge.js +++ b/web/bridge.js @@ -1,74 +1,273 @@ // SPDX-License-Identifier: AGPL-3.0-only -// The standalone HTML still works as a demo. This runs only inside JUCE WebView2. +// Actual JUCE native bridge. This script is loaded only inside the desktop host. +// Never claims the other 11 concept tracks or mock presets are live channels. (() => { const backend = window.__JUCE__?.backend; if (!backend?.emitEvent || !backend?.addEventListener) return; - const send = (action, value) => backend.emitEvent("arMixAction", { action, value }); - const target = document.querySelector(".status-help"); - if (!target) return; - const strip = document.createElement("div"); - strip.id = "nativeP1"; - strip.innerHTML = 'Starting audio...'; - target.replaceChildren(strip); - const style = document.createElement("style"); - style.textContent = ` - #nativeP1{display:flex;align-items:center;gap:5px;white-space:nowrap;font-size:10px;max-width:100%;overflow:auto} - #nativeP1 button{font:inherit;color:#cde5ed;border:1px solid #426273;border-radius:4px;padding:4px 7px; - background:linear-gradient(175deg,#42596b 0%,#233745 42%,#101e29 100%);cursor:pointer} - #nativeP1 button[aria-pressed=true]{background:linear-gradient(#24aadd,#10617d 58%,#063247); - border-color:#71d8f2;color:#fff} - #nativeP1 [data-p1-status]{color:#95b9c6;min-width:110px;overflow:hidden;text-overflow:ellipsis} - .status-help{min-width:0;flex:1} + + const send = (action, more = {}) => backend.emitEvent("arMixAction", {action, ...more}); + const state = {catalog: [], chain: [], scanning: false, message: "Connecting to native host...", + device: {}, filter: "", selectedCategory: "All", monitor: false, error: ""}; + + const escapeHtml = text => String(text ?? "").replace(/[&<>"']/g, c => ( + {"&":"&","<":"<",">":">",'"':""","'":"'"}[c])); + const percent = peak => Math.max(1,Math.min(100,(20*Math.log10(Math.max(1e-6,Number(peak)||0))+60)*100/60)); + const toStatus = text => { + const e = document.querySelector("#nativeDeviceStatus"); + if(e) e.textContent = text; + const footer = document.querySelector("#audioStatus"); + if(footer) footer.textContent = text; + }; + + // The v0.3 cosmetic demo catalog and FX editor are replaced with the REAL + // catalog/chain when running in JUCE. Keep HTML trial standalone unchanged. + const css = document.createElement("style"); + css.textContent = ` + .native-toolbar{display:flex;flex-wrap:wrap;gap:7px;align-items:center} + .native-btn{font:inherit;color:#d6e9ef;padding:8px 12px;border:1px solid #48677a;border-radius:6px; + background:linear-gradient(180deg,#405c70 0%,#243846 47%,#0d1e29 100%);cursor:pointer; + box-shadow:inset 0 1px 1px #93badc70,0 2px 3px #0008} + .native-btn:hover{border-color:#62b8dc} + .native-btn.primary{border-color:#2dbee9;background:linear-gradient(180deg,#4cddff 0%,#0f9fd1 42%,#08688c 100%);color:#042231} + .native-btn.warn{color:#ffd0c9;border-color:#915552} + .native-btn.on{border-color:#4ae3fd;color:#9ceaff;background:linear-gradient(#165b79,#123142)} + .native-panel{padding:16px 18px;max-width:1160px;margin:0 auto;color:#dcecf2;box-sizing:border-box} + .native-hdr{display:flex;justify-content:space-between;gap:15px;align-items:start;padding:6px 0 16px} + .native-hdr h2{font-size:19px;font-weight:500;margin:5px 0} + .native-sub{font-size:12px;color:#8da9b9;line-height:1.6} + .native-grid{display:grid;grid-template-columns:minmax(300px,1fr) minmax(280px,.95fr);gap:14px} + .native-card{background:linear-gradient(160deg,#1e303c,#13222c 75%);border:1px solid #3b5361;border-radius:9px;padding:12px; + box-shadow:inset 0 1px #7fb0ca27,0 7px 18px #0004;min-height:180px} + .native-card h3{font-size:13px;font-weight:550;color:#7fe4fb;margin:2px 0 12px} + .native-nodes{display:flex;flex-direction:column;gap:7px} + .native-node{display:flex;align-items:center;gap:7px;padding:7px 8px;border:1px solid #405a69;border-radius:6px;background:#101e28} + .native-node .node-index{color:#52c9ea;font:12px monospace;width:22px} + .native-node .node-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px} + .native-node .node-text small{display:block;color:#7196a8;font-size:10px;margin-top:3px} + .native-node.is-bypassed{opacity:.55} + .native-node button{padding:5px 7px;font-size:10px;min-width:28px} + .native-search{box-sizing:border-box;display:block;width:100%;font:12px inherit;outline:0;color:#dcecf2; + border:1px solid #4b6b79;background:#0b1923;border-radius:5px;padding:10px;margin-bottom:9px} + .native-category{display:flex;gap:4px;flex-wrap:wrap;margin:7px 0} + .native-category button{padding:5px 10px;font-size:11px} + .native-scroll{max-height:400px;overflow:auto;display:flex;flex-direction:column;gap:6px} + .native-item{display:flex;gap:8px;align-items:center;border:1px solid #324d5a;padding:8px 9px;background:#10232d;border-radius:6px} + .native-item div{min-width:0;flex:1} + .native-item b{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;font-weight:500} + .native-item small{color:#749aab;font-size:10px} + .native-tag{font-size:9px;border:1px solid #3f7a90;padding:3px 5px;border-radius:3px;color:#8ad6ed} + .native-empty{border:1px dashed #3b5361;padding:18px;color:#8fafbc;text-align:center;border-radius:5px;font-size:12px} + .native-status{padding:8px 10px;background:#10212c;border:1px solid #36546b;border-radius:5px;font-size:11px;color:#97bac8} + #nativeP2{display:flex;gap:5px;align-items:center;font-size:10px;white-space:nowrap} + #nativeP2 button{padding:4px 8px;font-size:10px} + #nativeDeviceStatus{color:#a8c4d0;max-width:360px;overflow:hidden;text-overflow:ellipsis} + .status-help{flex:1;min-width:0} + @media(max-width:1150px){.native-grid{grid-template-columns:1fr}.native-hdr{flex-direction:column}} `; - document.head.appendChild(style); - let monitor = false, bypass = false, warned = false; - strip.addEventListener("click", (e) => { - const b = e.target.closest("button[data-p1]"); - if (!b) return; - if (b.dataset.p1 === "setup") send("audioSetup"); - if (b.dataset.p1 === "load") send("chooseVst3"); - if (b.dataset.p1 === "unload") send("unloadVst3"); - if (b.dataset.p1 === "monitor") send("monitor", !monitor); - if (b.dataset.p1 === "bypass") send("bypass", !bypass); - }); + document.head.appendChild(css); + const footer = document.querySelector(".status-help"); + if(footer) footer.innerHTML = `
+ + + + Starting native audio... +
`; - // Actual output level from the native callback. Remaining mock channels - // are forced dark to avoid implying the P1 host has 12 live audio inputs. - function level(peak) { - const db = 20 * Math.log10(Math.max(1e-6, Number(peak) || 0)); - return Math.max(1, Math.min(100, (db + 60) * 100 / 60)); + const workspace = document.querySelector("#rackWorkspace"); + const mixer = document.querySelector("#mixer"); + const currentTab = () => document.querySelector(".nav button.selected")?.dataset.view; + const fxCategories = ["All","Dynamics","EQ","Delay","Reverb","Other"]; + const classFor = item => { + const s = (item.category+" "+item.name).toLowerCase(); + if(/compress|limit|gate|dynam|de.?ess/.test(s)) return "Dynamics"; + if(/eq|equal|filter/.test(s)) return "EQ"; + if(/delay|echo/.test(s)) return "Delay"; + if(/verb|room|hall/.test(s)) return "Reverb"; + return "Other"; + }; + function cardHeader(title,subtitle) { + return `
AR MIX · NATIVE VST3 ENGINE +

${escapeHtml(title)}

${escapeHtml(subtitle)}
`; + } + function renderRack() { + if(!workspace || currentTab()!=="FX RACK") return; + const matches = state.catalog.filter(p => ( + (state.selectedCategory==="All"||classFor(p)===state.selectedCategory) && + ((p.name+" "+p.vendor+" "+p.category).toLowerCase().includes(state.filter.toLowerCase())) + )); + workspace.dataset.nativeRack="1"; + workspace.innerHTML = `
+ ${cardHeader("Live VST3 FX Rack","Input 1 · live stereo chain · plugin order is the real processing order · 8 inserts maximum")} +
+ + + + ${state.catalog.length} plugins · ${escapeHtml(state.message)} +
+
+

ACTIVE PROCESSING CHAIN · ${state.chain.length}/8

+
+
MIC / AUDIO INPUT →
+ ${state.chain.map((p,i)=>`
+ ${String(i+1).padStart(2,"0")} + ${escapeHtml(p.name)}${p.latency||0} samples plugin latency + + + + + +
`).join("")} + ${state.chain.length===0?'
No real effects loaded. Choose a VST3 from the catalog to hear its processing.
':""} +
→ MASTER · ${escapeHtml(state.device.device||"Audio output")}
+
+
Live plugin changes briefly pause audio in this build. Avoid editing a chain during a livestream.
+
+
+

INSTALLED / IMPORTED PLUGIN CATALOG

+ +
${fxCategories.map(c=>``).join("")}
+
${matches.length?matches.slice(0,200).map(p=>`
+ VST3
${escapeHtml(p.name)} + ${escapeHtml(p.vendor||"Unknown developer")} · ${escapeHtml(p.category||"Effect")}
+
`).join("") + : '
No matching VST3. Click RESCAN VST3, ADD PLUGIN FOLDER, or IMPORT VST3 FILE.
'}
+
+
+

Only VST3 modules (.vst3) are supported. Legacy VST2 .dll is not a VST3 file. VST3 plugin editors open in separate native windows.

+
`; } - backend.addEventListener("arMixStatus", (s) => { - monitor = !!s.monitor; - bypass = !!s.bypass; - const mon = strip.querySelector('[data-p1="monitor"]'); - const by = strip.querySelector('[data-p1="bypass"]'); - mon.textContent = monitor ? "MONITOR ON" : "MONITOR OFF"; - mon.setAttribute("aria-pressed", String(monitor)); - by.textContent = bypass ? "BYPASS ON" : "BYPASS OFF"; - by.setAttribute("aria-pressed", String(bypass)); - strip.querySelector("[data-p1-status]").textContent = - s.error ? "ERROR: " + s.error : - (s.connected ? s.driver + " · " + Math.round(s.rate) + "Hz / " + s.buffer + " · " + - (s.plugin || "Dry mic") + " · +" + (s.pluginLatencySamples || 0) + " samples plugin latency" : - "NO AUDIO DEVICE"); - const status = document.getElementById("audioStatus"); - if (status) status.textContent = s.connected - ? "P1 NATIVE · " + (monitor ? "MONITOR ARMED" : "MONITOR MUTED (safe)") + - " · Live VST3: " + (s.plugin || "none") - : "P1 NATIVE · No audio device"; - const p = level(s.peak); - document.querySelectorAll("[data-meter]").forEach((meter) => - meter.style.setProperty("--level", meter.dataset.meter === "0" ? p + "%" : "1%")); - ["masterMeterL","masterMeterR","masterMeterAux"].forEach((id) => { - const el = document.getElementById(id); - if (el) el.style.setProperty("--level", p + "%"); + function renderSetup() { + if(!workspace||currentTab()!=="SETUP") return; + workspace.dataset.nativeSetup="1"; + const d=state.device; + workspace.innerHTML = `
+ ${cardHeader("Windows Audio Setup","Select your ASIO or WASAPI input and output using the native JUCE device selector. Settings are retained after restart.")} +
+

ACTIVE AUDIO DEVICE

+

Driver: ${escapeHtml(d.driver||"Not connected")}
Device: ${escapeHtml(d.device||"Not selected")}
Sample rate: ${Number(d.rate||0).toLocaleString()} Hz · Buffer: ${d.buffer||0} samples

+
+ + +
+

For first test: wired headphones, 48 kHz and 128/256 samples. Start MONITOR OFF. ASIO and WASAPI are not interchangeable with virtual streaming outputs; loopback routing is a separate feature.

+
+
`; + } + function patchMixer() { + if(!mixer) return; + const tracks=mixer.querySelectorAll(".strip"); + tracks.forEach((track,i)=>{ + if(i>0) {track.title="UI preview channel (audio not connected yet)";return;} + const rack=track.querySelector(".rack"); + if(!rack || rack.dataset.liveNative==="1") return; + rack.dataset.liveNative="1"; + rack.innerHTML = state.chain.slice(0,4).map(p=> + `` + ).join("")+``; + }); + } + + let renderPending = false; + function syncView(){ + if(renderPending) return; + renderPending=true; + queueMicrotask(()=>{ + renderPending=false; + if(currentTab()==="FX RACK"){ + if(workspace.dataset.nativeRack!=="1")renderRack(); + } else if(currentTab()==="SETUP"){ + if(workspace.dataset.nativeSetup!=="1")renderSetup(); + } + patchMixer(); }); - const cpu = document.querySelector(".cpu strong"); - if (cpu) cpu.textContent = "P1 LIVE"; - if (!warned && s.error) { - warned = true; - console.warn("AR MIX native audio:", s.error); + } + new MutationObserver(()=>syncView()).observe(workspace,{childList:true}); + new MutationObserver(()=>syncView()).observe(mixer,{childList:true}); + const repaint=()=>{ + if(currentTab()==="FX RACK") renderRack(); + if(currentTab()==="SETUP") renderSetup(); + patchMixer(); + }; + + // Capture native commands before the legacy v0.3 demo handlers. + document.addEventListener("click",e=>{ + const target=e.target.closest("[data-native-action],[data-native-add],[data-native-fx],[data-native-category],[data-go-native-rack],[data-insert]"); + if(!target)return; + if(target.matches("[data-insert]") && currentTab()!=="MIX") return; + e.preventDefault();e.stopImmediatePropagation(); + if(target.hasAttribute("data-go-native-rack")||target.hasAttribute("data-insert")){ + document.querySelector('.nav button[data-view="FX RACK"]')?.click();return; + } + const action=target.dataset.nativeAction; + if(action){ + if(action==="monitor")send("monitor",{value:!state.monitor}); + else send(action); + return; } + if(target.dataset.nativeAdd){send("addCatalog",{id:target.dataset.nativeAdd});return;} + if(target.dataset.nativeCategory){state.selectedCategory=target.dataset.nativeCategory;renderRack();return;} + const fx=target.dataset.nativeFx,slot=Number(target.dataset.slot); + if(fx==="editor")send("fxEditor",{slot}); + if(fx==="remove")send("fxRemove",{slot}); + if(fx==="bypass")send("fxBypass",{slot,value:!state.chain[slot]?.bypass}); + if(fx==="up"||fx==="down")send("fxMove",{slot,value:fx==="up"?-1:1}); + },true); + document.addEventListener("input",e=>{ + if(e.target.id!=="nativeVstSearch")return; + state.filter=e.target.value; + // Keep typing focus and selection while updating only catalog list on + // the next browser task. Full redraw of the search input would break UX. + const input=e.target; + const pos=input.selectionStart; + renderRack(); + const newInput=document.querySelector("#nativeVstSearch"); + newInput?.focus(); + newInput?.setSelectionRange(pos,pos); + },true); + + backend.addEventListener("arMixCatalog",data=>{ + state.catalog=Array.isArray(data.items)?data.items:[]; + state.scanning=!!data.scanning; + state.message=data.message||"Ready"; + repaint(); + }); + backend.addEventListener("arMixChain",nodes=>{ + state.chain=Array.isArray(nodes)?nodes:[]; + repaint(); + }); + backend.addEventListener("arMixNotice",data=>{ + const text=data.text||""; + const toast=document.querySelector("#toast"); + if(toast){ + toast.textContent=text; + toast.classList.add("show"); + setTimeout(()=>toast.classList.remove("show"),3500); + } + if(data.error)console.warn("AR MIX native:",text); + }); + backend.addEventListener("arMixStatus",d=>{ + state.device=d; + state.monitor=!!d.monitor; + const b=document.querySelector('[data-native-action="monitor"]'); + if(b){b.textContent=state.monitor?"MONITOR ON":"MONITOR OFF";b.classList.toggle("on",state.monitor);} + const text=d.error?"AUDIO ERROR: "+d.error: + d.connected?`${d.driver} · ${Math.round(d.rate)} Hz / ${d.buffer} · ${state.chain.length} LIVE VST3 · ${d.latencySamples||0} samples FX latency` + :"NO AUDIO DEVICE · SELECT AUDIO SETUP"; + toStatus(text); + // Only CH1 and master are sourced from a real native audio callback. + const src=percent(d.inputPeak), out=percent(d.peak); + document.querySelectorAll("[data-meter]").forEach(x=> + x.style.setProperty("--level",x.dataset.meter==="0"?src+"%":"1%")); + ["masterMeterL","masterMeterR","masterMeterAux"].forEach(id=>{ + const x=document.getElementById(id); + if(x)x.style.setProperty("--level",out+"%"); + }); + const cpu=document.querySelector(".cpu strong"); + if(cpu)cpu.textContent="NATIVE"; + const statusSetup=document.querySelector("[data-native-setup]"); + if(statusSetup && !document.activeElement?.matches("input"))renderSetup(); }); + // JS bridge may initialise after the initial native push. Explicit sync. + send("refreshState"); + syncView(); })(); From 5baea6dbacb3475fa6d3cecd2b584260d86d02cd Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 06:24:36 +0700 Subject: [PATCH 2/6] fix(p2): scanner lifetime guard, safe JSON field lifetimes and persist catalog updates --- src/PluginCatalog.h | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/PluginCatalog.h b/src/PluginCatalog.h index 55e9084b0..b27c20c2d 100644 --- a/src/PluginCatalog.h +++ b/src/PluginCatalog.h @@ -3,6 +3,9 @@ #include #include #include +#if JUCE_WINDOWS + #include +#endif #include #include #include @@ -57,6 +60,7 @@ class PluginCatalog final ~PluginCatalog() { alive_.store (false); + lifetime_->store (false); worker_.signalThreadShouldExit(); // Scanning cannot be forcibly cancelled inside a third-party scanner. // Never detach a worker that still references this object. @@ -177,9 +181,10 @@ class PluginCatalog final #endif // Completion is delivered by a SafePointer owned by the UI host, // so destruction cannot dereference the window after shutdown. - juce::MessageManager::callAsync ([&owner = owner_, results = std::move (found)]() mutable + auto lifetime = owner_.lifetime_; + juce::MessageManager::callAsync ([&owner = owner_, lifetime, results = std::move (found)]() mutable { - if (! owner.alive_.load()) return; + if (! lifetime->load()) return; for (const auto& e : results) { const auto iter = std::find_if (owner.entries_.begin(), owner.entries_.end(), @@ -213,14 +218,16 @@ class PluginCatalog final void load() { auto json = juce::JSON::parse (dataFolder_.getChildFile ("plugin-catalog.json")); - if (auto* items = json.getProperty ("items", {}).getArray()) + const auto storedItems = json.getProperty ("items", {}); + if (auto* items = storedItems.getArray()) for (const auto& item : *items) { auto entry = CatalogEntry::fromVar (item); if (entry.path.isNotEmpty()) entries_.push_back (std::move (entry)); } - if (auto* folders = json.getProperty ("folders", {}).getArray()) + const auto storedFolders = json.getProperty ("folders", {}); + if (auto* folders = storedFolders.getArray()) for (const auto& folder : *folders) customFolders_.addIfNotAlreadyThere (folder.toString()); scanMessage_ = "Ready - " + juce::String (entries_.size()) + " cached VST3 effects"; @@ -235,15 +242,15 @@ class PluginCatalog final o->setProperty ("schemaVersion", 1); o->setProperty ("items", juce::var (list)); o->setProperty ("folders", juce::var (folders)); - auto temporary = dataFolder_.getChildFile ("plugin-catalog.json.tmp"); - if (temporary.replaceWithText (juce::JSON::toString (juce::var (o.release()), true))) - temporary.moveFileTo (dataFolder_.getChildFile ("plugin-catalog.json")); + dataFolder_.getChildFile ("plugin-catalog.json") + .replaceWithText (juce::JSON::toString (juce::var (o.release()), true)); } juce::File dataFolder_; std::vector entries_; juce::StringArray customFolders_; std::atomic alive_ { true }, scanning_ { false }; + std::shared_ptr> lifetime_ = std::make_shared> (true); juce::String scanMessage_ = "Ready"; Scanner worker_; }; From c96a623e19770f06aff18f2b43460691d2b9efc1 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 06:24:45 +0700 Subject: [PATCH 3/6] fix(ui): regenerate native rack when changing tabs after demo workspace redraw --- web/bridge.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web/bridge.js b/web/bridge.js index de5b776c6..2eaaefc20 100644 --- a/web/bridge.js +++ b/web/bridge.js @@ -174,9 +174,9 @@ queueMicrotask(()=>{ renderPending=false; if(currentTab()==="FX RACK"){ - if(workspace.dataset.nativeRack!=="1")renderRack(); + if(workspace.firstElementChild?.dataset.liveNative!=="1")renderRack(); } else if(currentTab()==="SETUP"){ - if(workspace.dataset.nativeSetup!=="1")renderSetup(); + if(workspace.firstElementChild?.dataset.nativeSetup!=="1")renderSetup(); } patchMixer(); }); From 5d3041ad9da8642bda99237f17d4d7e63fa60f5d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 06:27:42 +0700 Subject: [PATCH 4/6] fix(p2): emit cached catalog after WebView load and coalesce device settings writes --- src/Main.cpp | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 44ca81b7c..f36d0de8b 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -118,6 +118,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer std::unique_ptr chooser_; std::unique_ptr editorWindow_; juce::String startupError_, lastAudioXml_; + bool initialStateSent_ = false; + unsigned int timerTicks_ = 0; void emitNotice (const juce::String& message, bool error = false) { @@ -264,14 +266,23 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer { if (!browser_.loaded) return; - // Audio-device preferences are saved on the message thread only. - if (auto xml = engine_.devices().createStateXml()) + if (!initialStateSent_) { - const auto text = xml->toString(); - if (text != lastAudioXml_) + initialStateSent_ = true; + emitCatalog(); + emitChain(); + } + // Persist configuration off the callback; cap XML serialization to ~3 s. + if (++timerTicks_ % 36 == 0) + { + if (auto xml = engine_.devices().createStateXml()) { - lastAudioXml_ = text; - settingsDirectory().getChildFile ("audio-devices.xml").replaceWithText (text); + const auto text = xml->toString(); + if (text != lastAudioXml_) + { + lastAudioXml_ = text; + settingsDirectory().getChildFile ("audio-devices.xml").replaceWithText (text); + } } } auto state = engine_.status(); From 8650cb6d2fb1e282cfd1c46e34d9f3b4ce6639d4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 06:29:57 +0700 Subject: [PATCH 5/6] fix(p2): wire real master mute to native audio output without auto-arming monitor --- src/LiveAudioEngine.h | 7 +++++-- src/Main.cpp | 2 ++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index a94d08e79..fff597ad7 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -67,6 +67,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if (std::isfinite (value)) channelGain_.store (juce::Decibels::decibelsToGain (juce::jlimit (-60.f, 10.f, value))); } void setChannelMuted (bool value) noexcept { channelMute_.store (value); } + void setMasterMuted (bool value) noexcept { masterMute_.store (value); } int chainSize() const noexcept { return count_; } @@ -184,6 +185,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("rate", d ? d->getCurrentSampleRate() : 0.0); o->setProperty ("buffer", d ? d->getCurrentBufferSizeSamples() : 0); o->setProperty ("monitor", monitor_.load()); + o->setProperty ("masterMute", masterMute_.load()); o->setProperty ("inputPeak", inputPeak_.load()); o->setProperty ("peak", outputPeak_.load()); o->setProperty ("latencySamples", totalLatency_.load()); @@ -199,7 +201,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback int count_ = 0; bool attached_ = false; juce::AudioBuffer scratch_; - std::atomic monitor_ { false }, channelMute_ { false }; + std::atomic monitor_ { false }, channelMute_ { false }, masterMute_ { false }; std::atomic masterGain_ { 1.f }, channelGain_ { 1.f }; std::atomic inputPeak_ { 0.f }, outputPeak_ { 0.f }; std::atomic totalLatency_ { 0 }; @@ -252,7 +254,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback int outputChannels, int samples, const juce::AudioIODeviceCallbackContext&) override { const bool enabled = monitor_.load (std::memory_order_relaxed); - const bool muted = channelMute_.load (std::memory_order_relaxed); + const bool muted = channelMute_.load (std::memory_order_relaxed) + || masterMute_.load (std::memory_order_relaxed); const float gain = masterGain_.load (std::memory_order_relaxed) * channelGain_.load (std::memory_order_relaxed); float inPeak = 0.f, outPeak = 0.f; diff --git a/src/Main.cpp b/src/Main.cpp index f36d0de8b..b2b843807 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -154,6 +154,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer engine_.setChannelGainDb (valueNumber); else if (name == "mute" && channel == 1 && value.isBool()) engine_.setChannelMuted (bool (value)); + else if (name == "masterMute" && value.isBool()) + engine_.setMasterMuted (bool (value)); } void showDeviceSetup() From 9f40fcb795c702f66c2c36839162aa21546f34d6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 06:31:39 +0700 Subject: [PATCH 6/6] perf(p2): lock-free plugin bypass, live-safe FX editing and deduplicated Windows CI --- .github/workflows/p1-windows.yml | 4 ++++ docs/P2_NATIVE_FX_RACK.md | 3 +++ src/LiveAudioEngine.h | 19 +++++++++++++------ src/Main.cpp | 30 ++++++++++++++++++++++++++---- 4 files changed, 46 insertions(+), 10 deletions(-) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 099d359bc..58df495cd 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -5,6 +5,10 @@ on: pull_request: workflow_dispatch: +concurrency: + group: windows-vst3-${{ github.head_ref || github.ref_name }} + cancel-in-progress: true + permissions: contents: read diff --git a/docs/P2_NATIVE_FX_RACK.md b/docs/P2_NATIVE_FX_RACK.md index b4aec8ffc..e98956311 100644 --- a/docs/P2_NATIVE_FX_RACK.md +++ b/docs/P2_NATIVE_FX_RACK.md @@ -32,3 +32,6 @@ - Add/remove/bypass/edit/reorder two real plugins and verify audible routing. - Save/restart audio device settings and verify the same device is selected. - Test repeatedly with headphones, 48 kHz / 128 samples then 64 only after stable result. + +## Live-safe P2 operations +Bypass toggles are atomic and do not detach the audio callback. Scanning plugins and add/remove/reorder are refused when monitoring is enabled, so the singer cannot accidentally force an audio callback restart while live. Turn MONITOR OFF to edit chain structure, then arm monitoring again. The VST3 code itself is third-party; test carefully. diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index fff597ad7..d92afaca3 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -132,7 +132,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback node.name = chosen->name; node.catalogId = catalogId; node.processor = std::move (instance); - slots_[count_++] = std::move (node); + slots_[count_] = std::move (node); + bypassFlags_[count_].store (false, std::memory_order_release); + ++count_; attach(); return {}; } @@ -140,10 +142,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool setBypass (int index, bool value) { if (index < 0 || index >= count_) return false; - // Message-thread writes under a detached callback; no data race. - detach(); + // Message-thread metadata and an atomic value consumed by the audio thread. slots_[index].bypass = value; - attach(); + bypassFlags_[index].store (value, std::memory_order_release); return true; } @@ -156,6 +157,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback for (int i = index; i + 1 < count_; ++i) slots_[i] = std::move (slots_[i + 1]); slots_[--count_] = Slot {}; + for (int i = 0; i < count_; ++i) + bypassFlags_[i].store (slots_[i].bypass, std::memory_order_release); attach(); return true; } @@ -171,6 +174,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback else for (int i = from; i > to; --i) slots_[i] = std::move (slots_[i - 1]); slots_[to] = std::move (moved); + for (int i = 0; i < count_; ++i) + bypassFlags_[i].store (slots_[i].bypass, std::memory_order_release); attach(); return true; } @@ -201,6 +206,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback int count_ = 0; bool attached_ = false; juce::AudioBuffer scratch_; + // Indexed atomic bypass flags: instant RT-safe toggles, no graph detachment. + std::array, maxFx> bypassFlags_ {}; std::atomic monitor_ { false }, channelMute_ { false }, masterMute_ { false }; std::atomic masterGain_ { 1.f }, channelGain_ { 1.f }; std::atomic inputPeak_ { 0.f }, outputPeak_ { 0.f }; @@ -235,7 +242,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback slot.processor->prepareToPlay (d->getCurrentSampleRate(), juce::jmax (32, d->getCurrentBufferSizeSamples())); slot.latency = slot.processor->getLatencySamples(); - if (!slot.bypass) latency += slot.latency; + if (!bypassFlags_[i].load (std::memory_order_relaxed)) latency += slot.latency; } } totalLatency_.store (latency); @@ -280,7 +287,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback for (int fx = 0; fx < count_; ++fx) { auto& slot = slots_[fx]; - if (slot.processor && ! slot.bypass) + if (slot.processor && ! bypassFlags_[fx].load (std::memory_order_relaxed)) slot.processor->processBlock (scratch_, midi); midi.clear(); } diff --git a/src/Main.cpp b/src/Main.cpp index b2b843807..7057f9ce5 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -216,11 +216,25 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer const int slot = static_cast (args.getProperty ("slot", -1)); if (action == "audioSetup") showDeviceSetup(); - else if (action == "scanVst3") catalog_.scanDefaults(); - else if (action == "addScanFolder") chooseFolder(); - else if (action == "importVst3") chooseImport(); + else if (action == "scanVst3") + { + if (engine_.isMonitorEnabled()) emitNotice ("Turn MONITOR OFF before scanning plugins.", true); + else catalog_.scanDefaults(); + } + else if (action == "addScanFolder") + { + if (engine_.isMonitorEnabled()) emitNotice ("Turn MONITOR OFF before scanning plugins.", true); + else chooseFolder(); + } + else if (action == "importVst3") + { + if (engine_.isMonitorEnabled()) emitNotice ("Turn MONITOR OFF before importing plugins.", true); + else chooseImport(); + } else if (action == "addCatalog") { + if (engine_.isMonitorEnabled()) + return emitNotice ("Turn MONITOR OFF before editing the live FX chain.", true); const auto* plugin = catalog_.find (args.getProperty ("id", {}).toString()); if (!plugin) return emitNotice ("Plugin not found in catalog. Rescan your VST3 folders.", true); @@ -231,11 +245,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer } else if (action == "fxRemove") { + if (engine_.isMonitorEnabled()) + return emitNotice ("Turn MONITOR OFF before removing a live FX.", true); editorWindow_.reset(); if (engine_.removeAt (slot)) emitChain(); } else if (action == "fxMove") { + if (engine_.isMonitorEnabled()) + return emitNotice ("Turn MONITOR OFF before reordering live FX.", true); editorWindow_.reset(); if (engine_.moveSlot (slot, slot + static_cast (value))) emitChain(); } @@ -256,7 +274,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer } } else if (action == "monitor" && value.isBool()) - engine_.setMonitorEnabled (bool (value)); + { + if (bool (value) && catalog_.busy()) + emitNotice ("VST3 scan still active. Wait for the scan to finish before enabling monitoring.", true); + else engine_.setMonitorEnabled (bool (value)); + } else if (action == "refreshState") { emitCatalog();