instrument: snap live params onto a fresh voice, roll a live drag back on capture loss, serialize the seqlock's two writers

This commit is contained in:
2026-07-30 21:39:56 -04:00
parent 1dade0bfcf
commit bbc7dc70bb
15 changed files with 621 additions and 143 deletions
+26 -20
View File
@@ -160,23 +160,28 @@ Daniel's ruling, verbatim: *"hell no, I was going to bring that up for the other
must live compute, latching the parameters at note on is not acceptable. long term these will be
automatable parameters."* It rejects the precedent, not one instance of it.
- **Which controls are live is ONE decision, recorded in ONE place** — `isLiveDeckParam`
(`ui/deck_groups`). Continuous playback controls go live: the six filter tone/modulation
knobs, and every stage time and stage level on all three envelopes. Everything else reloads
or drops to the voice-param rebuild. Two controls look continuous but are deliberately not
live — the pitch key-track and the velocity→cutoff depth feed values a voice latches at
note-on (the pitch ratio, the velocity-curve result), so making them live would retune or
re-gain a note already struck. The three capture-anchored overrides (root, loop span, start
frame) reload because they name positions in the decoded PCM.
- **Which controls are live is ONE decision, recorded in ONE place** — `isLiveDeckParam` and
`liveCommitFor` (`ui/deck_groups`), whose header is the home for why each excluded control is
excluded. Continuous playback controls go live: the six filter tone/modulation knobs, and
every stage time and stage level on all three envelopes. Everything else reloads or drops to
the voice-param rebuild. **FIVE continuous controls are outside the live set** — pitch
key-track, velocitycutoff depth, and Trigger's %-length, fade-in and fade-out — so a
Trigger-mode instance gets no live delivery on its amplitude controls at all; only the filter
and pitch-envelope knobs move a sounding one-shot.
- **Ownership sits ABOVE every snapshot.** `SampleData::live` is a NON-OWNING pointer to the one
block the shell owns per instance; a block owned by a snapshot would leave the drain slot's
still-sounding voices deaf to the knob under them. A drain voice tracking the knob is the
DESIRED behaviour — it is the note the user is hearing.
block the shell owns per instance. The member-ordering constraint that enforces it, and why,
are recorded at `liveParams_` in `shell/instrument/reasampler_processor.h`. A drain voice
tracking the knob is the DESIRED behaviour — it is the note the user is hearing.
- **Null is the bare engine.** `live == nullptr` is byte-identical to the pre-live core, which
is why `sampler_core`'s regression baselines needed no change.
- **Observation is at block boundaries, never per frame.** `VoiceEngine` reads the seqlock once
per `render()` and once per note-on; the per-sample path gained one predicted branch
(`filterRamping_`) and no indirection.
per `render()` and once per note-on; the per-sample path gained three predicted branches (the
voice's filter-ramp check and each envelope smoother's active check), all false at rest, and
no indirection.
- **A fresh note SNAPS, a sounding one holds φ.** They are different entry points on purpose
(`snapLive` vs `applyLive`): a voice that has rendered nothing has no phase to hold, and the
φ rule reads its stage-0 position under a stale zero-length stage as a completed stage. One
function serving both silently discarded every newly-dialled attack.
- **The mid-stage rule is HOLD NORMALIZED STAGE POSITION** (Daniel's pick among six candidates):
φ = elapsed/duration is held across a stage-time change, so the level is continuous by
construction and the remainder takes its share of the new duration. Stated over normalized
@@ -232,7 +237,7 @@ slider couldn't. Two pure modules split the forward (draw) and inverse (edit) ma
- The engine is the `sampler_core` CMake target over FOUR headers and TWO TUs, split on its own responsibility seam — cold note routing vs the hot per-sample render:
- `play_params.h` — the value layer: `PlayParams`/`AdsrParams`/`TriggerParams`/`PitchEnvParams`/`FilterParams`, the per-instance mode enums (`ChannelMode`/`VoiceMode`/`MonoTrigger`), and `SampleData` (the ONE loaded capture: decoded PCM + root + loop + start + keyTrack + velocity curve + play params). Shared by the engine, the codec, and the editor, so a UI/codec TU reading a param struct doesn't recompile when a `Voice` member changes. `FilterParams` stores the filter module's own `FilterSettings` by value rather than a parallel copy of its normalized positions.
- `envelopes.h` — the three per-frame evaluators (`AdsrEnvelope` AHDSR, `TriggerEnvelope` fade shape, `PitchEnvelope` AD offset), CONCRETE and fully header-inline. Never give them a common base or a virtual `tick()`: they are called per-voice-per-sample. The filter envelope is a SECOND `AdsrEnvelope` instance on the voice, not a fourth class. `AdsrEnvelope`/`PitchEnvelope` also own `applyLive` (the φ-holding mid-stage rule) and `StepSmoother`, the bounded offset that absorbs the two level steps φ cannot cover.
- `envelopes.h` — the three per-frame evaluators (`AdsrEnvelope` AHDSR, `TriggerEnvelope` fade shape, `PitchEnvelope` AD offset), CONCRETE and fully header-inline. Never give them a common base or a virtual `tick()`: they are called per-voice-per-sample. The filter envelope is a SECOND `AdsrEnvelope` instance on the voice, not a fourth class. `AdsrEnvelope`/`PitchEnvelope` also own `applyLive` (the φ-holding mid-stage rule), its fresh-note peer `snapLive`, and `StepSmoother`, the bounded offset that absorbs the two level steps φ cannot cover.
- `live_params.h` / `live_params.cpp` — the live-parameter block: `LiveValues` (the plain, trivially-copyable bundle the audio thread observes), the single-writer `LiveParams` seqlock that publishes it without a lock or a torn read, `foldLive` (the ONE derivation from `PlayParams` — every publisher goes through it so the two representations cannot drift), and `ValueRamp`, the per-frame glide whose EXACT termination is what lets the filter's equality-compare cutoff skip re-engage. Links no engine: the block is a value the voice observes, not a thing the engine owns.
- `voice.h` / `voice.cpp` — one voice. The per-SAMPLE render half (`advanceFrame` and everything it calls) is INLINE IN THE HEADER by RT constraint; the per-NOTE half (note-on setup incl. the Preserve ring prime, legato retune, gate-off, the off-thread shifter presize) is out of line in the TU. The voice owns its own `VoiceFilter` and filter envelope, run between the pitch stage and the amp multiply — see `engine/filter/CLAUDE.md`.
- `voice_engine.h` / `voice_engine.cpp` — `VoiceEngine`: note routing, bounded-stealing allocation, user-parameterized voice count (132, default 16), `VoiceMode` Poly/Mono (last-note held-note stack, `MonoTrigger` Retrigger/Legato), two-tier panic (CC 123 = all-notes-off release, CC 120 = immediate hard-stop including Trigger one-shots), and the block render loops. Preview injects a synthetic note-on at the loaded capture's root note into the main `VoiceEngine` — no dedicated `PreviewCard`; preview obeys polyphony/mono/voice-stealing/envelopes.
@@ -261,7 +266,7 @@ slider couldn't. Two pure modules split the forward (draw) and inverse (edit) ma
- `param_slider` — parameter control-panel: vertical stack of TOGGLE (two-segment selector) and SLIDER (horizontal track) rows; maps normalized value to/from handle pixel.
- `embed_strip` — compact single-row control layout for embed mode in the track FX chain.
- `knob_deck` — pure knob-deck layout + hit-test (FB1): group-box / caption-row / compact-toggle / knob-cell geometry, deterministic whole-group wrap, `DeckLayout` / `DeckHit`. Mirror of `action_bar`/`param_slider`; no LICE or REAPER types.
- `deck_groups` — also home to `isLiveDeckParam`, the editor's commit-tier routing predicate (see "Live parameter delivery" above); WHICH groups the Sample face's deck carries, split from `knob_deck`'s HOW they lay out: the `DeckParam` control-id space (the editor's `ParamControl` is an alias of it), the `DeckGroupId` list, `sampleDeckGroups` in signal-flow order (**pitch → filter → amp**, then voice/master), and the deck's bipolar-knob law. Reads `PlayMode` for the AMP group's Gate/Trigger face, which is why this and not `knob_deck` is the module that touches the engine's value layer.
- `deck_groups` — also home to `isLiveDeckParam` and `liveCommitFor`, the editor's whole commit-tier routing decision (see "Live parameter delivery" above); WHICH groups the Sample face's deck carries, split from `knob_deck`'s HOW they lay out: the `DeckParam` control-id space (the editor's `ParamControl` is an alias of it), the `DeckGroupId` list, `sampleDeckGroups` in signal-flow order (**pitch → filter → amp**, then voice/master), and the deck's bipolar-knob law. Reads `PlayMode` for the AMP group's Gate/Trigger face, which is why this and not `knob_deck` is the module that touches the engine's value layer.
- `curve_popup` — pure curve-popup geometry + dismissal test (FB1): centered sheet over the Sample face — width/height clamps, title row, Close button rect, curve-box rect, outside-sheet dismissal test. Mirror of `overflow_menu`; no LICE or REAPER types.
- `envelope_overlay` — pure amp-envelope→polyline geometry for the Sample-view envelope overlay (read from `envelope_overlay.h`): maps Gate's AHDSR shape or Trigger's fade-in/unity/%-length/fade-out shape to a polyline inside a rect at the shared time base (Gate: a bounded param-domain schematic, sample-length-free; Trigger: PCM-aligned wall-clock), every vertex clamped in-canvas (`x`/`y` inside the rect). Shares the `EnvNode`/`AmpEnvelope`/`timeToX`/`levelToY` vocabulary with `envelope_edit` so the drawn handle and its grab region agree pixel-for-pixel. No VST3/REAPER/LICE types at the boundary.
- `envelope_edit` — pure node hit-test + pixel-delta→clamped-param inverse map for the draggable envelope nodes (read from `envelope_edit.h`): `nodeAtPoint` resolves a grab to the nearest node within a pick radius (Chebyshev distance, draw-order tie-break); `resolveNodeDrag` maps a pixel delta since grab to a new `AmpEnvelope`, enforcing monotonic-in-time ordering between neighbouring nodes and the same caller-supplied per-param clamp bounds the sliders use — a drag can never produce a param a slider couldn't. Mirror of `card_drag`/`waveform_view`; the inverse of `envelope_overlay`'s params→polyline forward map, so node-drag and slider-edit read/write one shared model and can never diverge.
@@ -280,13 +285,14 @@ slider couldn't. Two pure modules split the forward (draw) and inverse (edit) ma
- **A filter envelope only advances while its depth is non-zero.** `tickFilterCutoff`'s exact
skip at `modAmount == 0` skips the envelope tick along with the solve, so dialling depth up
mid-note starts the envelope from the note's stage-0 position rather than from where it would
have been. Continuous either way (the contribution starts at 0), and keeping the skip is what
holds the at-rest per-sample path byte-identical — but don't read a live depth move as
"resuming" an envelope that was never running.
have been. Its step smoother is frozen with it — an absorbed step sits in the offset and
emits when depth is next dialled up (bounded, and scaled by a depth ramping from 0).
Continuous either way (the contribution starts at 0), and keeping the skip is what holds the
at-rest per-sample path byte-identical — but don't read a live depth move as "resuming" an
envelope that was never running.
- **A live edit leaves the snapshot's own `sample.play` stale, on purpose.** The block, not the
snapshot, is the audio thread's source; a new voice latches the stale copy and is corrected by
`applyLive(snap)` before its first frame. The persisted `params_` is written by the same
commit, so `getState` is never stale.
`snapLive` before its first frame.
- **`keyboard_strip`'s width-uniformity guarantee is client-pixel only.** Its test sweep
covers client-pixel widths (including multiples standing in for larger client areas);
nothing in the instrument implements `IPlugViewContentScaleSupport`, so host-side DPI
+35 -19
View File
@@ -90,6 +90,17 @@ public:
stagePos_ = 0.0;
}
// Live parameter delivery to a fresh voice — one that has NOT yet rendered a frame, whose
// latched copy may predate the newest edit. It takes the params outright: there is no
// phase to hold and nothing to be continuous with. applyLive cannot serve here in either
// direction — with a stale duration of 0 its phi rule reads stagePos_ == 0 as a COMPLETED
// stage and discards the newly-dialled time, and with a stale duration > 0 against a new 0
// it absorbs a full-scale step into a voice that has emitted nothing, fading the onset in.
void snapLive(const AdsrParams& params) {
params_ = params;
smooth_.clear();
}
// Live parameter delivery to a SOUNDING voice. The mid-stage rule is HOLD NORMALIZED
// STAGE POSITION: phi = elapsed/duration is kept fixed across the change, so this frame's
// level is unchanged by construction and the remainder of the stage takes its share of the
@@ -117,6 +128,11 @@ public:
// Once Release completes the envelope latches Finished and returns 0.0 forever (until
// the next noteOn). A single, monotonic per-frame step — the caller pulls one value per
// output frame.
//
// While the smoother runs the return may sit OUTSIDE [0,1] by the offset it is decaying
// (bounded by the step it absorbed). finished() ignores that residue, so a Release that
// completes with an offset still decaying is hard-cut when the voice frees — the audible
// remainder of a step the smoother had already taken most of.
double tick() {
const double out = tickStage();
return smooth_.active() ? out + smooth_.advance() : out;
@@ -127,8 +143,11 @@ public:
double level() const { return level_; }
private:
// The level tick() would emit right now under `params`, without advancing anything — the
// prediction applyLive compares across the change to size the smoother.
// The level tick() would emit right now under `params` without advancing anything. THE one
// home for every segment's shape: tickStage owns only the advance and the stage
// transitions and reads its output from here, so a per-segment curve added later lands in
// one place and the smoother can never size a step against a different curve than the
// output takes.
double stageLevel(const AdsrParams& params) const {
switch (stage_) {
case Stage::Attack: {
@@ -178,12 +197,7 @@ private:
return 0.0;
case Stage::Attack: {
if (params_.attackFrames <= 0) {
level_ = 1.0;
} else {
level_ = stagePos_ / static_cast<double>(params_.attackFrames);
if (level_ > 1.0) level_ = 1.0;
}
level_ = stageLevel(params_);
const double out = level_;
stagePos_ += 1.0;
if (stagePos_ >= static_cast<double>(params_.attackFrames)) {
@@ -208,7 +222,7 @@ private:
// smoother is applied exactly once per frame.
return tickStage();
}
level_ = 1.0;
level_ = stageLevel(params_);
const double out = level_;
stagePos_ += 1.0;
if (stagePos_ >= static_cast<double>(params_.holdFrames)) {
@@ -220,12 +234,7 @@ private:
}
case Stage::Decay: {
if (params_.decayFrames <= 0) {
level_ = params_.sustainLevel;
} else {
const double t = stagePos_ / static_cast<double>(params_.decayFrames);
level_ = 1.0 + (params_.sustainLevel - 1.0) * t;
}
level_ = stageLevel(params_);
const double out = level_;
stagePos_ += 1.0;
if (stagePos_ >= static_cast<double>(params_.decayFrames)) {
@@ -237,7 +246,7 @@ private:
}
case Stage::Sustain:
level_ = params_.sustainLevel;
level_ = stageLevel(params_);
return level_;
case Stage::Release: {
@@ -246,9 +255,7 @@ private:
stage_ = Stage::Finished;
return 0.0;
}
const double t = stagePos_ / static_cast<double>(params_.releaseFrames);
level_ = releaseFrom_ * (1.0 - t);
if (level_ < 0.0) level_ = 0.0;
level_ = stageLevel(params_);
const double out = level_;
stagePos_ += 1.0;
if (stagePos_ >= static_cast<double>(params_.releaseFrames)) {
@@ -348,6 +355,15 @@ public:
void configure(const PitchEnvParams& params) { params_ = params; pos_ = 0.0; }
void noteOn() { pos_ = 0.0; smooth_.clear(); }
// Peer of AdsrEnvelope::snapLive (see it for why the two paths cannot share code): a voice
// that has rendered nothing takes the new times and depth outright.
void snapLive(std::int64_t attackFrames, std::int64_t decayFrames, double peakSemitones) {
params_.attackFrames = attackFrames;
params_.decayFrames = decayFrames;
params_.peakSemitones = peakSemitones;
smooth_.clear();
}
// Live parameter delivery, same rule as AdsrEnvelope::applyLive: hold the normalized
// position within whichever leg the envelope is in, and absorb the depth step (peak is a
// level, not a duration). `enabled` is a discrete toggle and travels by reload, so it is
+14 -1
View File
@@ -52,6 +52,16 @@ LiveValues foldLive(const PlayParams& params);
// reader: after the retry budget it reports "nothing new" and the caller keeps its last good
// snapshot rather than spinning on the audio thread.
//
// SINGLE-WRITER IS THE CALLER'S JOB and is load-bearing: two concurrent writers can leave the
// generation EVEN mid-write (A stores gen+1, B reads odd and stores gen+2) while both copy the
// block, and a reader then accepts a torn block as coherent. Every publisher must serialize.
//
// The plain (non-atomic) block copied across the fences is the standard pragmatic seqlock:
// the fences give correct ordering, but the concurrent read of a non-atomic object is a data
// race under the C++ object model, so TSan/UBSan will report it. That report is expected, not
// a defect — there is no clean lock-free standard-C++ alternative that keeps the block a plain
// value the audio thread can copy in one shot.
//
// The writer interface deliberately assumes NO particular thread beyond single-writer, so a
// host's own parameter-change queue (delivered on the audio thread with sample offsets) can
// drive it later without a redesign.
@@ -64,7 +74,10 @@ public:
std::atomic_thread_fence(std::memory_order_release);
values_ = values;
std::atomic_thread_fence(std::memory_order_release);
seq_.store(gen + 2, std::memory_order_release); // even: complete and coherent
// Skip 0 on wrap (~2^31 publishes): landing there would read as "never published" and
// stall every reader until the NEXT publish — a silent mode, unlike a loud one.
const std::uint32_t next = (gen + 2 == 0u) ? 2u : gen + 2;
seq_.store(next, std::memory_order_release); // even: complete and coherent
}
// Copies the block into `out` and returns the generation actually observed, or 0 when
+16 -5
View File
@@ -197,13 +197,24 @@ void Voice::start(int note, int velocity, const SampleData& sample, bool declick
void Voice::applyLive(const instrument::engine::LiveValues& live, bool snap) {
// Gate's amplitude envelope is the AHDSR; Trigger's fade shape is anchored to a play span
// resolved at note-on and is not a live control, so it is deliberately untouched here.
if (playMode_ == PlayMode::Gate) env_.applyLive(live.adsr);
pitchEnv_.applyLive(live.pitchEnvAttackFrames, live.pitchEnvDecayFrames,
live.pitchEnvPeakSemitones);
// resolved at note-on and travels by reload instead (deck_groups.h names why).
//
// A fresh note and a sounding one take DIFFERENT envelope entry points, never one with a
// flag: a voice that has rendered nothing has no phase to hold and nothing to be
// continuous with, and the mid-stage rule misreads its stage-0 position (envelopes.h).
if (snap) {
if (playMode_ == PlayMode::Gate) env_.snapLive(live.adsr);
pitchEnv_.snapLive(live.pitchEnvAttackFrames, live.pitchEnvDecayFrames,
live.pitchEnvPeakSemitones);
} else {
if (playMode_ == PlayMode::Gate) env_.applyLive(live.adsr);
pitchEnv_.applyLive(live.pitchEnvAttackFrames, live.pitchEnvDecayFrames,
live.pitchEnvPeakSemitones);
}
if (!filterOn_) return; // filter enable is a discrete toggle: it travels by reload
filterEnv_.applyLive(live.filterEnv);
if (snap) filterEnv_.snapLive(live.filterEnv);
else filterEnv_.applyLive(live.filterEnv);
filterCutoffNorm_ = static_cast<double>(live.filterSettings.cutoffNorm);
filterKeyTrack_ = live.filterKeyTrack;
filterSettings_.morphLaw = live.filterSettings.morphLaw;
+2 -2
View File
@@ -119,8 +119,8 @@ public:
// Applies the live-parameter block to a voice that is already sounding (or, with `snap`,
// to one just started). Called at BLOCK boundaries by VoiceEngine — never per frame — so
// the per-sample shape is unchanged; every continuous control glides toward its new value
// from here rather than jumping to it. `snap` takes the values outright: a fresh note has
// nothing to glide from, and its latched copy may predate the newest edit.
// from here rather than jumping to it. `snap` takes the values outright — glides AND
// envelopes: a fresh note has nothing to glide from, and its copy may predate the edit.
//
// What is NOT here is the point: velocity and its curve result, the note number and the
// pitch ratio, and the decoded PCM stay latched at note-on.
+32 -1
View File
@@ -119,9 +119,40 @@ bool isLiveDeckParam(DeckParam id) {
case DeckParam::kFilterEnvSustain:
case DeckParam::kFilterEnvRelease:
return true;
default:
// Listed rather than defaulted so a newly added control is a COMPILE error here (the
// -Wswitch gate is GCC/Clang; MSVC's C4062 is off at this project's warning level)
// instead of silently defaulting to non-live. Reasons live in the header.
case DeckParam::kPlayMode:
case DeckParam::kPitchEngine:
case DeckParam::kTrigLength:
case DeckParam::kTrigFadeIn:
case DeckParam::kTrigFadeOut:
case DeckParam::kPitchEnvEnable:
case DeckParam::kKeyTrack:
case DeckParam::kFilterEnable:
case DeckParam::kFilterVel:
case DeckParam::kFilterLaw:
case DeckParam::kVoiceCount:
case DeckParam::kVoiceMode:
case DeckParam::kMonoTrigger:
case DeckParam::kMasterGain:
case DeckParam::kCount: // not a control
return false;
}
return false; // unreachable for a valid enumerator; silences a warning.
}
bool liveCommitFor(LiveDragKind kind, int paramId, PlayMode playMode) {
switch (kind) {
case LiveDragKind::kDeckKnob:
return paramId >= 0 && paramId < static_cast<int>(DeckParam::kCount) &&
isLiveDeckParam(static_cast<DeckParam>(paramId));
case LiveDragKind::kEnvNode:
return playMode == PlayMode::Gate;
case LiveDragKind::kOther:
return false;
}
return false;
}
} // namespace reasampler::instrument::ui
+27 -7
View File
@@ -77,15 +77,35 @@ std::vector<DeckGroupDesc> sampleDeckGroups(PlayMode playMode);
// controls, so this is a routing decision at the editor's commit site rather than a property
// of any one knob; moving a control across the line is a change here and nowhere else.
//
// Deliberately NOT live, each for its own reason: the discrete toggles (play mode, pitch
// engine, filter enable/law, pitch-envelope enable) name a different sound rather than a
// different setting of one; the three capture-anchored overrides (root, loop span, start
// frame) name positions in the decoded PCM; pitch key-track and the velocity->cutoff depth
// feed values a voice latches at note-on by design (the pitch ratio and the velocity-curve
// result), so making them live would retune or re-gain a note already struck; and Trigger's
// %-length and fades resolve a play span that is a fact about the note.
// THE home for why each excluded control is excluded. Five continuous controls are outside the
// live set, plus every discrete toggle:
// - the discrete toggles (play mode, pitch engine, filter enable/law, pitch-envelope enable)
// name a different sound rather than a different setting of one;
// - the three capture-anchored overrides (root, loop span, start frame) name positions in
// the decoded PCM;
// - kKeyTrack and kFilterVel feed values a voice latches at note-on by design (the pitch
// ratio and the velocity-curve result), so live delivery would retune or re-gain a note
// already struck;
// - kTrigLength resolves playEnd_, a fact about the note. kTrigFadeIn/kTrigFadeOut are pure
// amplitude shape and would be live-able in principle, but they live in `sample.play` and
// are baked into SampleData at build time — the engine rebuild copies that verbatim, so
// only a reload can deliver them without widening LiveValues. They fold into the AHD
// alongside Gate's, at which point they inherit its routing; until then they reload.
// Consequence, stated plainly: a Trigger-mode instance gets NO live delivery on its amplitude
// controls. Only the filter and pitch-envelope knobs move a sounding Trigger one-shot.
bool isLiveDeckParam(DeckParam id);
// The editor drag kinds that can commit live, in this pure module's own vocabulary (the
// shell's DragKind maps onto it) so the WHOLE routing decision — not just the predicate — is
// testable without a host.
enum class LiveDragKind { kOther, kDeckKnob, kEnvNode };
// Whether a drag of `kind` commits live. A deck knob is live per isLiveDeckParam (negative ids
// are the shell's processor-side sentinels and out-of-range ids are not controls, so neither
// reaches the enum); an envelope-node drag is live only in Gate, where it edits the AHDSR —
// in Trigger the same drag rewrites the play span, which is not a live control.
bool liveCommitFor(LiveDragKind kind, int paramId, PlayMode playMode);
// The deck's BIPOLAR knob law: 0.5 of the knob's travel is zero depth, the ends are -1 and
// +1. Exact inverses, and exact at the centre detent (0.5 -> 0 -> 0.5), so a knob parked at
// centre can never persist a hair of modulation. Out-of-range norm clamps to the endpoints.
+5 -5
View File
@@ -68,7 +68,8 @@ scattered `#ifdef`s in the VST shell, except the one described below).
(`DEF_CLASS2` / `INLINE_UID` / `FUID` from `pluginfactory.h` + `funknown.h`).
**The three commit tiers (Θ-W3).** An edit reaches the audio by exactly one of three routes, and
which route a control takes is decided once, by the pure `isLiveDeckParam` predicate — see
which route a control takes is decided once, by the pure `isLiveDeckParam` / `liveCommitFor` pair
(`core/instrument/ui/deck_groups`) that the editor's `dragCommitsLive` only maps onto — see
`core/instrument/CLAUDE.md`'s "Live parameter delivery" for the rule and its rationale.
1. **Full reload**`reloadInstrument`: bridge read, WAV re-decode, fresh engine, snapshot swap.
2. **Engine rebuild**`rebuildVoiceEngine`: same drain-slot swap around the already-decoded
@@ -76,10 +77,9 @@ which route a control takes is decided once, by the pure `isLiveDeckParam` predi
3. **Live**`publishLiveParams` (and `masterGain_`, the original of the shape): a lock-free
publish the audio thread observes at block boundaries. No rebuild, no snapshot, no disk.
`liveParams_` is declared ahead of the instrument slots so it outlives every snapshot pointing at
it. The editor's `commitLive` is the tier-3 peer of `commitAndReload` and still writes the
parameter set, so persistence is unchanged — `getState` serializes `params_`, never a reload
artifact, and the reload was never the persistence trigger.
The editor's `commitLive` is the tier-3 peer of `commitAndReload`; why it still writes the
parameter set is recorded at its declaration in `reasampler_editor.h`, and why `liveParams_` is
declared ahead of the instrument slots at that member in `reasampler_processor.h`.
**Non-goals / guardrails.**
- The instrument never captures and never inserts into the arrange. Playback is a
+1 -1
View File
@@ -105,7 +105,7 @@ void ReaSamplerEditor::onMouseUp(int x, int y) {
return;
}
// A live control already reached the voices during the drag; its release commits the
// final value the same way — no bridge read, no WAV re-decode, no snapshot rebuild.
// final value through the same tier.
if (dragCommitsLive(kind, paramId)) {
commitLive();
invalidate();
+16 -6
View File
@@ -205,8 +205,8 @@ LRESULT CALLBACK ReaSamplerEditor::wndProc(HWND hwnd, UINT msg, WPARAM wParam,
case WM_RBUTTONUP:
return 0; // claimed so the pair never reaches DefWindowProc (no context menu)
case WM_CAPTURECHANGED:
// Capture stolen mid-drag (modal dialog, alt-tab, etc.) — restore map_ to its
// pre-grab snapshot so the in-flight live-drag mutation is rolled back, then reset
// Capture stolen mid-drag (modal dialog, alt-tab, etc.) — restore params_ to its
// pre-grab snapshot so the in-flight drag mutation is rolled back, then reset
// the drag state machine so stale capture-less WM_MOUSEMOVEs don't keep editing.
// Mirror of the panel shell's WM_CAPTURECHANGED handler (panel_window.cpp).
if (self) {
@@ -219,15 +219,25 @@ LRESULT CALLBACK ReaSamplerEditor::wndProc(HWND hwnd, UINT msg, WPARAM wParam,
}
if (self->drag_ != DragKind::kNone) {
// A scrollbar drag + the processor-side deck knobs (preview velocity -2 /
// voice count / master gain) are transient (they mutate no parameter, so
// dragStartParams_ is not a rollback target) — reset drag state only.
// Every parameter-editing drag rolls its live mutation back to the snapshot.
// voice count / master gain) mutate no parameter, so dragStartParams_ is
// not a rollback target for them — reset drag state only. Every
// parameter-editing drag restores the pre-grab snapshot.
const bool transient = self->drag_ == DragKind::kScrollThumb ||
(self->drag_ == DragKind::kDeckKnob &&
(self->dragParamId_ == -2 ||
self->dragParamId_ == static_cast<int>(ParamControl::kVoiceCount) ||
self->dragParamId_ == static_cast<int>(ParamControl::kMasterGain)));
if (!transient) self->params_ = self->dragStartParams_;
if (!transient) {
self->params_ = self->dragStartParams_;
// A live drag already reached the voices AND the processor's own
// parameter set on every move, so restoring params_ alone would leave
// the face painting one value while the audio plays — and getState
// persists — the abandoned one. Roll back through the same tier the
// drag used.
if (self->dragCommitsLive(self->drag_, self->dragParamId_)) {
self->commitLive();
}
}
self->drag_ = DragKind::kNone;
self->dragParamId_ = -1;
self->curvePointIndex_ = -1; // curve-node drag state (peer reset)
+8 -7
View File
@@ -144,13 +144,14 @@ void ReaSamplerEditor::commitLive() {
}
bool ReaSamplerEditor::dragCommitsLive(DragKind kind, int paramId) const {
if (kind == DragKind::kDeckKnob) {
// Negative ids are the processor-side sentinels (preview velocity), not parameter-set
// controls, so they never reach the enum.
return paramId >= 0 &&
instrument::ui::isLiveDeckParam(static_cast<ParamControl>(paramId));
}
return kind == DragKind::kEnvNode && params_.play.playMode == PlayMode::Gate;
// The decision itself is the pure liveCommitFor's; this is only the shell's drag-kind
// vocabulary mapped onto it, so the routing is pinned by deck_groups' tests rather than
// by inspection of this file.
using instrument::ui::LiveDragKind;
const LiveDragKind k = kind == DragKind::kDeckKnob ? LiveDragKind::kDeckKnob
: kind == DragKind::kEnvNode ? LiveDragKind::kEnvNode
: LiveDragKind::kOther;
return instrument::ui::liveCommitFor(k, paramId, params_.play.playMode);
}
void ReaSamplerEditor::loadSelection(const std::string& id) {
+7
View File
@@ -153,6 +153,13 @@ void ReaSamplerProcessor::setInstrumentParams(const InstrumentParams& params) {
}
void ReaSamplerProcessor::publishLiveParams() {
// reloadMutex_ enforces the block's SINGLE-WRITER contract (live_params.h), not the
// reload's slot bookkeeping: reloadInstrument publishes the block too, and two concurrent
// seqlock writers can leave the generation even mid-write, which a reader would accept as
// a coherent — but torn — block. The audio thread never takes this mutex, so the cost is
// an off-thread wait behind a reload. Lock order matches reloadInstrument's
// (reloadMutex_ then paramsMutex_, taken by instrumentParams below).
std::lock_guard<std::mutex> lock(reloadMutex_);
const int rate = builtSampleRate_.load(std::memory_order_relaxed);
if (rate <= 0) return;
liveParams_.publish(
+11 -5
View File
@@ -154,11 +154,10 @@ public:
// Republishes the live-parameter block from the stored parameter set, resolved against the
// rate the loaded capture was built at so an unmoved value folds to exactly the frames the
// voices already latched. THE tier-3 commit: no bridge read, no WAV re-decode, no engine
// rebuild, no snapshot swap — the sounding note follows the knob. Persistence is
// unaffected: getState still serializes params_, so callers pair this with
// setInstrumentParams exactly as they paired it with reloadInstrument. No-op before
// anything has been decoded (the next reload bakes and publishes). UI thread.
// voices already latched. THE tier-3 commit (the three tiers are listed in this
// directory's CLAUDE.md). Callers pair this with setInstrumentParams exactly as they
// paired it with reloadInstrument. No-op before anything has been decoded (the next reload
// bakes and publishes). UI thread; serialized against reloadInstrument's own publish.
void publishLiveParams();
// Per-instance channel mode (mono | stereo), guarded by channelModeMutex_, never read
@@ -243,6 +242,13 @@ private:
// The rate the loaded capture was decoded/built at, so a live republish resolves the
// stored wall-clock seconds to exactly the frames the built SampleData carries. 0 = nothing
// built yet.
//
// ONE BLOCK, ONE RATE: this is stamped by whichever capture built last, and a reload
// publishes the new block before installing the new instrument. Swapping to a capture at a
// different rate therefore hands drain voices still ringing from the old-rate capture
// envelope frame counts resolved at the NEW rate (~8.8% timing shift on a 48k->44.1k swap).
// Unavoidable while one block sits above every snapshot, and it touches a release tail
// only.
std::atomic<int> builtSampleRate_{0};
// --- The audio-thread handoff (drain slot) ---