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
(fix) Drum Rack: keep replaced rack layouts alive until the audio thread is done with them (#178)
Chris Laupamaefa01cab6f72
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 64b8d22e..7f88afac 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -82,6 +82,11 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.Windows and Linux) always starts a new track.### Fixed+- **Drum Rack crash while loading a kit** (nota-daw/nota#177): building a Drum Rack kit (or+ any burst of rack edits) while audio was running could crash the audio engine with a+ use-after-free in the rack's render (seen on macOS). A rack keeps every replaced chain+ layout alive until the audio thread has finished two more blocks, instead of only the last+ 16 edits; the Instrument Rack, Audio Effect Rack and Rhythm's voice effects get the same fix.- **Session recording counts in** (nota-daw/nota#158): recording into a Session slot (or ascene) with the transport stopped now plays the metronome count-in first, with the slotblinking "Rec in…", and the take starts when it ends. A note you start during the count-indiff --git a/src/native/nota.engine/src/DrumRack.h b/src/native/nota.engine/src/DrumRack.hindex ca7654b0..f4f6a36d 100644--- a/src/native/nota.engine/src/DrumRack.h+++ b/src/native/nota.engine/src/DrumRack.h@@ -63,6 +63,7 @@ public:// Sum every audible pad, applying the per-pad decay VCA. Mirrors// RackInstrument::render with the pad envelope folded into the mix loop.void render(float* out, int32_t frames) override {+ const auto done = renderScope();RackState* st = live();if (!st || frames <= 0 || frames > kMaxBlock) return;bool anySolo = false;diff --git a/src/native/nota.engine/src/Engine_Rack.cpp b/src/native/nota.engine/src/Engine_Rack.cppindex e354674c..e765e82b 100644--- a/src/native/nota.engine/src/Engine_Rack.cpp+++ b/src/native/nota.engine/src/Engine_Rack.cpp@@ -16,9 +16,11 @@#include "RackDevice.h"#include "DrumRack.h"#include "Sampler.h"+#include "SnapshotHistory.h"#include <algorithm>#include <cmath>+#include <memory>#include <vector>// Catalog id -> index resolution lives in the plugin host (C ABI); reused here so@@ -492,6 +494,22 @@ bool Engine::drumRackSelfTest() {rk2.setSampleRate(44100.0);rk2.setState(blob.data(), static_cast<int32_t>(blob.size()));if (rk2.chainTriggerNote(0) != 36 || rk2.chainTriggerNote(1) != 38) return false;++ // Snapshot lifetime (#177): a kit load commits dozens of times inside one audio block.+ // The snapshot a render is walking must outlive all of them, and go two renders later.+ SnapshotHistory<int> h;+ auto first = std::make_shared<int>(0);+ const std::weak_ptr<int> held = first;+ h.publish(std::move(first));+ {+ const SnapshotHistory<int>::RenderScope block(h);+ const int* walking = h.live();+ for (int i = 1; i <= 40; ++i) h.publish(std::make_shared<int>(i));+ if (held.expired() || *walking != 0) return false;+ }+ { const SnapshotHistory<int>::RenderScope block(h); }+ h.publish(std::make_shared<int>(41));+ if (!held.expired()) return false;return true;}diff --git a/src/native/nota.engine/src/RackCore.h b/src/native/nota.engine/src/RackCore.hindex dd5ac499..ff07d33d 100644--- a/src/native/nota.engine/src/RackCore.h+++ b/src/native/nota.engine/src/RackCore.h@@ -18,6 +18,7 @@#pragma once#include "Instrument.h"+#include "SnapshotHistory.h"#include "Device.h"#include "Synth.h"@@ -129,8 +130,9 @@ public:}virtual ~RackCore() = default;- // Audio-thread view of the current snapshot (raw pointer, retained by states_).- RackState* live() const { return live_.load(std::memory_order_acquire); }+ // Audio-thread view of the current snapshot (raw pointer, retained by states_+ // until the renders that could still hold it have finished).+ RackState* live() const { return states_.live(); }// Fan the transport snapshot out to every chain child so hosted plugins nested// in a rack sync to the DAW clock too (the Instrument/Device overrides call this).@@ -694,6 +696,10 @@ public:protected:static std::shared_ptr<Device> makeDevice(int32_t kind) { return makeChainDevice(kind); }+ // Audio thread: hold one for the whole render/process call (it ends the render+ // epoch that frees retired snapshots).+ SnapshotHistory<RackState>::RenderScope renderScope() { return SnapshotHistory<RackState>::RenderScope(states_); }+// Macro response curve applied to the 0..1 value before mapping to [min,max].static float applyCurve(float v, int32_t curve) {v = std::clamp(v, 0.0f, 1.0f);@@ -751,9 +757,7 @@ private:}void commit(std::shared_ptr<RackState> ns) {authoring_ = ns;- states_.push_back(ns);- if (states_.size() > 16) states_.erase(states_.begin()); // keep short history alive for the audio thread- live_.store(ns.get(), std::memory_order_release);+ states_.publish(std::move(ns));}static void pruneMappings(std::shared_ptr<RackState>& ns, int32_t removedChain) {auto& v = ns->mappings;@@ -806,8 +810,7 @@ private:static constexpr uint32_t kBlobVersion = 8; // v2 triggerNote; v3 Sampler; v4 plugins; v5 zones/names/rack-out/curve; v6 drum pad shaping + swing/humanize; v7 effect-rack mode/dry-wet/pdc/select; v8 chain namestd::shared_ptr<RackState> authoring_;- std::vector<std::shared_ptr<RackState>> states_;- std::atomic<RackState*> live_{nullptr};+ SnapshotHistory<RackState> states_;};} // namespace notadiff --git a/src/native/nota.engine/src/RackDevice.h b/src/native/nota.engine/src/RackDevice.hindex 43fc836c..a0d9fc52 100644--- a/src/native/nota.engine/src/RackDevice.h+++ b/src/native/nota.engine/src/RackDevice.h@@ -34,6 +34,7 @@ public:// ---- in-place processing: Parallel / Series / Select + dry-wet + gain ----void process(float* buf, int32_t frames) override {+ const auto done = renderScope();RackState* st = live();if (!st || frames <= 0 || frames > kMaxBlock) return;if (st->chains.empty()) return; // pass-through until chains existdiff --git a/src/native/nota.engine/src/RackInstrument.h b/src/native/nota.engine/src/RackInstrument.hindex 6a35baed..d8a80f40 100644--- a/src/native/nota.engine/src/RackInstrument.h+++ b/src/native/nota.engine/src/RackInstrument.h@@ -77,6 +77,7 @@ public:// ---- render: sum every audible chain into `out` -------------------------void render(float* out, int32_t frames) override {+ const auto done = renderScope();RackState* st = live();if (!st || frames <= 0 || frames > kMaxBlock) return;bool anySolo = false;diff --git a/src/native/nota.engine/src/RhythmMachine.h b/src/native/nota.engine/src/RhythmMachine.hindex c2d49513..a7cd2736 100644--- a/src/native/nota.engine/src/RhythmMachine.h+++ b/src/native/nota.engine/src/RhythmMachine.h@@ -45,6 +45,7 @@#include "Instrument.h"#include "SampleBuffer.h"#include "BuiltinDevices.h"+#include "SnapshotHistory.h"#include <algorithm>#include <atomic>@@ -130,11 +131,11 @@ public:void setTransport(double beatStart, double spb, bool playing) override {if (spb > 0.0) spb_ = spb;beatStart_ = beatStart; playing_ = playing;- if (FxState* fx = fxLive_.load(std::memory_order_acquire)) // tempo-synced voice FX (a synced Delay)+ if (FxState* fx = fxStates_.live()) // tempo-synced voice FX (a synced Delay)for (auto& ch : fx->chain) for (auto& d : ch) if (d) d->setTransport(beatStart, spb, playing);}void setTransportInfo(const TransportInfo& ti) override {- if (FxState* fx = fxLive_.load(std::memory_order_acquire))+ if (FxState* fx = fxStates_.live())for (auto& ch : fx->chain) for (auto& d : ch) if (d) d->setTransportInfo(ti);}@@ -211,11 +212,11 @@ public:// ---- per-voice FX chains (message thread; the audio thread reads the live snapshot) ----int32_t voiceDeviceCount(int v) const {- FxState* fx = fxLive_.load(std::memory_order_acquire);+ FxState* fx = fxStates_.live();return (fx && v >= 0 && v < kVoices) ? static_cast<int32_t>(fx->chain[v].size()) : 0;}Device* voiceDevice(int v, int d) const {- FxState* fx = fxLive_.load(std::memory_order_acquire);+ FxState* fx = fxStates_.live();if (!fx || v < 0 || v >= kVoices || d < 0 || d >= static_cast<int>(fx->chain[v].size())) return nullptr;return fx->chain[v][d].get();}@@ -289,9 +290,9 @@ public:applyMacro(macro, get(Macro0 + macro));return idx;}- int32_t macroMappingCount() const { FxState* fx = fxLive_.load(std::memory_order_acquire); return fx ? static_cast<int32_t>(fx->maps.size()) : 0; }+ int32_t macroMappingCount() const { FxState* fx = fxStates_.live(); return fx ? static_cast<int32_t>(fx->maps.size()) : 0; }bool macroMapping(int i, MacroMap& out) const {- FxState* fx = fxLive_.load(std::memory_order_acquire);+ FxState* fx = fxStates_.live();if (!fx || i < 0 || i >= static_cast<int>(fx->maps.size())) return false;out = fx->maps[i];return true;@@ -347,7 +348,7 @@ public:// Voice FX + kit label, tagged "RFX1": per voice a device count, then per device its// builtinKind, bypass flag and params; then the kit label.putU32(b, kFxMagic);- FxState* fx = fxLive_.load(std::memory_order_acquire);+ FxState* fx = fxStates_.live();for (int v = 0; v < kVoices; ++v) {const auto* ch = fx ? &fx->chain[v] : nullptr;const int n = ch ? static_cast<int>(ch->size()) : 0;@@ -458,7 +459,7 @@ public:// The voice FX are copied device by device (kind + params + bypass): a clone must not// share DSP state with the original, which keeps playing until the swap.auto ns = std::make_shared<FxState>();- if (FxState* fx = fxLive_.load(std::memory_order_acquire))+ if (FxState* fx = fxStates_.live())for (int v = 0; v < kVoices; ++v)for (auto& d : fx->chain[v]) {auto c = d ? makeChainDevice(d->builtinKind()) : nullptr;@@ -470,7 +471,7 @@ public:c->setBypassed(d->bypassed());ns->chain[v].push_back(std::move(c));}- if (FxState* fx = fxLive_.load(std::memory_order_acquire)) ns->maps = fx->maps;+ if (FxState* fx = fxStates_.live()) ns->maps = fx->maps;r->commitFx(ns);r->kit_ = kit_;for (int m = 0; m < kMacros; ++m) r->macroNames_[m] = macroNames_[m];@@ -493,6 +494,7 @@ public:void allNotesOff() override { for (auto& vc : voices_) vc.active = false; }void render(float* out, int32_t frames) override {+ const SnapshotHistory<FxState>::RenderScope done(fxStates_);const float swing = get(Swing), human = get(Humanize);const float accentG = 1.0f + get(Accent) * 1.0f; // up to +6 dB-ishconst float vol = get(Volume) * 1.2f;@@ -516,7 +518,7 @@ public:float grMax = 0.0f;// Voices with an FX chain render into their own buffer and run through it; the rest// go straight to the sum. Chunks keep the buffers small and the chain's block bounded.- FxState* fx = fxLive_.load(std::memory_order_acquire);+ FxState* fx = fxStates_.live();bool hasFx[kVoices] = {false};bool anyFx = false;if (fx)@@ -641,7 +643,7 @@ private:// Push macro m's value to its targets. Any thread (automation plays on the audio thread):// it only reads the live snapshot and stores atomics / device params.void applyMacro(int m, float value) {- FxState* fx = fxLive_.load(std::memory_order_acquire);+ FxState* fx = fxStates_.live();if (!fx) return;for (const auto& mp : fx->maps) {if (mp.macro != m) continue;@@ -654,13 +656,11 @@ private:}}std::shared_ptr<FxState> copyFx() const { return fxAuthoring_ ? std::make_shared<FxState>(*fxAuthoring_) : std::make_shared<FxState>(); }- // Publish a new FX snapshot. The last few stay alive so a block still reading an older- // one never sees it freed (the RackCore scheme).+ // Publish a new FX snapshot. Older ones stay alive until no render can still be+ // reading them (the RackCore scheme).void commitFx(std::shared_ptr<FxState> ns) {fxAuthoring_ = ns;- fxStates_.push_back(ns);- if (fxStates_.size() > 16) fxStates_.erase(fxStates_.begin());- fxLive_.store(ns.get(), std::memory_order_release);+ fxStates_.publish(std::move(ns));}static void putU32(std::vector<uint8_t>& b, uint32_t v) { for (int i = 0; i < 4; ++i) b.push_back((uint8_t)(v >> (i * 8))); }static constexpr double kTwoPi = 6.283185307179586;@@ -854,8 +854,7 @@ private:std::atomic<float> pn_[kNumParams];std::shared_ptr<FxState> fxAuthoring_; // voice FX (message thread)- std::vector<std::shared_ptr<FxState>> fxStates_; // recent snapshots kept alive- std::atomic<FxState*> fxLive_{nullptr};+ SnapshotHistory<FxState> fxStates_; // live snapshot + retirees (audio reads fxStates_.live())std::string kit_; // factory kit label (message thread)std::string macroNames_[kMacros]; // custom macro names ("" = "Macro N"; message thread)float mix_[kChunk * 2]; // audio thread: the chunk's sumdiff --git a/src/native/nota.engine/src/SnapshotHistory.h b/src/native/nota.engine/src/SnapshotHistory.hnew file mode 100644index 00000000..57915da1--- /dev/null+++ b/src/native/nota.engine/src/SnapshotHistory.h@@ -0,0 +1,65 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// SnapshotHistory — lifetime of an immutable snapshot the message thread publishes+// and the audio thread reads through a raw pointer (a rack's chains, a Rhythm+// Machine's voice FX). Replaced snapshots are retired with the audio thread's render+// epoch and freed once two more renders have finished, so none can still be walking+// them: the engine's preview / Mosaic pattern. A fixed-size history isn't a grace+// period: a kit load commits dozens of times inside one audio block (#177).+//+// Threads. publish() and everything else that isn't marked runs on the message+// thread. The audio thread only calls live() and ends each render with a+// RenderScope, so it neither touches the retired list nor frees memory. While the+// owner isn't being rendered, retired snapshots simply wait.++#pragma once++#include <algorithm>+#include <atomic>+#include <cstdint>+#include <memory>+#include <utility>+#include <vector>++namespace nota {++template <class T>+class SnapshotHistory {+public:+ // Audio-thread view of the current snapshot; valid until the end of the render+ // that read it.+ T* live() const { return live_.load(std::memory_order_acquire); }++ // Publish `next` and retire the current one; frees retirees no render can still hold.+ void publish(std::shared_ptr<T> next) {+ live_.store(next.get(), std::memory_order_seq_cst);+ // Read after the swap: a render that saw the old pointer has finished by epoch now + 2.+ const uint64_t now = epoch_.load(std::memory_order_seq_cst);+ if (current_) retired_.emplace_back(now, std::move(current_));+ current_ = std::move(next);+ retired_.erase(std::remove_if(retired_.begin(), retired_.end(),+ [&](const auto& r) { return now >= r.first + 2; }),+ retired_.end());+ }++ // Audio thread: one per render/process call, ending that call's render epoch on+ // every return path.+ class RenderScope {+ public:+ explicit RenderScope(SnapshotHistory& h) : h_(h) {}+ ~RenderScope() { h_.epoch_.fetch_add(1, std::memory_order_seq_cst); }+ RenderScope(const RenderScope&) = delete;+ RenderScope& operator=(const RenderScope&) = delete;+ private:+ SnapshotHistory& h_;+ };++private:+ std::shared_ptr<T> current_;+ std::vector<std::pair<uint64_t, std::shared_ptr<T>>> retired_;+ std::atomic<T*> live_{nullptr};+ std::atomic<uint64_t> epoch_{0};+};++} // namespace nota