diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 6aa9fd2e2..458be169b 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -1,7 +1,7 @@ name: Windows Native VST3 Host on: push: - branches: [ main, feature/p1-first-sound-windows, feature/p2-native-vst-catalog-fx-rack, feature/p2-daw-workflow-progress, fix/p2-native-output-monitor-diagnostics, fix/p2-realtime-glitch-telemetry-latest-gui, fix/p2-truthful-meter-pan-fx-toggle ] + branches: [ main, feature/p1-first-sound-windows, feature/p2-native-vst-catalog-fx-rack, feature/p2-daw-workflow-progress, fix/p2-native-output-monitor-diagnostics, fix/p2-realtime-glitch-telemetry-latest-gui, fix/p2-truthful-meter-pan-fx-toggle, feature/p2-native-state-presets ] pull_request: workflow_dispatch: @@ -34,6 +34,7 @@ jobs: node --check web/monitor.js node --check web/app.js node --test tests/native_ui_contract_test.mjs + node --test tests/native_preset_contract_test.mjs - name: Configure Windows x64 shell: pwsh run: > @@ -42,7 +43,7 @@ jobs: -DBUILD_TESTING=ON -DJUCE_WEBVIEW2_PACKAGE_LOCATION="${{ github.workspace }}/.deps" - name: Build executable and native RT tests - run: cmake --build build --config Release --target ARMixConsole ARMixRTTests --parallel 2 + run: cmake --build build --config Release --target ARMixConsole ARMixRTTests ARMixPresetTests --parallel 2 - name: Test realtime control primitives run: ctest --test-dir build -C Release --output-on-failure - name: Package native executable @@ -53,13 +54,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/ArSonMix-P2-LiveMeter-Pan-FXToggle.exe" + Copy-Item $exe.FullName "dist/ArSonMix-P2-Native-Presets.exe" Copy-Item README.md "dist/README.md" "P2 experimental: audio routes automatically; use headphones at low level. Only Channel 1 is native. Other strips are inactive previews." | Out-File -FilePath dist/FIRST_SOUND_README.txt -Encoding utf8 - uses: actions/upload-artifact@v4 with: - name: ArSonMix-P2-LiveMeter-Pan-FXToggle-Windows-x64 + name: ArSonMix-P2-Native-Presets-Windows-x64 path: dist/ if-no-files-found: error retention-days: 14 diff --git a/CMakeLists.txt b/CMakeLists.txt index 537820cca..b5ffe4664 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,7 +19,7 @@ juce_add_gui_app(ARMixConsole juce_add_binary_data(ARMixAssets SOURCES web/index.html web/styles.css web/app.js web/bridge.js web/monitor.js) -target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/PluginCatalog.h src/DiagnosticsRecorder.h src/StereoPan.h) +target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/PluginCatalog.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h) target_compile_definitions(ARMixConsole PRIVATE JUCE_WEB_BROWSER=1 JUCE_USE_WIN_WEBVIEW2=1 @@ -33,6 +33,7 @@ target_link_libraries(ARMixConsole PRIVATE juce::juce_gui_extra juce::juce_audio_utils juce::juce_audio_processors + juce::juce_cryptography juce::juce_audio_devices juce::juce_recommended_config_flags juce::juce_recommended_warning_flags) @@ -42,4 +43,10 @@ if(BUILD_TESTING) add_executable(ARMixRTTests tests/realtime_control_test.cpp) target_compile_features(ARMixRTTests PRIVATE cxx_std_20) add_test(NAME RealtimeControlPrimitives COMMAND ARMixRTTests) + juce_add_console_app(ARMixPresetTests PRODUCT_NAME "ArSonMix Native Preset Tests") + target_sources(ARMixPresetTests PRIVATE tests/native_preset_roundtrip_test.cpp src/NativePresetArchive.h) + target_link_libraries(ARMixPresetTests PRIVATE juce::juce_core juce::juce_cryptography + juce::juce_recommended_config_flags) + target_compile_features(ARMixPresetTests PRIVATE cxx_std_20) + add_test(NAME NativePresetZipRoundTrip COMMAND ARMixPresetTests) endif() diff --git a/docs/P2_NATIVE_PRESETS.md b/docs/P2_NATIVE_PRESETS.md new file mode 100644 index 000000000..0423b0778 --- /dev/null +++ b/docs/P2_NATIVE_PRESETS.md @@ -0,0 +1,27 @@ +# P2.4 — Native My Sounds · VST3 binary preset ZIP + +**Source of requirements:** `docs/ARD_AR_MIX_LIVE_FX_HOST_v0.3.md`, sections 2, 7, 8, 8.1, 13. This phase closes the fundamental persistence gap. This is NOT yet complete session/snapshot support or live-safe hot-swap. + +## Completed milestone +- A native `MY SOUNDS` button is available beside Live FX Rack and in the FX Rack toolbar. +- Save `*.armix` files to the native app-data `AR-MIX-Studio/presets/` directory. +- ZIP contains `manifest.json` and `state/00.bin` through `state/07.bin`, captured with JUCE `AudioPluginInstance::getStateInformation` and restored with `setStateInformation` (full vendor-controlled binary state, unlike browser dummy knobs). +- Manifest includes schema/version, Channel 1 input gain/PAN/mute, master gain/mute, ordered stable plugin file/UID/catalog identity, bypass and SHA-256 per plugin-state blob. Output device/driver routing is **not** stored or switched. +- Input validates 8-plugin maximum, 8 MiB per plugin state, ZIP file 72 MiB, 256 KiB manifest, fixed entry names/entry count, finite numeric settings, plugin identity and SHA-256. It never extracts archive entries to arbitrary filesystem paths. +- Recall stages a full new chain and restores each VST3 state before detaching the existing audio callback. If plugin validation/creation/state restoration fails, active chain is left intact. Old processors are retired on the message thread after callback is detached. +- Audio output **must be muted before save or recall** because vendor plugin binary state calls and current graph detach are not guaranteed glitch-free. Output remains muted after recall. The UI explains why instead of silently interrupting a live broadcast. + +## Physical trial on Windows +1. Select input/output in AUDIO SETUP and add ArSonKuPik or another known working VST3. Make an audible adjustment inside the plugin editor. +2. Open SIGNAL CHECK and click MUTE OUTPUT. Open MY SOUNDS, enter `Vocal Test 1`, SAVE SOUND. +3. Edit the plugin parameters to something clearly different or remove the plugin while muted. +4. Open MY SOUNDS and RECALL the saved sound. Check plugin editor state, bypass and processing, fader/PAN/master settings, and insert order. Unmute output manually. +5. Close/restart the EXE and repeat recall. Native presets should persist. Confirm there is no unexpected audio-device switch. +6. Test corrupted archives and missing plugins. The current chain must be retained when validation fails. + +## Deferred ARD work / phase gate +- Smooth live graph switching with a prepared immutable graph + epoch-ack and bounded crossfade, so snapshot changes can be auditioned without output mute. +- Full mixer snapshots including every native channel and sends, A/B preview, durable sessions and autosave journal. +- Dedicated storage worker and out-of-process plugin scanner. ZIP save/restore I/O and vendor plugin preparation currently run on the non-real-time message thread *while output is muted*. +- Multiple independent physical/virtual inputs and real routing/stream output, rather than demo strips. +- Plugin compatibility test matrix / actual Windows xrun & 60-minute soak gates. diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index c717c31b8..fdf5d4ad6 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -3,6 +3,7 @@ #include #include #include "StereoPan.h" +#include "NativePresetArchive.h" #include #include #include @@ -22,7 +23,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback struct Slot { std::unique_ptr processor; - juce::String name, catalogId; + juce::String name, catalogId, path; + int uid = 0; bool bypass = false; int latency = 0; }; @@ -150,6 +152,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback Slot node; node.name = chosen->name; node.catalogId = catalogId; + node.path = filename; + node.uid = uid; node.processor = std::move (instance); slots_[count_] = std::move (node); bypassFlags_[count_].store (false, std::memory_order_release); @@ -158,6 +162,133 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return {}; } + // Capture VST3 vendor binary state, not the legacy WebView2 mock settings. + // Must only run when output is muted (caller enforces): callback is detached + // exactly once, no plugin state methods ever execute on the audio thread. + juce::String captureSnapshot (armix::storage::Snapshot& snapshot) + { + if (!isOutputMuted()) return "Mute hardware output before saving a native preset"; + snapshot.effects.clear(); + snapshot.channelDb = juce::Decibels::gainToDecibels ( + channelGain_.load (std::memory_order_relaxed), -60.f); + snapshot.masterDb = juce::Decibels::gainToDecibels ( + masterGain_.load (std::memory_order_relaxed), -60.f); + snapshot.pan = channelPan_.load (std::memory_order_relaxed); + snapshot.channelMute = channelMute_.load (std::memory_order_relaxed); + snapshot.masterMute = masterMute_.load (std::memory_order_relaxed); + detach(); + juce::String error; + try + { + for (int i = 0; i < count_; ++i) + { + const auto& slot = slots_[i]; + if (!slot.processor) { error = "Invalid active FX slot"; break; } + armix::storage::FxState state; + state.path = slot.path; + state.name = slot.name; + state.catalogId = slot.catalogId; + state.uid = slot.uid; + state.bypass = bypassFlags_[i].load (std::memory_order_acquire); + slot.processor->getStateInformation (state.binary); + if (state.binary.getSize() > armix::storage::NativePresetArchive::maxStateBytes) + { + error = "Plugin state exceeds 8 MB: " + slot.name; + break; + } + snapshot.effects.push_back (std::move (state)); + } + } + catch (...) + { + error = "Plugin threw while saving its state"; + } + attach(); + if (error.isNotEmpty()) snapshot.effects.clear(); + return error; + } + + // Stage every plugin/state BEFORE touching the currently operating plan. + // Caller must mute output; replacing the graph is non-RT, and no old + // processor is destroyed until the callback has been detached. + juce::String restoreSnapshot (const armix::storage::Snapshot& snapshot) + { + if (!isOutputMuted()) + return "Mute hardware output before recalling a native preset"; + if (snapshot.effects.size() > maxFx) return "Too many plugins in preset"; + auto* device = deviceManager_.getCurrentAudioDevice(); + if (!device) return "No active audio device"; + auto* fmt = formats_.getFormat (0); + if (!fmt) return "No VST3 format available"; + const auto rate = device->getCurrentSampleRate(); + const auto buffer = juce::jmax (32, device->getCurrentBufferSizeSamples()); + + std::array staged; + for (int i = 0; i < static_cast (snapshot.effects.size()); ++i) + { + const auto& fx = snapshot.effects[static_cast (i)]; + if (fx.binary.getSize() > armix::storage::NativePresetArchive::maxStateBytes || + !juce::File (fx.path).exists() || !fx.path.endsWithIgnoreCase (".vst3")) + return "Plugin is missing or invalid: " + fx.name; + juce::OwnedArray descriptions; + fmt->findAllTypesForFile (descriptions, fx.path); + juce::PluginDescription* match = nullptr; + for (auto* candidate : descriptions) + if (candidate != nullptr && candidate->uniqueId == fx.uid && + !candidate->isInstrument) + { match = candidate; break; } + if (!match) return "VST3 plugin identity missing: " + fx.name; + + juce::String error; + auto processor = formats_.createPluginInstance (*match, rate, buffer, error); + if (!processor) return "Cannot open preset plugin " + fx.name + ": " + error; + juce::AudioProcessor::BusesLayout layout; + layout.inputBuses.add (juce::AudioChannelSet::stereo()); + layout.outputBuses.add (juce::AudioChannelSet::stereo()); + if (!processor->setBusesLayout (layout)) + return "Unsupported VST3 stereo bus: " + fx.name; + try + { + // State is restored before insertion; live audio still uses the + // old plan until every new instance has finished construction. + processor->prepareToPlay (rate, buffer); + if (fx.binary.getSize() > 0) + processor->setStateInformation ( + fx.binary.getData(), static_cast (fx.binary.getSize())); + } + catch (...) + { + return "Plugin failed to restore its binary state: " + fx.name; + } + Slot slot; + slot.name = match->name; + slot.catalogId = fx.catalogId; + slot.path = fx.path; + slot.uid = fx.uid; + slot.bypass = fx.bypass; + slot.processor = std::move (processor); + staged[static_cast (i)] = std::move (slot); + } + + detach(); + for (int i = 0; i < count_; ++i) + if (slots_[i].processor) slots_[i].processor->releaseResources(); + auto retired = std::move (slots_); + slots_ = std::move (staged); + count_ = static_cast (snapshot.effects.size()); + for (int i = 0; i < maxFx; ++i) + bypassFlags_[i].store (i < count_ ? slots_[i].bypass : false, + std::memory_order_release); + setChannelGainDb (snapshot.channelDb); + setChannelPan (snapshot.pan); + setMasterGainDb (snapshot.masterDb); + setChannelMuted (snapshot.channelMute); + setMasterMuted (snapshot.masterMute); + attach(); + // retired instances are destroyed on the message thread, never callback. + return {}; + } + bool setBypass (int index, bool value) { if (index < 0 || index >= count_) return false; diff --git a/src/Main.cpp b/src/Main.cpp index 10e5f4bd9..8ae996541 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -92,6 +92,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr juce::Colour (0xff101921), allButtons), catalog_ (settingsDirectory()), diagnostics_ (settingsDirectory().getChildFile ("diagnostics")), + presets_ (settingsDirectory().getChildFile ("presets")), browser_ (juce::WebBrowserComponent::Options{} .withBackend (juce::WebBrowserComponent::Options::Backend::webview2) .withWinWebView2Options ( @@ -141,6 +142,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr LiveAudioEngine engine_; PluginCatalog catalog_; DiagnosticsRecorder diagnostics_; + armix::storage::NativePresetArchive presets_; Browser browser_; std::unique_ptr chooser_; std::unique_ptr editorWindow_; @@ -166,6 +168,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr browser_.emitEventIfBrowserIsVisible ("arMixCatalog", catalog_.snapshot()); } + void emitPresets() + { + if (browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixPresets", presets_.list()); + } + void emitChain() { if (browser_.loaded) @@ -283,6 +291,63 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const int slot = static_cast (args.getProperty ("slot", -1)); if (action == "audioSetup") showDeviceSetup(); + else if (action == "presetList") + emitPresets(); + else if (action == "presetSave") + { + const auto name = armix::storage::NativePresetArchive::cleanName ( + args.getProperty ("name", {}).toString()); + if (name.isEmpty()) + return emitNotice ("Choose a valid preset name", true); + if (!engine_.isOutputMuted()) + return emitNotice ("Mute output in SIGNAL CHECK before saving a native sound preset. This avoids interrupting your live performance.", true); + editorWindow_.reset(); + armix::storage::Snapshot snapshot; + snapshot.name = name; + auto error = engine_.captureSnapshot (snapshot); + if (error.isEmpty()) error = presets_.save (snapshot); + if (error.isNotEmpty()) + { + diagnostics_.record ("PRESET_SAVE_FAIL", name + ": " + error); + emitNotice (error, true); + } + else + { + diagnostics_.record ("PRESET_SAVED", name + " (" + juce::String (snapshot.effects.size()) + " VST3)"); + emitPresets(); + emitNotice ("Native VST3 preset saved: " + name); + } + } + else if (action == "presetLoad") + { + const auto name = args.getProperty ("name", {}).toString(); + if (!engine_.isOutputMuted()) + return emitNotice ("Mute output in SIGNAL CHECK before recalling a native sound preset.", true); + editorWindow_.reset(); + armix::storage::Snapshot snapshot; + auto error = presets_.load (name, snapshot); + if (error.isEmpty()) error = engine_.restoreSnapshot (snapshot); + if (error.isNotEmpty()) + { + diagnostics_.record ("PRESET_LOAD_FAIL", name + ": " + error); + emitNotice ("Preset unchanged: " + error, true); + } + else + { + diagnostics_.record ("PRESET_LOADED", name + " (" + juce::String (snapshot.effects.size()) + " VST3)"); + emitChain(); + auto updated = std::make_unique(); + updated->setProperty ("name", name); + updated->setProperty ("channelDb", snapshot.channelDb); + updated->setProperty ("masterDb", snapshot.masterDb); + updated->setProperty ("pan", snapshot.pan * 100.f); + updated->setProperty ("channelMute", snapshot.channelMute); + updated->setProperty ("masterMute", snapshot.masterMute); + if (browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixNativePresetLoaded", juce::var (updated.release())); + emitNotice ("Native sound recalled: " + name + ". Output remains muted until you unmute it."); + } + } else if (action == "openDiagnostics") { const auto file = diagnostics_.getLogFile(); @@ -389,6 +454,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr emitCatalog(); emitScanProgress(); emitChain(); + emitPresets(); } if (catalog_.busy() && timerTicks_ % 3 == 0) emitScanProgress(); diff --git a/src/NativePresetArchive.h b/src/NativePresetArchive.h new file mode 100644 index 000000000..08b007914 --- /dev/null +++ b/src/NativePresetArchive.h @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include + +// P2.4 native VST3-state container. Archive never extracts paths to disk. +// All calls are CONTROL/IO thread only, never made by AudioIODeviceCallback. +namespace armix::storage +{ +struct FxState +{ + juce::String name, path, catalogId; + int uid = 0; + bool bypass = false; + juce::MemoryBlock binary; +}; + +struct Snapshot +{ + juce::String name; + float channelDb = 0.f, pan = 0.f, masterDb = 0.f; + bool channelMute = false, masterMute = false; + std::vector effects; +}; + +class NativePresetArchive final +{ +public: + static constexpr int maxEffects = 8; + static constexpr size_t maxStateBytes = 8 * 1024 * 1024; + static constexpr juce::int64 maxArchiveBytes = 72 * 1024 * 1024; + + explicit NativePresetArchive (juce::File directory) : folder_ (std::move (directory)) + { + folder_.createDirectory(); + } + + static juce::String cleanName (juce::String input) + { + return input.trim().substring (0, 56) + .retainCharacters ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -_"); + } + + juce::File fileFor (const juce::String& name) const + { + return folder_.getChildFile (cleanName (name) + ".armix"); + } + + juce::var list() const + { + juce::Array values; + auto files = folder_.findChildFiles (juce::File::findFiles, false, "*.armix"); + for (const auto& file : files) + { + if (values.size() >= 120) break; + values.add (file.getFileNameWithoutExtension()); + } + return juce::var (values); + } + + // This ZIP is the ARD-specified portable container, not a list of GUI knob labels. + juce::String save (const Snapshot& state) + { + if (state.effects.size() > maxEffects) return "Too many effects in snapshot"; + const auto safe = cleanName (state.name); + if (safe.isEmpty()) return "Use a preset name containing letters or numbers"; + if (!folder_.isDirectory() && folder_.createDirectory().failed()) + return "Preset directory cannot be created"; + + juce::ZipFile::Builder builder; + auto manifest = std::make_unique(); + manifest->setProperty ("format", "arsonmix.native.fx-snapshot"); + manifest->setProperty ("schemaVersion", 1); + manifest->setProperty ("name", safe); + manifest->setProperty ("channelId", "ch-001"); + manifest->setProperty ("channelDb", static_cast (state.channelDb)); + manifest->setProperty ("channelPan", static_cast (state.pan)); + manifest->setProperty ("masterDb", static_cast (state.masterDb)); + manifest->setProperty ("channelMute", state.channelMute); + manifest->setProperty ("masterMute", state.masterMute); + // Hardware output endpoints are intentionally NOT saved or switched. + juce::Array items; + for (int index = 0; index < static_cast (state.effects.size()); ++index) + { + const auto& fx = state.effects[static_cast (index)]; + if (! fx.path.endsWithIgnoreCase (".vst3") || fx.path.length() > 1024 || + fx.binary.getSize() > maxStateBytes || fx.path.isEmpty()) + return "Invalid plugin path or oversized VST3 state in slot " + juce::String (index + 1); + const auto path = "state/" + juce::String (index).paddedLeft ('0', 2) + ".bin"; + auto obj = std::make_unique(); + obj->setProperty ("name", fx.name); + obj->setProperty ("path", fx.path); + obj->setProperty ("catalogId", fx.catalogId); + obj->setProperty ("uid", fx.uid); + obj->setProperty ("bypass", fx.bypass); + obj->setProperty ("statePath", path); + obj->setProperty ("stateBytes", static_cast (fx.binary.getSize())); + obj->setProperty ("sha256", juce::SHA256 (fx.binary).toHexString()); + items.add (juce::var (obj.release())); + builder.addEntry ( + std::make_unique (fx.binary.getData(), fx.binary.getSize(), true), + 0, path, juce::Time::getCurrentTime()); + } + manifest->setProperty ("pluginInstances", juce::var (items)); + const auto json = juce::JSON::toString (juce::var (manifest.release()), true); + if (json.getNumBytesAsUTF8() > 256 * 1024) return "Manifest too large"; + builder.addEntry ( + std::make_unique (json.toRawUTF8(), + static_cast (json.getNumBytesAsUTF8()), true), + 6, "manifest.json", juce::Time::getCurrentTime()); + + juce::TemporaryFile temp (fileFor (safe)); + auto stream = temp.getFile().createOutputStream(); + if (! stream) return "Unable to open temporary preset file"; + if (! builder.writeToStream (*stream, nullptr)) + return "Preset ZIP write failed; original preset untouched"; + stream->flush(); + if (stream->getStatus().failed()) + return "Failed to flush preset to disk"; + stream.reset(); + if (temp.getFile().getSize() > maxArchiveBytes) + return "Preset archive exceeds safety limit"; + if (! temp.overwriteTargetFileWithTemporary()) + return "Could not commit preset file atomically"; + return {}; + } + + juce::String load (const juce::String& requestedName, Snapshot& output) const + { + const auto safe = cleanName (requestedName); + if (safe.isEmpty() || safe != requestedName) return "Invalid preset name"; + const auto file = fileFor (safe); + if (! file.existsAsFile() || file.getSize() > maxArchiveBytes) + return "Preset file missing or above safety limit"; + juce::ZipFile zip (file); + if (zip.getNumEntries() < 1 || zip.getNumEntries() > maxEffects + 1) + return "Invalid preset archive entry count"; + const int manifestIndex = zip.getIndexOfFileName ("manifest.json"); + if (manifestIndex < 0 || !zip.getEntry (manifestIndex) || + zip.getEntry (manifestIndex)->uncompressedSize > 256 * 1024) + return "Preset manifest missing or exceeds 256 KB"; + const auto manifestStream = std::unique_ptr ( + zip.createStreamForEntry (manifestIndex)); + if (!manifestStream) return "Cannot open preset manifest"; + const auto data = manifestStream->readEntireStreamAsString(); + if (data.getNumBytesAsUTF8() > 256 * 1024) return "Manifest exceeds limit"; + const auto manifest = juce::JSON::parse (data); + if (!manifest.isObject() || + manifest.getProperty ("format", {}).toString() != "arsonmix.native.fx-snapshot" || + static_cast (manifest.getProperty ("schemaVersion", 0)) != 1 || + !manifest.getProperty ("pluginInstances", {}).isArray()) + return "Unsupported native preset format"; + auto temp = Snapshot {}; + temp.name = safe; + auto readDb = [&manifest] (const char* key, double minimum, double maximum, float& result) + { + const auto v = manifest.getProperty (key, {}); + if (!v.isDouble() && !v.isInt()) return false; + const auto number = static_cast (v); + if (!std::isfinite (number) || number < minimum || number > maximum) return false; + result = static_cast (number); + return true; + }; + if (!readDb ("channelDb", -60, 10, temp.channelDb) || + !readDb ("masterDb", -60, 10, temp.masterDb) || + !readDb ("channelPan", -1, 1, temp.pan)) + return "Unsafe mixer values in preset"; + const auto m1 = manifest.getProperty ("channelMute", {}); + const auto m2 = manifest.getProperty ("masterMute", {}); + if (!m1.isBool() || !m2.isBool()) return "Invalid mute flags"; + temp.channelMute = static_cast (m1); + temp.masterMute = static_cast (m2); + + const auto entries = manifest.getProperty ("pluginInstances", {}); + const auto* list = entries.getArray(); + if (!list || list->size() > maxEffects || zip.getNumEntries() != list->size() + 1) + return "Preset plugin count mismatch"; + + for (int i = 0; i < list->size(); ++i) + { + const auto& entry = list->getReference (i); + if (!entry.isObject()) return "Invalid preset plugin record"; + auto fx = FxState {}; + fx.name = entry.getProperty ("name", {}).toString(); + fx.path = entry.getProperty ("path", {}).toString(); + fx.catalogId = entry.getProperty ("catalogId", {}).toString(); + const auto vUid = entry.getProperty ("uid", {}); + const auto vBypass = entry.getProperty ("bypass", {}); + if (!vUid.isInt() || !vBypass.isBool() || + !fx.path.endsWithIgnoreCase (".vst3") || fx.path.length() > 1024) + return "Invalid VST3 identity"; + fx.uid = static_cast (vUid); + fx.bypass = static_cast (vBypass); + const auto statePath = "state/" + juce::String (i).paddedLeft ('0', 2) + ".bin"; + if (entry.getProperty ("statePath", {}).toString() != statePath) + return "Unexpected archive state path"; + const int zipIndex = zip.getIndexOfFileName (statePath); + const auto* zipEntry = zipIndex >= 0 ? zip.getEntry (zipIndex) : nullptr; + if (!zipEntry || zipEntry->uncompressedSize < 0 || + zipEntry->uncompressedSize > static_cast (maxStateBytes) || + static_cast (entry.getProperty ("stateBytes", -1)) != zipEntry->uncompressedSize) + return "VST3 state is missing or exceeds safety limit"; + auto input = std::unique_ptr (zip.createStreamForEntry (zipIndex)); + if (!input) return "Unable to read VST3 state"; + input->readIntoMemoryBlock (fx.binary, static_cast (maxStateBytes + 1)); + if (fx.binary.getSize() != static_cast (zipEntry->uncompressedSize) || + !juce::SHA256 (fx.binary).toHexString().equalsIgnoreCase ( + entry.getProperty ("sha256", {}).toString())) + return "VST3 state integrity check failed"; + temp.effects.push_back (std::move (fx)); + } + output = std::move (temp); // transactional: caller sees only validated state + return {}; + } + +private: + juce::File folder_; +}; +} // namespace armix::storage diff --git a/tests/native_preset_contract_test.mjs b/tests/native_preset_contract_test.mjs new file mode 100644 index 000000000..a3e914803 --- /dev/null +++ b/tests/native_preset_contract_test.mjs @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Static guard: the native preset path must never silently fall back to demo +// localStorage or authorize an unmuted VST3 graph mutation. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +const get=p=>readFileSync(p,'utf8'); +const main=get('src/Main.cpp'), engine=get('src/LiveAudioEngine.h'); +const io=get('src/NativePresetArchive.h'), bridge=get('web/bridge.js'); +test('full vendor state is captured/restored by the native host',()=>{ + assert.match(engine,/getStateInformation \(state\.binary\)/); + assert.match(engine,/setStateInformation \(/); + assert.match(engine,/snapshot\.effects\.push_back/); + assert.match(engine,/auto retired = std::move \(slots_\)/); +}); +test('ZIP archive does not extract untrusted paths to disk',()=>{ + assert.match(io,/juce::ZipFile::Builder/); + assert.match(io,/manifest\.json/); + assert.match(io,/juce::SHA256/); + assert.match(io,/maxStateBytes = 8 \* 1024 \* 1024/); + assert.doesNotMatch(io,/uncompressTo|uncompressEntry/); +}); +test('muted-only safety and transactional read',()=>{ + assert.match(main,/!engine_\.isOutputMuted\(\)/); + assert.match(engine,/if \(!isOutputMuted\(\)\)/); + assert.match(io,/output = std::move \(temp\)/); +}); +test('separate native My Sounds not browser-only preset',()=>{ + assert.match(bridge,/data-my-sounds/); + assert.match(bridge,/send\("presetSave",\{name\}\)/); + assert.match(bridge,/send\("presetLoad",\{name\}\)/); + assert.match(bridge,/arMixNativePresetLoaded/); +}); diff --git a/tests/native_preset_roundtrip_test.cpp b/tests/native_preset_roundtrip_test.cpp new file mode 100644 index 000000000..7f77567f0 --- /dev/null +++ b/tests/native_preset_roundtrip_test.cpp @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Runtime test for the actual .armix ZIP implementation, not static text. +#ifdef NDEBUG + #undef NDEBUG +#endif +#include +#include +#include +#include "../src/NativePresetArchive.h" + +int main() +{ + auto folder = juce::File::getSpecialLocation (juce::File::tempDirectory) + .getNonexistentChildFile ("ArSonMixPresetUnit", "", false); + assert (folder.createDirectory().wasOk()); + armix::storage::NativePresetArchive archive (folder); + + armix::storage::Snapshot original; + original.name = "Vocal Session 01"; + original.channelDb = -7.25f; + original.masterDb = -3.5f; + original.pan = .42f; + original.channelMute = true; + original.masterMute = false; + armix::storage::FxState plugin; + plugin.name = "Test FX"; + plugin.path = "C:/Nonexistent/Test FX.vst3"; + plugin.uid = 982314; + plugin.catalogId = "test-fx-982314"; + plugin.bypass = true; + const char bytes[] = { '\x01', '\x00', '\x02', '\x7f', '\x01', '\x12' }; + plugin.binary.append (bytes, sizeof (bytes)); + original.effects.push_back (std::move (plugin)); + const auto error = archive.save (original); + if (error.isNotEmpty()) std::cerr << "SAVE: " << error << "\n"; + assert (error.isEmpty()); + + armix::storage::Snapshot loaded; + const auto loadError = archive.load (original.name, loaded); + if (loadError.isNotEmpty()) std::cerr << "LOAD: " << loadError << "\n"; + assert (loadError.isEmpty()); + assert (loaded.name == original.name); + assert (std::abs (loaded.channelDb - original.channelDb) < 1e-4f); + assert (std::abs (loaded.masterDb - original.masterDb) < 1e-4f); + assert (std::abs (loaded.pan - original.pan) < 1e-4f); + assert (loaded.channelMute && !loaded.masterMute); + assert (loaded.effects.size() == 1); + assert (loaded.effects[0].path == original.effects[0].path); + assert (loaded.effects[0].uid == original.effects[0].uid); + assert (loaded.effects[0].catalogId == original.effects[0].catalogId); + assert (loaded.effects[0].bypass); + assert (loaded.effects[0].binary == original.effects[0].binary); + + // Malformed ZIP must not replace previously validated snapshot state. + const auto existingName = loaded.name; + { + juce::FileOutputStream out (archive.fileFor (original.name)); + assert (out.openedOk()); + assert (out.setPosition (0)); + assert (out.writeByte ('?')); + out.flush(); + } + auto failure = archive.load (original.name, loaded); + assert (failure.isNotEmpty()); + assert (loaded.name == existingName && loaded.effects.size() == 1); + + folder.deleteRecursively(); + std::cout << "PASS: native ZIP round-trip, binary VST state, mixer values, corruption refusal\n"; + return 0; +} diff --git a/web/bridge.js b/web/bridge.js index 33fd2388f..ce7c52e09 100644 --- a/web/bridge.js +++ b/web/bridge.js @@ -11,7 +11,7 @@ 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: "", progress: {active:false,phase:"done",done:0,total:0,found:0,current:""}, adding:false}; + device: {}, presets: [], filter: "", selectedCategory: "All", monitor: false, error: "", progress: {active:false,phase:"done",done:0,total:0,found:0,current:""}, adding:false}; const escapeHtml = text => String(text ?? "").replace(/[&<>"']/g, c => ( {"&":"&","<":"<",">":">",'"':""","'":"'"}[c])); @@ -75,6 +75,7 @@ if(footer) footer.innerHTML = `
+ LIVE AUDIO AUTO-ROUTED Starting native audio...
`; @@ -102,6 +103,7 @@
+ ${state.chain.length}/8 live effects · Real-time processor chain (Channel 1)
@@ -219,8 +221,45 @@ nav.appendChild(b); } } + function renderMySounds(){ + const dlg=document.getElementById("nativeMySounds"); + if(!dlg)return; + const muted=!state.monitor; + dlg.querySelector(".native-dialog-body").innerHTML=` +
+ Native .armix presets save the REAL VST3 binary settings, insert order, + bypass, Channel 1 fader/PAN/mute and master. Other demo channels are NOT included. + Devices and output routing are never changed by recall. +
+
+ ${muted?"OUTPUT MUTED · Save/recall is available." + :"LIVE OUTPUT ACTIVE · Mute output first to protect your performance."} + ${muted?"":''} +
+
+ + +
+
SAVED NATIVE SOUNDS · ${state.presets.length}
+
${state.presets.length? + state.presets.map(n=>`
+ ${escapeHtml(n)}.armix · full vendor VST3 state + +
`).join("") : + '
No native sounds saved. Mute output, then save the current live FX chain.
'} +
`; + dlg.querySelector(".native-dialog-footer").textContent= + "Changing active FX while performing is not seamless yet. Output stays muted after recall. Do not distribute presets containing licensed plugin state without permission."; + } + function openMySounds(){ + renderMySounds(); + showDialog("nativeMySounds"); + send("presetList"); + } function initModals(){ createDialog("nativeFxSelector","Add VST3 Effect"); + createDialog("nativeMySounds","My Sounds · Native Presets",true); createDialog("nativePluginManager","Plugin Manager"); createDialog("nativeAudioSetup","Opening Audio Setup",true); const setup=document.getElementById("nativeAudioSetup"); @@ -300,11 +339,33 @@ // Capture native controls before the legacy v0.3 demo handlers. document.addEventListener("click", function(e){ - const el=e.target.closest("[data-native-action],[data-native-add],[data-native-fx],[data-native-category],[data-go-native-rack],[data-insert],[data-plugin-picker],[data-plugin-manager],[data-close-modal]"); + const el=e.target.closest("[data-native-action],[data-native-add],[data-native-fx],[data-native-category],[data-go-native-rack],[data-insert],[data-plugin-picker],[data-plugin-manager],[data-my-sounds],[data-preset-mute],[data-preset-save],[data-preset-load],[data-close-modal]"); if(!el)return; e.preventDefault();e.stopImmediatePropagation(); if(el.dataset.closeModal){hideDialog(el.dataset.closeModal);return;} + if(el.hasAttribute("data-my-sounds")){openMySounds();return;} + if(el.hasAttribute("data-preset-mute")){ + send("monitor",{value:false});state.monitor=false;renderMySounds();return; + } + if(el.hasAttribute("data-preset-save")){ + const input=document.getElementById("nativePresetName"); + const name=(input?.value||"").trim(); + if(!name)return; + input.disabled=true; + requestAnimationFrame(()=>requestAnimationFrame(()=>{ + send("presetSave",{name}); + input.disabled=false; + })); + return; + } + if(el.hasAttribute("data-preset-load")){ + const name=el.dataset.presetLoad; + if(!name)return; + if(!confirm('Recall native sound "'+name+'"? Current plugin chain will be replaced. Output must remain muted.'))return; + requestAnimationFrame(()=>requestAnimationFrame(()=>send("presetLoad",{name}))); + return; + } if(el.hasAttribute("data-plugin-manager")){ renderManager();showDialog("nativePluginManager");return; } @@ -367,6 +428,31 @@ input?.setSelectionRange(pos,pos); },true); + backend.addEventListener("arMixPresets",items=>{ + state.presets=Array.isArray(items)?items:[]; + const dialog=document.getElementById("nativeMySounds"); + if(dialog&&!dialog.hidden){ + const previous=dialog.querySelector("#nativePresetName")?.value||""; + renderMySounds(); + const input=dialog.querySelector("#nativePresetName"); + if(input)input.value=previous; + } + }); + backend.addEventListener("arMixNativePresetLoaded",d=>{ + // Synchronize the real mixer controls. Do not apply the legacy localStorage + // demo presets as an authoritative source for DSP. + if(typeof channels!=="undefined" && channels[0]){ + channels[0].fader=Number(d.channelDb)||0; + channels[0].pan=Math.round(Number(d.pan)||0); + channels[0].mute=!!d.channelMute; + if(typeof masterGain!=="undefined")masterGain=Number(d.masterDb)||0; + if(typeof masterMute!=="undefined")masterMute=!!d.masterMute; + if(typeof renderMixer==="function")renderMixer(); + if(typeof renderMaster==="function")renderMaster(); + patchMixer(); + } + hideDialog("nativeMySounds"); + }); backend.addEventListener("arMixCatalog",data=>{ state.catalog=Array.isArray(data.items)?data.items:[]; state.scanning=!!data.scanning;