Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(chore) Unify engine config JSON and make the data dir explicit (#201)
rafi61287a4014b2ee7
diff --git a/BUILD.md b/BUILD.mdindex 772d3a7c..e9beb993 100644--- a/BUILD.md+++ b/BUILD.md@@ -26,6 +26,13 @@ existing checkout (and again after a pull that moves it):git submodule update --init --recursive```+## CMake dependencies (CPM)++Small header-only libs are fetched by [CPM](https://github.com/cpm-cmake/CPM.cmake) into the build dir (`_deps`)+from pinned URLs — never vendored. A fresh configure needs network. To reuse downloads+across builds, export `CPM_SOURCE_CACHE=~/.cache/CPM`; for an air-gapped build, override+a package with `-DFETCHCONTENT_SOURCE_DIR_<NAME>=<dir>`.+## Quick start```bashdiff --git a/LICENSES/third-party.md b/LICENSES/third-party.mdindex 2128792c..8b3e9df0 100644--- a/LICENSES/third-party.md+++ b/LICENSES/third-party.md@@ -21,6 +21,8 @@ public domain, or AGPL-compatible copyleft.| LAME | 3.100 | MP3 encoding (export) | **LGPL-2.0-or-later** | ⚠️ cleared with a condition — see note 7 || signalsmith-stretch | vendored | Time-stretch / pitch-shift (clip warping) | MIT | ✅ in use || signalsmith-linear | vendored | FFT / linear DSP primitives | MIT | ✅ in use |+| nlohmann/json | 3.12.0 | `audio.json` / `midi.json` device config (engine) | MIT | ✅ in use — CPM release tarball, fetched to build dir |+| CPM.cmake | v0.43.2 | CMake package manager (build-time only, not linked) | MIT | ✅ in use — downloaded at configure time, never vendored || HIIR (Laurent de Soras) | 1.40 | Oversampling (polyphase halfband IIR) | WTFPL | ✅ in use — see note 4 || Apple CoreAudio / CoreMIDI / AudioToolbox | system | Audio + MIDI I/O (macOS) | system SDK | ✅ in use || Geist / Geist Mono (Vercel) | 1.7.2 | UI and numeric typefaces (`assets/fonts`) | **SIL OFL 1.1** | ✅ in use — see note 5 |diff --git a/src/managed/Nota.App/App.axaml.cs b/src/managed/Nota.App/App.axaml.csindex 444b2655..db53d05a 100644--- a/src/managed/Nota.App/App.axaml.cs+++ b/src/managed/Nota.App/App.axaml.cs@@ -30,6 +30,9 @@ public partial class App : Avalonia.Application{var services = new ServiceCollection();// Engine: one native handle, exposed to the layers through its port.+ // Tell native code where its data lives first, so it never has to guess:+ // audio.json / midi.json and the plugin catalog land next to C# settings.+ NotaEngine.SetDataDir(NotaPaths.DataDir);services.AddSingleton<NotaEngine>();services.AddSingleton<IAudioEngine>(sp => sp.GetRequiredService<NotaEngine>());services.AddSingleton(new EngineBuildInfo(NotaEngine.Version));diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.csindex fda60ea3..ca8afae0 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs@@ -36,6 +36,12 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_engine_destroy")]internal static partial void Destroy(IntPtr engine);+ [LibraryImport(Lib, EntryPoint = "nota_set_data_dir", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial NotaResult SetDataDir(string path);++ [LibraryImport(Lib, EntryPoint = "nota_get_data_dir")]+ internal static partial IntPtr GetDataDir();+[LibraryImport(Lib, EntryPoint = "nota_engine_start")]internal static partial NotaResult Start(IntPtr engine);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.csindex 834caf55..aefc6983 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs@@ -26,6 +26,16 @@ public sealed partial class NotaEngine : IAudioEngine/// <summary>Engine library version, e.g. "0.2.5" (src/native/nota.engine/VERSION).</summary>public static string Version => Marshal.PtrToStringUTF8(NativeMethods.Version()) ?? "?";+ /// <summary>+ /// Tells the native engine where its per-user data lives (audio.json, midi.json,+ /// plugin catalog). Call once at startup with <c>NotaPaths.DataDir</c>, before+ /// creating the engine handle; <c>null</c>/empty resets to auto-detect.+ /// </summary>+ public static void SetDataDir(string? path) => Check(NativeMethods.SetDataDir(path ?? ""));++ /// <summary>Effective native data dir (the override, or what auto-detect resolved).</summary>+ public static string DataDir => Marshal.PtrToStringUTF8(NativeMethods.GetDataDir()) ?? "";+/// <summary>Negotiated output sample rate, or 0 if not started.</summary>public double SampleRate{diff --git a/src/managed/Nota.Infrastructure/NotaPaths.cs b/src/managed/Nota.Infrastructure/NotaPaths.csindex 491d1d01..3c7d3124 100644--- a/src/managed/Nota.Infrastructure/NotaPaths.cs+++ b/src/managed/Nota.Infrastructure/NotaPaths.cs@@ -2,13 +2,13 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//// Single source of truth for Nota's per-user data directory, shared by the-// settings, recovery and logging services (and mirrored by the native engine's-// audio.json / midi.json writers). Platform conventions:+// settings, recovery and logging services. Pushed to native at startup via+// NotaEngine.SetDataDir (nota_set_data_dir); the engine itself never infers+// platform paths — besides this value only NOTA_DATA_DIR (tests) is honoured.+// Platform conventions:// macOS -> ~/Library/Application Support/Nota (unchanged from the mac-only era)// Windows -> %APPDATA%\Nota (Roaming AppData)// Linux -> $XDG_CONFIG_HOME/nota or ~/.config/nota (lowercase, XDG style)-// The native side resolves the same locations (cfgfile::dataDir, the plugin host)-// so config written by C++ and C# lands in one place.namespace Nota.Infrastructure;diff --git a/src/native/nota.engine/.gitignore b/src/native/nota.engine/.gitignorenew file mode 100644index 00000000..53d99899--- /dev/null+++ b/src/native/nota.engine/.gitignore@@ -0,0 +1 @@+/.cache\ No newline at end of filediff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txtindex c32cc5a3..f7367673 100644--- a/src/native/nota.engine/CMakeLists.txt+++ b/src/native/nota.engine/CMakeLists.txt@@ -10,6 +10,27 @@ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_CURRENT_# OBJC/OBJCXX only exist on Apple; enable them conditionally so the Windows# (MSVC/clang-cl) configure doesn't fail looking for an Objective-C compiler.project(nota_engine LANGUAGES C CXX VERSION ${NOTA_ENGINE_VERSION})+++set(CPM_VERSION "v0.43.2")+set(CPM_SHA256 "49a3bef91ceb65bb66d57255e12d1ffd22abc2f6408fa9fe4534c544a2f232aa")+set(CPM_FILE "${CMAKE_BINARY_DIR}/_cpm/CPM.cmake")+if(NOT EXISTS "${CPM_FILE}")+ file(DOWNLOAD+ "https://github.com/cpm-cmake/CPM.cmake/releases/download/${CPM_VERSION}/CPM.cmake"+ "${CPM_FILE}"+ EXPECTED_HASH SHA256=${CPM_SHA256}+ STATUS _cpm_status)+ list(GET _cpm_status 0 _cpm_code)+ if(NOT _cpm_code EQUAL 0)+ message(FATAL_ERROR+ "CPM download failed (network needed on fresh configure). "+ "Set CPM_SOURCE_CACHE or -DFETCHCONTENT_SOURCE_DIR_<NAME>=<dir>. "+ "Status: ${_cpm_status}")+ endif()+endif()+include("${CPM_FILE}")+include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/dependencies.cmake")if(APPLE)enable_language(OBJC)enable_language(OBJCXX)@@ -70,6 +91,8 @@ set(NOTA_ENGINE_SOURCESsrc/nota_engine_audition.cppsrc/Audition.cppsrc/AudioBackendFactory.cpp # platform-selected backend construction+ src/NotaConfigFile.cpp # per-user data dir + atomic file IO (all platforms)+ src/ConfigJson.cpp # audio.json / midi.json via vendored nlohmann/json)# Platform device layer: macOS (CoreAudio/CoreMIDI) vs the shared non-Apple layer@@ -91,7 +114,6 @@ elseif(WIN32 OR (UNIX AND NOT APPLE))src/AudioConfig_miniaudio.cppsrc/MidiInput_rtmidi.cppsrc/MidiConfig_rtmidi.cpp- src/NotaConfigFile.cppsrc/GamepadInput_stub.cpp # v1: macOS-only; reports zero padsvendor/rtmidi/RtMidi.cpp)@@ -161,7 +183,7 @@ add_subdirectory(vendor/flac)# our thin CMakeLists (upstream ships none). Pure C, no nasm/SSE.add_subdirectory(vendor/lame)-target_link_libraries(nota_engine PRIVATE FLAC lame)+target_link_libraries(nota_engine PRIVATE FLAC lame nlohmann_json::nlohmann_json)# --- Plugin hosting (M3) via JUCE -------------------------------------------# JUCE lives ONLY in the pluginhost module; the core engine above staysdiff --git a/src/native/nota.engine/cmake/dependencies.cmake b/src/native/nota.engine/cmake/dependencies.cmakenew file mode 100644index 00000000..cc9db190--- /dev/null+++ b/src/native/nota.engine/cmake/dependencies.cmake@@ -0,0 +1,17 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+#+# CMake dependencies via CPM (general infra, not per-library vendoring).+# Nothing here lands in the repo: CPM fetches each package into the build dir+# (_deps) from a pinned URL + URL_HASH below. To add a dependency, append one+# CPMAddPackage block and its row in LICENSES/third-party.md.++CPMAddPackage(+ NAME nlohmann_json+ VERSION 3.12.0+ URL "https://github.com/nlohmann/json/releases/download/v3.12.0/json.tar.xz"+ URL_HASH "SHA256=42f6e95cad6ec532fd372391373363b62a14af6d771056dbfc86160e6dfff7aa"+ OPTIONS+ "JSON_BuildTests OFF"+ "JSON_Install OFF"+)diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 335223d5..d7b958c5 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -207,6 +207,18 @@ NOTA_API const char* nota_engine_version(void);NOTA_API NotaEngine* nota_engine_create(void);NOTA_API void nota_engine_destroy(NotaEngine* engine);+/* --- Per-user data directory --------------------------------------------+ * Where audio.json / midi.json, the plugin catalog (plugins.xml) and scan+ * paths live. Set once at startup from the managed side (NotaPaths.DataDir)+ * before creating the engine or touching device config; NULL or "" clears the+ * override. The engine never infers platform paths itself — besides the+ * override only NOTA_DATA_DIR (tests) is honoured; unset means persistence is+ * off (loads return defaults, saves are skipped). The directory is created+ * best-effort. get returns the effective directory ("" when unset), UTF-8,+ * owned by the engine, valid until the next call. */+NOTA_API NotaResult nota_set_data_dir(const char* path_utf8);+NOTA_API const char* nota_get_data_dir(void);+/* Open the default CoreAudio output device and start the audio thread. */NOTA_API NotaResult nota_engine_start(NotaEngine* engine);diff --git a/src/native/nota.engine/pluginhost/PluginHost.cpp b/src/native/nota.engine/pluginhost/PluginHost.cppindex 7f1c7f4c..7c378105 100644--- a/src/native/nota.engine/pluginhost/PluginHost.cpp+++ b/src/native/nota.engine/pluginhost/PluginHost.cpp@@ -17,9 +17,7 @@#include "Instrument.h"#include "PluginHostBridge.h"#include "CommandQueue.h" // SpscRingBuffer: message-thread -> audio-thread note injection-#if !defined(__APPLE__) // JUCE_MAC is not defined yet: the JUCE headers come below-#include "NotaConfigFile.h" // cfgfile::dataDir: the Windows/Linux per-user data dir-#endif+#include "NotaConfigFile.h" // cfgfile::dataDir/dataDirOverride: the per-user data dir#include <juce_audio_processors/juce_audio_processors.h>#include <juce_gui_basics/juce_gui_basics.h>@@ -126,15 +124,22 @@ juce::KnownPluginList& catalog() {return list;}-// Per-user Nota data dir (mirrors NotaPaths.DataDir / cfgfile::dataDir):-// macOS -> ~/Library/Application Support/Nota-// Windows -> %APPDATA%\Nota-// Linux -> $XDG_CONFIG_HOME/nota or ~/.config/nota+// Per-user Nota data dir: the explicit override (nota_set_data_dir, i.e.+// NotaPaths.DataDir) or NOTA_DATA_DIR (tests). Unset on Windows/Linux means+// cfgfile::dataDir() is empty and catalog IO becomes a silent no-op — the app+// always sets the override at startup, so this only bites standalone use.juce::File notaSupportDir() {+ // Explicit override from nota_set_data_dir (managed startup) wins everywhere,+ // so the host never diverges from audio.json / midi.json.+ if (std::string over = nota::cfgfile::dataDirOverride(); !over.empty()) {+ juce::File dir{juce::CharPointer_UTF8(over.c_str())};+ dir.createDirectory();+ return dir;+ }// NOTA_DATA_DIR (tests) relocates the catalog + scan paths, like NotaPaths.DataDir.// Needed because on macOS JUCE resolves the home folder via NSHomeDirectory(), not $HOME.- if (const char* over = std::getenv("NOTA_DATA_DIR"); over != nullptr && *over != '\0') {- juce::File dir{juce::CharPointer_UTF8(over)};+ if (const char* env = std::getenv("NOTA_DATA_DIR"); env != nullptr && *env != '\0') {+ juce::File dir{juce::CharPointer_UTF8(env)};dir.createDirectory();return dir;}diff --git a/src/native/nota.engine/src/AudioConfig.mm b/src/native/nota.engine/src/AudioConfig.mmindex 4141038a..93285780 100644--- a/src/native/nota.engine/src/AudioConfig.mm+++ b/src/native/nota.engine/src/AudioConfig.mm@@ -1,10 +1,17 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// macOS device enumeration for AudioConfig.h (CoreAudio). Persistence+// (audio.json) lives in the shared ConfigJson.cpp.#include "AudioConfig.h"+#if defined(__APPLE__)+#import <CoreAudio/CoreAudio.h>-#import <Foundation/Foundation.h>+#import <CoreFoundation/CoreFoundation.h>++#include <vector>namespace nota {namespace {@@ -79,19 +86,6 @@ AudioDeviceID defaultDeviceId(bool inputScope) {return dev;}-// ~/Library/Application Support/Nota/audio.json-NSString* configPath() {- NSArray* dirs = NSSearchPathForDirectoriesInDomains(- NSApplicationSupportDirectory, NSUserDomainMask, YES);- if (dirs.count == 0) return nil;- NSString* dir = [dirs[0] stringByAppendingPathComponent:@"Nota"];- [[NSFileManager defaultManager] createDirectoryAtPath:dir- withIntermediateDirectories:YES- attributes:nil- error:nil];- return [dir stringByAppendingPathComponent:@"audio.json"];-}-} // namespacestd::vector<AudioDeviceInfo> enumerateAudioDevices(bool inputScope) {@@ -140,41 +134,6 @@ uint32_t resolveAudioDeviceId(const std::string& uid, bool inputScope) {return defaultDeviceId(inputScope); // empty or unknown UID -> current default}-AudioConfig loadAudioConfig() {- AudioConfig cfg;- NSString* path = configPath();- if (!path) return cfg;- NSData* data = [NSData dataWithContentsOfFile:path];- if (!data) return cfg;- id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];- if (![json isKindOfClass:[NSDictionary class]]) return cfg;- NSDictionary* d = (NSDictionary*)json;- if (NSString* s = d[@"outputDeviceUid"]; [s isKindOfClass:[NSString class]])- cfg.outputDeviceUid = s.UTF8String;- if (NSString* s = d[@"inputDeviceUid"]; [s isKindOfClass:[NSString class]])- cfg.inputDeviceUid = s.UTF8String;- if (NSNumber* n = d[@"sampleRate"]; [n isKindOfClass:[NSNumber class]])- cfg.sampleRate = n.doubleValue;- if (NSNumber* n = d[@"bufferFrames"]; [n isKindOfClass:[NSNumber class]])- cfg.bufferFrames = n.intValue;- return cfg;-}--void saveAudioConfig(const AudioConfig& cfg) {- NSString* path = configPath();- if (!path) return;- NSDictionary* d = @{- @"outputDeviceUid": [NSString stringWithUTF8String:cfg.outputDeviceUid.c_str()],- @"inputDeviceUid": [NSString stringWithUTF8String:cfg.inputDeviceUid.c_str()],- @"sampleRate": @(cfg.sampleRate),- @"bufferFrames": @(cfg.bufferFrames),- };- NSData* data = [NSJSONSerialization dataWithJSONObject:d- options:NSJSONWritingPrettyPrinted- error:nil];- if (!data) return;- // Atomic write (temp + rename), like ProjectService.Save.- [data writeToFile:path atomically:YES];-}-} // namespace nota++#endif // defined(__APPLE__)diff --git a/src/native/nota.engine/src/AudioConfig_miniaudio.cpp b/src/native/nota.engine/src/AudioConfig_miniaudio.cppindex 8efea52b..af8d17ab 100644--- a/src/native/nota.engine/src/AudioConfig_miniaudio.cpp+++ b/src/native/nota.engine/src/AudioConfig_miniaudio.cpp@@ -1,20 +1,16 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Non-Apple implementation of AudioConfig.h (device enumeration + persisted config)-// for Windows + Linux, mirroring the macOS AudioConfig.mm but backed by miniaudio-// (WASAPI on Windows; PulseAudio/ALSA on Linux). Devices are keyed by a UID string-// derived from the miniaudio ma_device_id (stable for a given endpoint within a-// session). Config persists to <config-dir>/audio.json (NotaConfigFile::dataDir).+// Non-Apple device enumeration for AudioConfig.h (Windows + Linux, miniaudio+// WASAPI / PulseAudio / ALSA). Persistence (audio.json) lives in the shared+// ConfigJson.cpp. Devices are keyed by a UID string derived from the miniaudio+// ma_device_id (stable for a given endpoint within a session).#include "AudioConfig.h"#include "MiniaudioDevices.h"-#include "NotaConfigFile.h"#include "nota_miniaudio.h"#include <cstdio>-#include <cstring>-#include <filesystem>#include <string>#include <vector>@@ -88,33 +84,4 @@ bool notaMiniaudioDeviceIdForIndex(bool inputScope, uint32_t oneBasedIndex, ma_dreturn true;}-AudioConfig loadAudioConfig() {- AudioConfig cfg;- std::string dir = cfgfile::dataDir();- if (dir.empty()) return cfg;- std::string path = (std::filesystem::path(dir) / "audio.json").string();- std::string json = cfgfile::readFile(path);- if (json.empty()) return cfg;- cfgfile::jsonGetString(json, "outputDeviceUid", cfg.outputDeviceUid);- cfgfile::jsonGetString(json, "inputDeviceUid", cfg.inputDeviceUid);- double sr = 0.0; if (cfgfile::jsonGetNumber(json, "sampleRate", sr)) cfg.sampleRate = sr;- double bf = 0.0; if (cfgfile::jsonGetNumber(json, "bufferFrames", bf)) cfg.bufferFrames = static_cast<int32_t>(bf);- double we = 0.0; if (cfgfile::jsonGetNumber(json, "wasapiExclusive", we) && we != 0.0) cfg.wasapiExclusive = true;- return cfg;-}--void saveAudioConfig(const AudioConfig& cfg) {- std::string dir = cfgfile::dataDir();- if (dir.empty()) return;- std::string json = "{\n";- json += " \"outputDeviceUid\": \"" + cfgfile::jsonEscape(cfg.outputDeviceUid) + "\",\n";- json += " \"inputDeviceUid\": \"" + cfgfile::jsonEscape(cfg.inputDeviceUid) + "\",\n";- json += " \"sampleRate\": " + std::to_string(cfg.sampleRate) + ",\n";- json += " \"bufferFrames\": " + std::to_string(cfg.bufferFrames) + ",\n";- json += " \"wasapiExclusive\": " + std::string(cfg.wasapiExclusive ? "true" : "false") + "\n";- json += "}\n";- std::string path = (std::filesystem::path(dir) / "audio.json").string();- cfgfile::writeFileAtomic(path, json);-}-} // namespace notadiff --git a/src/native/nota.engine/src/ConfigJson.cpp b/src/native/nota.engine/src/ConfigJson.cppnew file mode 100644index 00000000..6a207604--- /dev/null+++ b/src/native/nota.engine/src/ConfigJson.cpp@@ -0,0 +1,114 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Single JSON implementation for the tiny engine config files (audio.json /+// midi.json) on every platform. Previously macOS used NSJSONSerialization while+// Windows/Linux hand-rolled string-concat + substring parsing, which diverged+// (missing keys, bool-vs-0/1). Now both go through the vendored nlohmann/json.+// Runs on the message thread only (file I/O); never on the audio thread (AR-6).++#include "AudioConfig.h"+#include "MidiConfig.h"+#include "NotaConfigFile.h"++#include <nlohmann/json.hpp>++#include <algorithm>+#include <filesystem>++namespace nota {+namespace {++using nlohmann::json;++bool getBoolTolerant(const json& j, const char* key, bool fallback) {+ auto it = j.find(key);+ if (it == j.end()) return fallback;+ if (it->is_boolean()) return it->get<bool>();+ if (it->is_number()) return *it != 0;+ return fallback;+}++double getNumberTolerant(const json& j, const char* key, double fallback) {+ auto it = j.find(key);+ if (it == j.end()) return fallback;+ if (it->is_number()) return it->get<double>();+ if (it->is_boolean()) return it->get<bool>() ? 1.0 : 0.0;+ return fallback;+}++std::string getStringTolerant(const json& j, const char* key) {+ auto it = j.find(key);+ if (it == j.end()) return {};+ if (it->is_string()) return it->get<std::string>();+ return {};+}++} // namespace++AudioConfig loadAudioConfig() {+ AudioConfig cfg;+ std::string dir = cfgfile::dataDir();+ if (dir.empty()) return cfg;+ std::string text = cfgfile::readFile((std::filesystem::path(dir) / "audio.json").string());+ if (text.empty()) return cfg;+ try {+ json j = json::parse(text);+ if (!j.is_object()) return cfg;+ cfg.outputDeviceUid = getStringTolerant(j, "outputDeviceUid");+ cfg.inputDeviceUid = getStringTolerant(j, "inputDeviceUid");+ cfg.sampleRate = getNumberTolerant(j, "sampleRate", 0.0);+ cfg.bufferFrames = static_cast<int32_t>(getNumberTolerant(j, "bufferFrames", 0.0));+ cfg.wasapiExclusive = getBoolTolerant(j, "wasapiExclusive", false);+ } catch (...) {+ // Corrupt file -> defaults, like before.+ }+ return cfg;+}++void saveAudioConfig(const AudioConfig& cfg) {+ std::string dir = cfgfile::dataDir();+ if (dir.empty()) return;+ json j;+ j["outputDeviceUid"] = cfg.outputDeviceUid;+ j["inputDeviceUid"] = cfg.inputDeviceUid;+ j["sampleRate"] = cfg.sampleRate;+ j["bufferFrames"] = cfg.bufferFrames;+ j["wasapiExclusive"] = cfg.wasapiExclusive;+ cfgfile::writeFileAtomic((std::filesystem::path(dir) / "audio.json").string(), j.dump(2) + "\n");+}++MidiConfig loadMidiConfig() {+ MidiConfig cfg;+ std::string dir = cfgfile::dataDir();+ if (dir.empty()) return cfg;+ std::string text = cfgfile::readFile((std::filesystem::path(dir) / "midi.json").string());+ if (text.empty()) return cfg;+ try {+ json j = json::parse(text);+ if (!j.is_object()) return cfg;+ auto it = j.find("disabledInputUids");+ if (it != j.end() && it->is_array()) {+ for (const auto& el : *it)+ if (el.is_string())+ cfg.disabledInputUids.push_back(el.get<std::string>());+ }+ cfg.mpe = getBoolTolerant(j, "mpe", true);+ double bend = getNumberTolerant(j, "mpeBendRange", 48.0);+ cfg.mpeBendRange = std::clamp(static_cast<int32_t>(bend), 1, 96);+ } catch (...) {+ }+ return cfg;+}++void saveMidiConfig(const MidiConfig& cfg) {+ std::string dir = cfgfile::dataDir();+ if (dir.empty()) return;+ json j;+ j["disabledInputUids"] = cfg.disabledInputUids;+ j["mpe"] = cfg.mpe;+ j["mpeBendRange"] = cfg.mpeBendRange;+ cfgfile::writeFileAtomic((std::filesystem::path(dir) / "midi.json").string(), j.dump(2) + "\n");+}++} // namespace notadiff --git a/src/native/nota.engine/src/CoreAudioBackend.mm b/src/native/nota.engine/src/CoreAudioBackend.mmindex 8515a761..2feca4d2 100644--- a/src/native/nota.engine/src/CoreAudioBackend.mm+++ b/src/native/nota.engine/src/CoreAudioBackend.mm@@ -3,6 +3,9 @@#include "CoreAudioBackend.h"++#if defined(__APPLE__)+#import <AudioToolbox/AudioToolbox.h>#import <CoreAudio/CoreAudio.h>@@ -236,3 +239,5 @@ void CoreAudioBackend::stop() {}} // namespace nota++#endif // defined(__APPLE__)diff --git a/src/native/nota.engine/src/CoreAudioInput.mm b/src/native/nota.engine/src/CoreAudioInput.mmindex 774171f1..0701ae70 100644--- a/src/native/nota.engine/src/CoreAudioInput.mm+++ b/src/native/nota.engine/src/CoreAudioInput.mm@@ -3,6 +3,8 @@#include "CoreAudioInput.h"+#if defined(__APPLE__)+#import <AudioToolbox/AudioToolbox.h>#import <CoreAudio/CoreAudio.h>@@ -138,3 +140,5 @@ void CoreAudioInput::stop() {}} // namespace nota++#endif // defined(__APPLE__)diff --git a/src/native/nota.engine/src/GamepadInput.mm b/src/native/nota.engine/src/GamepadInput.mmindex 050c37e2..c880b27b 100644--- a/src/native/nota.engine/src/GamepadInput.mm+++ b/src/native/nota.engine/src/GamepadInput.mm@@ -8,6 +8,8 @@#include "GamepadInput.h"#include "CommandQueue.h" // SpscRingBuffer+#if defined(__APPLE__)+#import <GameController/GameController.h>#import <Foundation/Foundation.h>@@ -246,3 +248,5 @@ int32_t GamepadInput::pollEvents(ButtonEvent* out, int32_t max) {}} // namespace nota++#endif // defined(__APPLE__)diff --git a/src/native/nota.engine/src/MidiConfig.mm b/src/native/nota.engine/src/MidiConfig.mmindex 7cc1b86f..e15f7cb3 100644--- a/src/native/nota.engine/src/MidiConfig.mm+++ b/src/native/nota.engine/src/MidiConfig.mm@@ -1,12 +1,18 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// macOS device enumeration for MidiConfig.h (CoreMIDI). Persistence+// (midi.json) lives in the shared ConfigJson.cpp.#include "MidiConfig.h"#include <algorithm>+#include <string>++#if defined(__APPLE__)#import <CoreMIDI/CoreMIDI.h>-#import <Foundation/Foundation.h>+#import <CoreFoundation/CoreFoundation.h>namespace nota {namespace {@@ -34,19 +40,6 @@ std::string endpointDisplayName(MIDIEndpointRef ep) {return out;}-// ~/Library/Application Support/Nota/midi.json-NSString* configPath() {- NSArray* dirs = NSSearchPathForDirectoriesInDomains(- NSApplicationSupportDirectory, NSUserDomainMask, YES);- if (dirs.count == 0) return nil;- NSString* dir = [dirs[0] stringByAppendingPathComponent:@"Nota"];- [[NSFileManager defaultManager] createDirectoryAtPath:dir- withIntermediateDirectories:YES- attributes:nil- error:nil];- return [dir stringByAppendingPathComponent:@"midi.json"];-}-} // namespacestd::string midiUidForEndpoint(uint32_t endpoint) {@@ -73,40 +66,6 @@ std::vector<MidiDeviceInfo> enumerateMidiInputs() {return out;}-MidiConfig loadMidiConfig() {- MidiConfig cfg;- NSString* path = configPath();- if (!path) return cfg;- NSData* data = [NSData dataWithContentsOfFile:path];- if (!data) return cfg;- id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];- if (![json isKindOfClass:[NSDictionary class]]) return cfg;- NSDictionary* d = (NSDictionary*)json;- if (NSArray* arr = d[@"disabledInputUids"]; [arr isKindOfClass:[NSArray class]]) {- for (id item in arr)- if ([item isKindOfClass:[NSString class]])- cfg.disabledInputUids.push_back(((NSString*)item).UTF8String);- }- if (NSNumber* m = d[@"mpe"]; [m isKindOfClass:[NSNumber class]]) cfg.mpe = m.boolValue;- if (NSNumber* r = d[@"mpeBendRange"]; [r isKindOfClass:[NSNumber class]])- cfg.mpeBendRange = std::clamp(r.intValue, 1, 96);- return cfg;-}--void saveMidiConfig(const MidiConfig& cfg) {- NSString* path = configPath();- if (!path) return;- NSMutableArray* arr = [NSMutableArray arrayWithCapacity:cfg.disabledInputUids.size()];- for (const auto& uid : cfg.disabledInputUids)- [arr addObject:[NSString stringWithUTF8String:uid.c_str()]];- NSDictionary* d = @{ @"disabledInputUids": arr,- @"mpe": @(cfg.mpe),- @"mpeBendRange": @(cfg.mpeBendRange) };- NSData* data = [NSJSONSerialization dataWithJSONObject:d- options:NSJSONWritingPrettyPrinted- error:nil];- if (!data) return;- [data writeToFile:path atomically:YES];-}-} // namespace nota++#endif // defined(__APPLE__)diff --git a/src/native/nota.engine/src/MidiConfig_rtmidi.cpp b/src/native/nota.engine/src/MidiConfig_rtmidi.cppindex 52f2d921..955aa789 100644--- a/src/native/nota.engine/src/MidiConfig_rtmidi.cpp+++ b/src/native/nota.engine/src/MidiConfig_rtmidi.cpp@@ -1,20 +1,15 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Non-Apple implementation of MidiConfig.h for Windows + Linux, mirroring the macOS-// MidiConfig.mm but backed by RtMidi (WinMM on Windows; ALSA sequencer on Linux).+// Non-Apple device enumeration for MidiConfig.h (Windows + Linux, RtMidi+// WinMM / ALSA). Persistence (midi.json) lives in the shared ConfigJson.cpp.// RtMidi exposes no numeric unique id, so the port's display name serves as the// stable UID (a documented v1 limitation: two inputs with identical names collide).-// Config persists to <config-dir>/midi.json (NotaConfigFile::dataDir).#include "MidiConfig.h"-#include "NotaConfigFile.h"#include "rtmidi/RtMidi.h"-#include <algorithm>-#include <filesystem>-#include <memory>#include <string>namespace nota {@@ -49,33 +44,4 @@ std::vector<MidiDeviceInfo> enumerateMidiInputs() {return out;}-MidiConfig loadMidiConfig() {- MidiConfig cfg;- std::string dir = cfgfile::dataDir();- if (dir.empty()) return cfg;- std::string path = (std::filesystem::path(dir) / "midi.json").string();- std::string json = cfgfile::readFile(path);- if (json.empty()) return cfg;- cfgfile::jsonGetStringArray(json, "disabledInputUids", cfg.disabledInputUids);- double v = 0.0;- if (cfgfile::jsonGetNumber(json, "mpe", v)) cfg.mpe = v != 0.0;- if (cfgfile::jsonGetNumber(json, "mpeBendRange", v)) cfg.mpeBendRange = std::clamp(static_cast<int32_t>(v), 1, 96);- return cfg;-}--void saveMidiConfig(const MidiConfig& cfg) {- std::string dir = cfgfile::dataDir();- if (dir.empty()) return;- std::string json = "{\n \"disabledInputUids\": [";- for (size_t i = 0; i < cfg.disabledInputUids.size(); ++i) {- if (i) json += ",";- json += "\n \"" + cfgfile::jsonEscape(cfg.disabledInputUids[i]) + "\"";- }- json += cfg.disabledInputUids.empty() ? "]," : "\n ],";- json += "\n \"mpe\": " + std::string(cfg.mpe ? "1" : "0");- json += ",\n \"mpeBendRange\": " + std::to_string(cfg.mpeBendRange) + "\n}\n";- std::string path = (std::filesystem::path(dir) / "midi.json").string();- cfgfile::writeFileAtomic(path, json);-}-} // namespace notadiff --git a/src/native/nota.engine/src/MidiInput.mm b/src/native/nota.engine/src/MidiInput.mmindex 7281a2aa..025d5f00 100644--- a/src/native/nota.engine/src/MidiInput.mm+++ b/src/native/nota.engine/src/MidiInput.mm@@ -4,6 +4,8 @@#include "MidiInput.h"#include "MidiConfig.h"+#if defined(__APPLE__)+#import <CoreMIDI/CoreMIDI.h>#include <algorithm>@@ -90,3 +92,5 @@ void MidiInput::close() {} // namespace nota#pragma clang diagnostic pop++#endif // defined(__APPLE__)diff --git a/src/native/nota.engine/src/NotaConfigFile.cpp b/src/native/nota.engine/src/NotaConfigFile.cppindex 2074ce6e..b3a9f10a 100644--- a/src/native/nota.engine/src/NotaConfigFile.cpp+++ b/src/native/nota.engine/src/NotaConfigFile.cpp@@ -4,134 +4,48 @@#include "NotaConfigFile.h"#include <cstdlib>-#include <cstdio>#include <filesystem>#include <fstream>+#include <mutex>#include <sstream>namespace nota::cfgfile {namespace {-// Skip whitespace starting at pos; returns index of first non-ws (or npos-safe end).-size_t skipWs(const std::string& s, size_t pos) {- while (pos < s.size() && (s[pos] == ' ' || s[pos] == '\t' || s[pos] == '\n' || s[pos] == '\r'))- ++pos;- return pos;-}+std::mutex g_dataDirMutex;+std::string g_dataDirOverride;-// Parse a JSON string literal whose opening quote is at s[pos] == '"'.-// On success sets out to the unescaped value and pos to just past the closing quote.-bool parseString(const std::string& s, size_t& pos, std::string& out) {- if (pos >= s.size() || s[pos] != '"') return false;- ++pos;- out.clear();- while (pos < s.size()) {- char c = s[pos++];- if (c == '"') return true;- if (c == '\\' && pos < s.size()) {- char e = s[pos++];- switch (e) {- case '"': out.push_back('"'); break;- case '\\': out.push_back('\\'); break;- case '/': out.push_back('/'); break;- case 'b': out.push_back('\b'); break;- case 'f': out.push_back('\f'); break;- case 'n': out.push_back('\n'); break;- case 'r': out.push_back('\r'); break;- case 't': out.push_back('\t'); break;- case 'u': {- if (pos + 4 > s.size()) return false;- unsigned code = 0;- for (int i = 0; i < 4; ++i) {- char h = s[pos++];- code <<= 4;- if (h >= '0' && h <= '9') code |= unsigned(h - '0');- else if (h >= 'a' && h <= 'f') code |= unsigned(h - 'a' + 10);- else if (h >= 'A' && h <= 'F') code |= unsigned(h - 'A' + 10);- else return false;- }- // Minimal UTF-8 encode of the BMP code point (config ids are ASCII/BMP).- if (code < 0x80) out.push_back(char(code));- else if (code < 0x800) {- out.push_back(char(0xC0 | (code >> 6)));- out.push_back(char(0x80 | (code & 0x3F)));- } else {- out.push_back(char(0xE0 | (code >> 12)));- out.push_back(char(0x80 | ((code >> 6) & 0x3F)));- out.push_back(char(0x80 | (code & 0x3F)));- }- break;- }- default: out.push_back(e); break;- }- } else {- out.push_back(c);- }- }- return false; // unterminated-}+} // namespace-// Find the value position just after `"key" :` at the top level. Returns npos if-// not found. (Sufficient for our flat one-object config files.)-size_t findValue(const std::string& json, const std::string& key) {- std::string needle = "\"" + key + "\"";- size_t k = json.find(needle);- if (k == std::string::npos) return std::string::npos;- size_t p = skipWs(json, k + needle.size());- if (p >= json.size() || json[p] != ':') return std::string::npos;- return skipWs(json, p + 1);+void setDataDirOverride(const std::string& dir) {+ std::lock_guard<std::mutex> lock(g_dataDirMutex);+ g_dataDirOverride = dir;}-#if !defined(_WIN32)-// Earlier engine builds wrote audio.json / midi.json / plugins.xml / scanpaths.txt to-// <root>/Nota while the managed side used <root>/nota. Move what is there into the one-// folder, never overwriting, and drop the old folder once it is empty. Best-effort.-void migrateLegacyDir(const std::filesystem::path& legacy, const std::filesystem::path& dir) {- std::error_code ec;- if (!std::filesystem::is_directory(legacy, ec)) return;- if (std::filesystem::equivalent(legacy, dir, ec)) return; // case-insensitive filesystem- for (const auto& entry : std::filesystem::directory_iterator(legacy, ec)) {- auto target = dir / entry.path().filename();- if (!std::filesystem::exists(target, ec))- std::filesystem::rename(entry.path(), target, ec);- }- std::filesystem::remove(legacy, ec); // only succeeds if empty+std::string dataDirOverride() {+ std::lock_guard<std::mutex> lock(g_dataDirMutex);+ return g_dataDirOverride;}-#endif--} // namespacestd::string dataDir() {- // NOTA_DATA_DIR (tests) relocates the data root, like NotaPaths.DataDir.- if (const char* over = std::getenv("NOTA_DATA_DIR"); over && *over) {+ // The engine never guesses platform paths: the app tells it once via+ // nota_set_data_dir (NotaPaths.DataDir), tests via NOTA_DATA_DIR.+ // Unset (empty) means config persistence is off: loads return defaults,+ // saves and the plugin catalog are skipped.+ {+ std::lock_guard<std::mutex> lock(g_dataDirMutex);+ if (!g_dataDirOverride.empty()) {+ std::error_code ec;+ std::filesystem::create_directories(g_dataDirOverride, ec);+ return g_dataDirOverride;+ }+ }+ if (const char* env = std::getenv("NOTA_DATA_DIR"); env && *env) {std::error_code ec;- std::filesystem::create_directories(over, ec);- return over;+ std::filesystem::create_directories(env, ec);+ return env;}- // Resolve the per-user config root, then append the app folder — mirrors- // NotaPaths.DataDir on the managed side. Windows: %APPDATA%\Nota.- // Linux: $XDG_CONFIG_HOME, else $HOME/.config (XDG Base Directory spec), + "nota".- std::filesystem::path root;-#if defined(_WIN32)- if (const char* appdata = std::getenv("APPDATA"); appdata && *appdata)- root = appdata;- if (root.empty()) return {};- std::filesystem::path dir = root / "Nota";-#else- if (const char* xdg = std::getenv("XDG_CONFIG_HOME"); xdg && *xdg)- root = xdg;- else if (const char* home = std::getenv("HOME"); home && *home)- root = std::filesystem::path(home) / ".config";- if (root.empty()) return {};- std::filesystem::path dir = root / "nota";-#endif- std::error_code ec;- std::filesystem::create_directories(dir, ec);-#if !defined(_WIN32)- static const bool migrated = (migrateLegacyDir(root / "Nota", dir), true);- (void)migrated;-#endif- return dir.string();+ return {};}std::string readFile(const std::string& path) {@@ -160,66 +74,4 @@ bool writeFileAtomic(const std::string& path, const std::string& content) {return !ec;}-std::string jsonEscape(const std::string& s) {- std::string out;- out.reserve(s.size() + 8);- for (char c : s) {- switch (c) {- case '"': out += "\\\""; break;- case '\\': out += "\\\\"; break;- case '\b': out += "\\b"; break;- case '\f': out += "\\f"; break;- case '\n': out += "\\n"; break;- case '\r': out += "\\r"; break;- case '\t': out += "\\t"; break;- default:- if (static_cast<unsigned char>(c) < 0x20) {- char buf[8];- std::snprintf(buf, sizeof(buf), "\\u%04x", c & 0xFF);- out += buf;- } else {- out.push_back(c);- }- }- }- return out;-}--bool jsonGetString(const std::string& json, const std::string& key, std::string& out) {- size_t p = findValue(json, key);- if (p == std::string::npos) return false;- return parseString(json, p, out);-}--bool jsonGetNumber(const std::string& json, const std::string& key, double& out) {- size_t p = findValue(json, key);- if (p == std::string::npos) return false;- try {- size_t consumed = 0;- out = std::stod(json.substr(p), &consumed);- return consumed > 0;- } catch (...) {- return false;- }-}--bool jsonGetStringArray(const std::string& json, const std::string& key,- std::vector<std::string>& out) {- size_t p = findValue(json, key);- if (p == std::string::npos) return false;- if (p >= json.size() || json[p] != '[') return false;- p = skipWs(json, p + 1);- if (p < json.size() && json[p] == ']') return true; // empty array- while (p < json.size()) {- std::string v;- if (!parseString(json, p, v)) return false;- out.push_back(std::move(v));- p = skipWs(json, p);- if (p < json.size() && json[p] == ',') { p = skipWs(json, p + 1); continue; }- if (p < json.size() && json[p] == ']') return true;- return false;- }- return false;-}-} // namespace nota::cfgfilediff --git a/src/native/nota.engine/src/NotaConfigFile.h b/src/native/nota.engine/src/NotaConfigFile.hindex a811c1b2..4fc72f5d 100644--- a/src/native/nota.engine/src/NotaConfigFile.h+++ b/src/native/nota.engine/src/NotaConfigFile.h@@ -1,36 +1,31 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Small helpers shared by the non-Apple config layer (AudioConfig_miniaudio.cpp and-// MidiConfig_rtmidi.cpp, on Windows + Linux): the per-user data directory and a minimal-// JSON read/write for the tiny audio.json / midi.json config files. These files are-// engine-internal (the managed layer reads them only through C ABI getters), so a-// hand-rolled parser is sufficient — but string values (WASAPI endpoint ids can contain-// backslashes/braces) are properly escaped. The directory mirrors NotaPaths.DataDir on-// the managed side: %APPDATA%\Nota on Windows, $XDG_CONFIG_HOME/nota (or ~/.config/nota)-// on Linux, or NOTA_DATA_DIR when set (tests). The plugin host's catalog lives here too.+// Small helpers shared by the config layer on all platforms (AudioConfig and+// MidiConfig persistence): the per-user data directory plus atomic file read/write.+// JSON itself is handled by nlohmann/json (fetched via CPM, see cmake/dependencies.cmake)+// in ConfigJson.cpp — this header stays JSON-free. The engine never infers platform+// paths: the directory is set once at startup from the managed side+// (nota_set_data_dir <- NotaPaths.DataDir); tests use NOTA_DATA_DIR instead.+// Unset (empty) means persistence is off. The plugin host's catalog lives here too.#pragma once#include <string>-#include <vector>namespace nota::cfgfile {-// Per-user config dir, created on first use. Empty string if it can't be resolved.+// Explicit override set once at startup via nota_set_data_dir (C ABI), fed from+// NotaPaths.DataDir on the managed side. Empty = unset (persistence off).+// Thread-safe; never called on the audio thread (config IO is message-thread).+void setDataDirOverride(const std::string& dir);+std::string dataDirOverride();++// Per-user config dir, created on first use. Empty when unset (no override and+// no NOTA_DATA_DIR): loads return defaults, saves are skipped.std::string dataDir();std::string readFile(const std::string& path);bool writeFileAtomic(const std::string& path, const std::string& content);-std::string jsonEscape(const std::string& s);--// Extract "key":"value" (JSON-unescaped). False if the key is absent.-bool jsonGetString(const std::string& json, const std::string& key, std::string& out);-// Extract "key": <number>. False if the key is absent / unparseable.-bool jsonGetNumber(const std::string& json, const std::string& key, double& out);-// Extract "key":["a","b",...]; appends unescaped elements. False if key absent.-bool jsonGetStringArray(const std::string& json, const std::string& key,- std::vector<std::string>& out);-} // namespace nota::cfgfilediff --git a/src/native/nota.engine/src/nota_engine_core.cpp b/src/native/nota.engine/src/nota_engine_core.cppindex f5c1b5a6..3d884cd7 100644--- a/src/native/nota.engine/src/nota_engine_core.cpp+++ b/src/native/nota.engine/src/nota_engine_core.cpp@@ -14,6 +14,8 @@#include <new>#include <string>+#include "NotaConfigFile.h"+// Injected by CMake from src/native/nota.engine/VERSION.#ifndef NOTA_VERSION_STRING#error "NOTA_VERSION_STRING must be defined by the build (see CMakeLists.txt)"@@ -31,6 +33,24 @@ void nota_engine_destroy(NotaEngine* engine) {delete reinterpret_cast<Engine*>(engine);}+NotaResult nota_set_data_dir(const char* path_utf8) {+ // NULL / "" clears the override (persistence off unless NOTA_DATA_DIR is set).+ // Called once at startup from the managed side; never on+ // the audio thread (AR-6: create_directories does file I/O).+ if (!path_utf8 || !*path_utf8) {+ nota::cfgfile::setDataDirOverride({});+ return NOTA_OK;+ }+ nota::cfgfile::setDataDirOverride(std::string(path_utf8));+ return NOTA_OK;+}++const char* nota_get_data_dir(void) {+ static std::string s; // owned by the engine, valid until the next call+ s = nota::cfgfile::dataDir();+ return s.c_str();+}+NotaResult nota_engine_start(NotaEngine* engine) {if (!engine) return NOTA_ERR_INVALID_ARG;return reinterpret_cast<Engine*>(engine)->start() ? NOTA_OK : NOTA_ERR_AUDIO_DEVICE;