Bake window: derived note lengths carry exact durations, not ladder rungs — a long take is no longer cut at 384 beats

Hold keeps its picker. Also: one home for the %-fold, duration-ordered Hold travel, and a corrupt tail degrades to absent rather than fabricating one.
This commit is contained in:
2026-08-01 21:10:38 -04:00
parent 19aeb92775
commit 65f6070348
35 changed files with 772 additions and 226 deletions
+4 -4
View File
@@ -281,7 +281,7 @@ anything for a trigger shape.
### `engine/`
- 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.
- `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. Also the ONE home of the drawn-EG rule family — `splineActive`, `effectivePlayMode`, `enforceGateUnavailableWhileDrawn` and `effectiveLengthFraction` — all templated over the frames and seconds representations, so no consumer of either can re-read the raw fields instead.
- `envelopes.h` — the three per-frame evaluators (`AdsrEnvelope` AHDSR, `AhdEnvelope` the sustain-less Attack/Hold/Decay, `PitchEnvelope` the AHD pitch offset), CONCRETE and fully header-inline. Never give them a common base or a virtual `tick()`: they are called per-voice-per-sample. Also home to `fitAhd`/`ahdLevelAt`, THE span split and shape every sustain-less envelope shares. A voice carries two of each shape — the amp's and the filter's — and its play mode picks which pair it reads. `AdsrEnvelope`/`PitchEnvelope` own `applyLive` (the φ-holding mid-stage rule), its fresh-note peer `snapLive`, and `StepSmoother`, the bounded offset that absorbs the level steps φ cannot cover; `AhdEnvelope` is POSITIONAL (evaluated at a source offset, not ticked), so it has no phase to hold and smooths a live reshape instead.
- `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`. **Documented ~600-line-ceiling exception** (root `CLAUDE.md` structural heuristic 1): `voice.h` sits over the ceiling because `advanceFrame`'s RT-inline constraint forbids the seam a split would need — a documented exception, not silent overshoot.
@@ -299,14 +299,14 @@ anything for a trigger shape.
- `params_payload` — the PARAMS-PAYLOAD half of that codec, split from the envelope half on the axis the format already has: the payload carries its own version and grows independently, so the two version ladders are two responsibilities. An INTERNAL seam — the public entry points stay `serialize`/`deserializeComponentState`. The prose ladder and every version constant stay in `component_state_io.h`, their one home.
- `bank_sync` — generation change-detection + assignment-request consume: owns the yes/no decision logic so the rules are provable without a host. The processor shell owns cadence and side effects.
- `bridge_marshal` — pure marshalling helper for the REAPER VST-host bridge read: interprets the `GetProjExtState` int return against its filled buffer.
- `trigger_seam` — the shared Trigger play-SPAN formula: how the stored %-length becomes the source-frame span the voice plays, the overlay draws over and the bake's window holds, threading `startFrame` correctly. Home to `effectiveLengthFraction`, the spline fold every one of those three must apply — the %-knob goes inert but stays STORED while a contour is drawn, so a raw read of it silently shortens whatever reads it. (Its fade frames↔fraction converters retired with the fade pair itself.)
- `trigger_seam` — the shared Trigger play-SPAN formula: how a %-length becomes the source-frame span the overlay draws over and the bake's window holds, threading `startFrame` correctly and clamping the fraction the same way `Voice::start` does (the engine evaluates the same formula inline rather than depending on `map/`). The spline fold every consumer must apply first — `effectiveLengthFraction` — is `play_params.h`'s, beside the rest of that rule family. (Its fade frames↔fraction converters retired with the fade pair itself.)
### `ui/`
- `editor_geometry` (`core/instrument/ui`) — the shared geometry VOCABULARY every instrument UI module speaks: the `core::ui::Rect` alias, `contains()`, and `OverlayArea` (a one-field `Rect` wrapper, no implicit conversion from `Rect`). Header-only (an INTERFACE CMake target), so it carries no layout of its own.
- `sample_bands` — **THE band-stack allocator**, and the only module that owns the Sample face's vertical inventory — including `kEditorMinWidth`/`kEditorMinHeight`, the editor's client-area floor, which IS its default size (the shell's `checkSizeConstraint` and opening `ViewRect` both read it; the face grows, never shrinks below what the stack is laid out for). Three bands top-to-bottom (CHROME toolbar+control row / WAVEFORM elastic, floored at two stacked lanes / DECKS bottom-anchored at the knob deck's own wrapped height), plus the waveform band's lane split (`waveformLanes` takes a resolved `LaneSplit`, not a raw bool — only `waveformSurface` folds the source-channel-count decision in). A shared READ-ONLY surface for every band owner — a band's interior module lays out inside the rect it is handed and never re-allocates the stack.
- `sample_chrome` — the CHROME band's interior: the toolbar row (title + the whole right-anchored control run — bake Hold cell, bake, preview, velocity knob cell, channel toggle, Browse) over the strip row, which the piano strip owns outright. The title takes what the run leaves; the strip takes its whole row, inset only by the shared band pad so it lines up with the waveform band beneath. Every run member's width is RESERVED unconditionally, the Hold cell included: the run is right-anchored, so laying a member out conditionally would slide its neighbours out from under the pointer. Also `previewGlyph`, the preview button's play triangle — three vertices for one filled-triangle draw, so the button's label needs no font metric and no image asset.
- `bake_hold` — the Hold knob's value domain and nothing else: the knob's normalized [0,1] mapped onto the note-length ladder and back. Split from `sample_chrome` on the same axis `deck_values` was split from `knob_deck` — that says where the cell is, this says what its position means.
- `sample_chrome` — the CHROME band's interior: the toolbar row (title + the whole right-anchored control run — bake Hold cell, bake, preview, velocity knob cell, channel toggle, Browse) over the strip row, which the piano strip owns outright. The title takes what the run leaves; the strip takes its whole row, inset only by the shared band pad so it lines up with the waveform band beneath. Every run member's width is RESERVED unconditionally, the Hold cell included the only conditionally-drawn one, and the leftmost, so what its reservation buys is a title slot that does not re-measure when a loop is dialled in or out (`sample_chrome.h` records the cost). Also `previewGlyph`, the preview button's play triangle — three vertices for one filled-triangle draw, so the button's label needs no font metric and no image asset.
- `bake_hold` — the Hold knob's value domain and nothing else: the knob's normalized [0,1] mapped onto the note-length ladder and back, ordered by LENGTH rather than by the ladder's presentation order. Split from `sample_chrome` on the same axis `deck_values` was split from `knob_deck` — that says where the cell is, this says what its position means.
- `keyboard_strip` — piano-keyboard strip: true white/black key geometry (whites tiled at one width, blacks overlaid at one width and height, straddling their boundary), hit-test resolving black-over-white by zone, root-marker rect, the absolute-position drag resolver, and MIDI note naming under the C4 convention. **Same-class keys are one integer width by construction; the residue of an indivisible band width (`w % 75`, up to 74 px) lands in symmetric end margins, never in a key** — uniform widths and gap-free edge-to-edge tiling cannot both hold, and uniformity wins.
- `waveform_view` — the WAVEFORM band's interior: `waveformSurface` resolves the drawn lane(s) (two stacked lanes, L over R, only when the mode is stereo AND the source has a second channel — a mono source under stereo mode is dual-mono and draws one lane) plus **the** overlay area, and `laneEnvelope` splits one multi-channel envelope pass per lane. Also maps frame span linearly across a rect; generic named draggable markers with drag-delta resolver, clamp, and zero-crossing snap, plus `markerHandleRect` — a top-strip grab tab distinct from a marker's full-height column, so two markers that share a frame stay independently grabbable (the column goes to the first in draw order; the tab, asked first, resolves the other).
- **Overlay contract (consumed by later waveform work).** `WaveformSurface::overlay` — equivalently the standalone `waveformOverlayArea(band)` — is the FULL band in both modes. Everything riding the waveform (the amp-envelope trace and its node handles, the start/loop markers, the loop region) draws ONCE into it, spanning both stacked lanes; hit-testing resolves against the same area so a grab in the lower lane reaches them. Anything drawn or hit-tested per lane is a duplicate and a defect — structurally enforced: `overlay` is the distinct `OverlayArea` type (`editor_geometry`), not `Rect`, so every overlay-consuming API (`frameToX`/`markerAtPoint`/`resolveDragFrame`, `envelope_edit`'s `nodeAtPoint`/`resolveNodeDrag`, `envelope_overlay`'s `buildEnvelopePolyline`) rejects a lane rect at compile time rather than silently accepting one.
+7 -5
View File
@@ -35,11 +35,13 @@ decision about what the render made obsolete.
source exhaustion, since the read head frees the voice whether or not the gate is down.
`bakeWindowNeedsHold` is the predicate, and it reads the ENGINE's loop fold rather than the
loop fields, so the control that collects Hold cannot appear for a loop the voice refuses.
- **Trailing silence is free; truncation is not.** Every derivation rounds outward — the Gate
note rounds UP to a programmable length that outlasts the source, the Varispeed bound takes
the deepest reachable offset, and every path is padded by the voice's terminal declick ramp
(`kDeclickFrames`, unconditionally — not branched on the pitch engine that has the ramp
today). Judge any change to this module against that asymmetry.
- **Trailing silence is free; truncation is not.** Every derivation errs outward — the
Varispeed bound takes the deepest reachable offset the voice can play, and every path is
padded by the voice's terminal declick ramp (`kDeclickFrames`, unconditionally — not branched
on the pitch engine that has the ramp today). Judge any change to this module against that
asymmetry. What it does NOT mean is quantizing: a derived length is an exact duration and a
finite ladder cannot express one (`note/CLAUDE.md`) — rounding up to a rung truncated any
source past the top rung, which is the failure this asymmetry exists to prevent.
- **The reset's survive list is written out; everything else defaults.** `resetAfterBake`
starts from a default-constructed parameter set and copies back only the mapping facts.
A parameter added later therefore resets by default — the safe direction, since
+13 -15
View File
@@ -7,7 +7,7 @@
#include "core/instrument/engine/loop/loop_span.h" // resolveLoop (the one sustain-loop fold)
#include "core/instrument/engine/voice.h" // kDeclickFrames (the terminal ramp length)
#include "core/instrument/map/trigger_seam.h" // the one Trigger span formula + %-fold
#include "core/instrument/map/trigger_seam.h" // triggerPlayLength (the one span formula)
namespace reasampler::instrument::bake {
@@ -71,9 +71,8 @@ bool bakeWindowNeedsHold(const SampleData& dialed) {
}
NoteProgram defaultBakeProgram(const SampleData& dialed, int renderSampleRate,
note::Tempo tempo, note::Division hold,
note::Velocity velocity) {
NoteProgram p; // 1/4 straight, capture opening at note-on
note::Division hold, note::Velocity velocity) {
NoteProgram p; // a quarter note, capture opening at note-on
p.velocity = velocity;
if (renderSampleRate <= 0) return p;
const double rate = static_cast<double>(renderSampleRate);
@@ -86,25 +85,24 @@ NoteProgram defaultBakeProgram(const SampleData& dialed, int renderSampleRate,
double endOffsetSeconds = 0.0;
if (dialed.play.playMode == PlayMode::Trigger) {
// Trigger ignores note-off entirely: the sound ends when the read head reaches the
// play span's end, which has nothing to do with the note's length — so the end
// offset is whatever is left after the note, positive or negative.
const std::int64_t span = map::triggerPlayLength(
map::effectiveLengthFraction(dialed.play), frameCount, start);
endOffsetSeconds = static_cast<double>(span) / rate * stretch -
tempo.beatsToSeconds(note::divisionBeats(p.length));
// play span's end. The note is that span, so the window closes on the sound rather
// than on a length the voice never consulted.
const std::int64_t span =
map::triggerPlayLength(effectiveLengthFraction(dialed.play), frameCount, start);
p.length = note::lengthOfSeconds(static_cast<double>(span) / rate * stretch);
} else if (bakeWindowNeedsHold(dialed)) {
// The loop cycles for as long as the note is held, so the hold IS the length, and the
// release is the one stage that runs after note-off.
p.length = hold;
p.length = note::lengthOfDivision(hold);
endOffsetSeconds = releaseSeconds;
} else {
// Gate with no loop: the read head runs off the source and frees the voice whether or
// not the gate is still down, so the maximal sound is the whole post-start span held.
// Rounding the note UP to a programmable length that outlasts it costs nothing — the
// voice is already gone by then — while a shorter note releases mid-attack.
// Exact, not a ladder rung: a source longer than the ladder's top rung would otherwise
// take that rung and release mid-sound, and rounding up to one costs trailing silence
// on every other source.
const std::int64_t postStart = (std::max)(std::int64_t{0}, frameCount - start);
const double exhaustSeconds = static_cast<double>(postStart) / rate * stretch;
p.length = note::shortestDivisionAtLeast(tempo.secondsToBeats(exhaustSeconds));
p.length = note::lengthOfSeconds(static_cast<double>(postStart) / rate * stretch);
endOffsetSeconds = releaseSeconds;
}
// The voice rings its last output out over kDeclickFrames instead of hard-cutting it, and
+11 -7
View File
@@ -31,21 +31,25 @@ bool bakeWindowNeedsHold(const SampleData& dialed);
// The bake's programmed note, DERIVED from the dialed sound at `renderSampleRate` (the rate
// the bake renders at, which is what the engine's frame counts are consumed against):
//
// Trigger — note length is nominal (note-off is ignored); the end offset carries the
// whole play span, stretched by the deepest downward Varispeed offset.
// Trigger — the note IS the play span (note-off is ignored anyway), stretched by the
// deepest downward Varispeed offset.
// Gate, loop — `hold` is the note length; the end offset is the release.
// Gate, no loop— the read head runs off the source and frees the voice whatever the gate is
// doing, so the note is rounded UP to the shortest programmable length that
// outlasts the source. Holding longer than that sounds identical, which is
// what makes the overshoot trailing silence rather than a different sound.
// doing, so the note is the whole post-start span, stretched the same way.
//
// Both derived lengths are EXACT durations, not ladder rungs: a source longer than the
// ladder's top rung has no rung that covers it, and quantizing up to one overshoots every
// other source (see note/CLAUDE.md). `hold` alone stays musical — it is a picker.
//
// Every case is padded by the voice's terminal declick ramp (kDeclickFrames): trailing
// silence is free, and closing the window on the frame the ramp starts is a hard cut.
// `hold` is read only in the Gate-with-loop case; `velocity` is the velocity the note fires
// at, and it feeds the Varispeed stretch as well as the render.
//
// Takes no tempo: nothing derived here is beat-denominated. The one field that is — `hold` —
// meets the tempo in resolveNote, with the rest of the program's beat-denominated fields.
note::NoteProgram defaultBakeProgram(const SampleData& dialed, int renderSampleRate,
note::Tempo tempo, note::Division hold,
note::Velocity velocity);
note::Division hold, note::Velocity velocity);
// The render window in frames. TWO domains meet here: `totalFrames` is the captured FILE's
// length, everything else counts RENDER frames from whichever comes first, note-on or the
+21 -5
View File
@@ -195,13 +195,29 @@ bool splineActive(const Play& p) {
(p.filter.enabled && p.filterSpline.mode == EnvMode::Spline);
}
// The one enforcement of splineActive's rule (see its doc above). Header-inline and
// allocation-free: play_params.h sits on the per-voice-per-sample include path. Both callers —
// resolvePlay (sample_map.cpp) and the editor's applyControl — route through here, so the two
// cannot drift apart.
// The mode the engine will actually run, and the one home of splineActive's rule (see its doc
// above). Header-inline and allocation-free: play_params.h sits on the per-voice-per-sample
// include path. Every caller — resolvePlay (sample_map.cpp), the editor's applyControl, and
// the editor's read-only predicates — routes through one of these two, so none of them can
// drift into a second reading of the fields.
template <class Play>
PlayMode effectivePlayMode(const Play& p) {
return splineActive(p) ? PlayMode::Trigger : p.playMode;
}
template <class Play>
void enforceGateUnavailableWhileDrawn(Play& p) {
if (splineActive(p)) p.playMode = PlayMode::Trigger;
p.playMode = effectivePlayMode(p);
}
// The %-length the voice ACTUALLY plays. Same rule family, same reason it is templated: a drawn
// contour is a pure time function over the full sample length, so any active spline EG folds
// the fraction to 1.0 while the stored knob goes inert — but the stored value survives, so a
// pre-spline setting is still there to be read. Every consumer of the Trigger span must fold it
// here or it silently plays/draws/bakes a fraction of the take.
template <class Play>
double effectiveLengthFraction(const Play& p) {
return splineActive(p) ? 1.0 : p.trigger.lengthFraction;
}
// [start, end) frames, half-open. A zero-length loop (start == end) is the "no sustain loop"
+7 -8
View File
@@ -6,8 +6,6 @@
#include <algorithm>
#include "core/instrument/map/trigger_seam.h" // effectiveLengthFraction (the one %-length rule)
namespace reasampler {
void Voice::presizePreserveShifters(std::int64_t windowFrames) {
@@ -103,12 +101,13 @@ void Voice::start(int note, int velocity, const SampleData& sample, bool declick
env_.noteOn();
playEnd_ = 0; // unused in Gate
} else {
// Trigger: play [start, playEnd) where playEnd = start + round(frac*(frames-start)).
// The spline fold lives in effectiveLengthFraction (trigger_seam.h), which the bake's
// window derivation reads too — a second copy of it here is what let a stored-but-inert
// %-knob shorten the bake while the voice played the whole take.
double frac = instrument::map::effectiveLengthFraction(p);
if (frac <= 0.0) frac = 0.0; // %=0 -> zero play length (finishes immediately)
// Trigger: play [start, playEnd) where playEnd = start + round(frac*(frames-start))
// map/trigger_seam.h's formula, evaluated inline because the engine does not depend on
// map/. The spline fold is effectiveLengthFraction (play_params.h); a second copy of it
// here is what let a stored-but-inert %-knob shorten the bake while the voice played
// the whole take.
double frac = effectiveLengthFraction(p);
if (!(frac > 0.0)) frac = 0.0; // %=0 (or a corrupt NaN) -> finishes immediately
if (frac > 1.0) frac = 1.0;
std::int64_t playLen = static_cast<std::int64_t>(
static_cast<double>(postStart) * frac + 0.5); // round
+3 -3
View File
@@ -2,9 +2,9 @@ reasampler_pure_library(bridge_marshal SOURCES bridge_marshal.cpp)
reasampler_test(bridge_marshal LINK bridge_marshal)
reasampler_pure_library(trigger_seam SOURCES trigger_seam.cpp)
# The %-length fold lives beside the span formula, so the header reads play_params' value
# layer; the test links that set and nothing else still no engine, no editor geometry.
reasampler_test(trigger_seam LINK trigger_seam velocity_curve peaks filter curve_law)
# Plain frame arithmetic over doubles: no engine, no value layer, no editor geometry. The
# %-length fold it used to host lives with its siblings in play_params.h.
reasampler_test(trigger_seam LINK trigger_seam)
reasampler_pure_library(bank_sync
SOURCES bank_sync.cpp
+45 -14
View File
@@ -94,24 +94,41 @@ void liftTriggerFades(std::int64_t fadeInFrames, std::int64_t fadeOutFrames, dou
out.decayCurve = kTriggerFadeLiftDecayCurve;
}
// A wire double whose consumers assume a domain they cannot check: the seconds fields reach
// resolvePlay's static_cast<std::int64_t> and peakSemitones reaches the bake's pow() and the
// voice's ratio multiply — both undefined or poisoning on NaN. Degrades to the field's own
// construction default, so a damaged blob loses that field rather than the record.
double finiteOr(double v, double fallback) { return std::isfinite(v) ? v : fallback; }
// A root-note override off the wire. Clamped HERE and not only where it is consumed: planBake
// clamps the note it renders at into MIDI range while the SampleData keeps the raw override as
// its root, and the two disagreeing makes the read rate something other than 1 — which
// mis-sizes the bake's window in the truncating direction.
int clampMidiNote(int note) { return (std::max)(0, (std::min)(127, note)); }
// Read the play tail (v5 shape onward) into `p`. Shared by the legacy zone reader and the
// v8 single-record reader so the two can never disagree about field order.
void readSecondsPlayTail(ByteReader& r, InstrumentParams& p, double projectRate) {
const PlaySeconds fallback; // the construction defaults, read rather than restated
p.play.playMode = (r.u8() != 0) ? PlayMode::Trigger : PlayMode::Gate;
p.play.adsr.holdSeconds = bitsToDouble(r.u64());
p.play.trigger.lengthFraction = bitsToDouble(r.u64());
p.play.adsr.holdSeconds = finiteOr(bitsToDouble(r.u64()), fallback.adsr.holdSeconds);
p.play.trigger.lengthFraction =
finiteOr(bitsToDouble(r.u64()), fallback.trigger.lengthFraction);
const std::int64_t fadeIn = r.i64();
const std::int64_t fadeOut = r.i64();
liftTriggerFades(fadeIn, fadeOut, projectRate, p.play.trigAhd);
p.play.pitchEngine = (r.u8() != 0) ? PitchEngine::Preserve : PitchEngine::Varispeed;
p.play.pitchEnv.enabled = (r.u8() != 0);
p.play.pitchEnv.shape.attackSeconds = bitsToDouble(r.u64());
p.play.pitchEnv.shape.decaySeconds = bitsToDouble(r.u64());
p.play.pitchEnv.peakSemitones = bitsToDouble(r.u64());
p.play.adsr.attackSeconds = bitsToDouble(r.u64());
p.play.adsr.decaySeconds = bitsToDouble(r.u64());
p.play.adsr.sustainLevel = bitsToDouble(r.u64());
p.play.adsr.releaseSeconds = bitsToDouble(r.u64());
p.play.pitchEnv.shape.attackSeconds =
finiteOr(bitsToDouble(r.u64()), fallback.pitchEnv.shape.attackSeconds);
p.play.pitchEnv.shape.decaySeconds =
finiteOr(bitsToDouble(r.u64()), fallback.pitchEnv.shape.decaySeconds);
p.play.pitchEnv.peakSemitones =
finiteOr(bitsToDouble(r.u64()), fallback.pitchEnv.peakSemitones);
p.play.adsr.attackSeconds = finiteOr(bitsToDouble(r.u64()), fallback.adsr.attackSeconds);
p.play.adsr.decaySeconds = finiteOr(bitsToDouble(r.u64()), fallback.adsr.decaySeconds);
p.play.adsr.sustainLevel = finiteOr(bitsToDouble(r.u64()), fallback.adsr.sustainLevel);
p.play.adsr.releaseSeconds = finiteOr(bitsToDouble(r.u64()), fallback.adsr.releaseSeconds);
}
// Read a velocity curve tail into `curve`, interpreting its y values in `domain` — the domain
@@ -170,6 +187,14 @@ void readSplineEnv(ByteReader& r, SplineEnv& s) {
reasampler::instrument::engine::CurveDomain::Unipolar);
}
// A block whose declared length overruns what the blob still holds has no realignment point:
// every byte after it belongs to a block that was truncated, so a later tail that reads them
// as its own gets an ARBITRARY value — and a tail that clamps (the bake Hold does) turns that
// into a legal-looking fabrication rather than an obvious one. Draining is what makes the
// stream's end honest: each later tail then reads past it and degrades to absent through its
// own revive, while the record that parsed cleanly ahead of the damage survives.
void drainUnaligned(ByteReader& r) { r.pos = r.bytes.size(); }
// Apply a hard-flag tail to an already-read velocity curve. A count that disagrees with the
// curve fromPoints actually produced — including an out-of-bounds or truncated one — is
// dropped rather than applied to shifted knots, and the whole params record parsed ahead of
@@ -185,7 +210,10 @@ void readHardFlags(ByteReader& r, VelocityCurve& curve) {
return;
}
const std::size_t remaining = r.bytes.size() > r.pos ? r.bytes.size() - r.pos : 0;
if (count > remaining) return; // bound-and-skip: cannot safely reserve/read this many
if (count > remaining) {
drainUnaligned(r); // the flags this count promised are not all there
return;
}
std::vector<std::uint8_t> flags;
flags.reserve(count);
for (std::uint32_t i = 0; i < count; ++i) flags.push_back(r.u8());
@@ -306,7 +334,7 @@ PayloadRead readLegacyZonePayload(ByteReader& r, std::uint32_t pv, double projec
r.i32(); // lowNote — the retired key range; read to keep the record walk aligned
r.i32(); // highNote
const std::uint8_t hasOverride = r.u8();
if (hasOverride) p.rootOverride = r.i32();
if (hasOverride) p.rootOverride = clampMidiNote(r.i32());
if (extended) {
const std::uint8_t hasLoop = r.u8();
if (hasLoop) {
@@ -325,9 +353,11 @@ PayloadRead readLegacyZonePayload(ByteReader& r, std::uint32_t pv, double projec
// are source-timeline, read as-is. A/D/S/R are ABSENT in v3 -> keep the defaults.
assert(projectRate > 0.0 && "readLegacyZonePayload: projectRate must be > 0 for v3 lift");
const double liftRate = projectRate > 0.0 ? projectRate : 1.0; // avoids div-by-zero; assert fires first
const PlaySeconds fallback; // same guard as readSecondsPlayTail's peer fields
p.play.playMode = (r.u8() != 0) ? PlayMode::Trigger : PlayMode::Gate;
p.play.adsr.holdSeconds = static_cast<double>(r.i64()) / liftRate;
p.play.trigger.lengthFraction = bitsToDouble(r.u64());
p.play.trigger.lengthFraction =
finiteOr(bitsToDouble(r.u64()), fallback.trigger.lengthFraction);
const std::int64_t fadeIn = r.i64();
const std::int64_t fadeOut = r.i64();
liftTriggerFades(fadeIn, fadeOut, liftRate, p.play.trigAhd);
@@ -335,7 +365,8 @@ PayloadRead readLegacyZonePayload(ByteReader& r, std::uint32_t pv, double projec
p.play.pitchEnv.enabled = (r.u8() != 0);
p.play.pitchEnv.shape.attackSeconds = static_cast<double>(r.i64()) / liftRate;
p.play.pitchEnv.shape.decaySeconds = static_cast<double>(r.i64()) / liftRate;
p.play.pitchEnv.peakSemitones = bitsToDouble(r.u64());
p.play.pitchEnv.peakSemitones =
finiteOr(bitsToDouble(r.u64()), fallback.pitchEnv.peakSemitones);
} else if (secondsPlay) {
readSecondsPlayTail(r, p, projectRate);
}
@@ -457,7 +488,7 @@ PayloadRead readParamsPayload(ByteReader& r, double projectRate) {
PayloadRead out;
InstrumentParams& p = out.params;
const std::uint8_t hasRoot = r.u8();
if (hasRoot) p.rootOverride = r.i32();
if (hasRoot) p.rootOverride = clampMidiNote(r.i32());
const std::uint8_t hasLoop = r.u8();
if (hasLoop) {
SampleLoop lp;
+4 -2
View File
@@ -10,8 +10,10 @@ std::int64_t triggerPlayLength(double lengthFraction,
std::int64_t frameCount,
std::int64_t startFrame) {
const std::int64_t postStart = (std::max)(std::int64_t{0}, frameCount - startFrame);
if (postStart <= 0 || lengthFraction <= 0.0) return 0;
return static_cast<std::int64_t>(lengthFraction * static_cast<double>(postStart) + 0.5);
if (postStart <= 0 || !(lengthFraction > 0.0)) return 0; // also catches NaN
const double frac = (std::min)(1.0, lengthFraction);
const auto len = static_cast<std::int64_t>(frac * static_cast<double>(postStart) + 0.5);
return (std::min)(postStart, (std::max)(std::int64_t{0}, len));
}
} // namespace reasampler::instrument::map
+11 -20
View File
@@ -1,32 +1,23 @@
// trigger_seam — the shared Trigger play-span formula: how the stored %-length becomes the
// source-frame span the voice plays, the overlay draws over, and the bake's window holds.
// One home so those three cannot disagree about where a Trigger note ends.
// trigger_seam — the shared Trigger play-span formula: how a %-length becomes the source-frame
// span the voice plays, the overlay draws over, and the bake's window holds. One home so those
// cannot disagree about where a Trigger note ends.
//
// playLengthFrames = round(effectiveLengthFraction * (frameCount - startFrame))
// playLengthFrames = round(clamp01(lengthFraction) * (frameCount - startFrame))
#pragma once
#include <cstdint>
#include "core/instrument/engine/play_params.h" // splineActive (the %-knob's inert rule)
namespace reasampler::instrument::map {
// The %-length the voice ACTUALLY plays. A drawn contour is a pure time function over the
// full sample length, so any active spline EG folds the fraction to 1.0 and the stored knob
// goes inert (splineActive, play_params.h) — but the stored value survives, so a pre-spline
// setting is still there to be read. Every consumer of the span must fold it here or it
// silently plays/draws/bakes a fraction of the take.
// `startFrame` is the effective start point (0 when absent), `lengthFraction` the EFFECTIVE one
// — fold it through effectiveLengthFraction (play_params.h) first, or a stored-but-inert %-knob
// shortens the span. Returns 0 for an empty post-start span and for any fraction that is not
// above zero, NaN included; the fraction is clamped to 1.0 and the result to the span, so a
// corrupt stored value cannot reach past the source.
//
// Templated over the two parameter representations for the same reason splineActive is.
template <class Play>
double effectiveLengthFraction(const Play& p) {
return splineActive(p) ? 1.0 : p.trigger.lengthFraction;
}
// postStart = max(0, frameCount - startFrame); playLength = round(lengthFraction * postStart).
// `startFrame` is the effective start point (0 when absent), `lengthFraction` the EFFECTIVE
// one above. Returns 0 when postStart == 0 or lengthFraction <= 0.
// Voice::start evaluates this same clamped formula inline rather than calling it: the engine
// does not depend on `map/`, in either direction.
std::int64_t triggerPlayLength(double lengthFraction,
std::int64_t frameCount,
std::int64_t startFrame);
+16 -7
View File
@@ -13,7 +13,8 @@ is a performance *description* plus its arithmetic, read by two consumers that m
diverge: the bake that renders it, and any surface that comes to edit it. Today the bake
DERIVES the whole record from the dialed sound rather than asking for it — the one field a
derivation cannot supply is the Gate-over-a-loop note length, and that arrives as a single
`Division` (see `bake/CLAUDE.md`), not as a hand-programmed record.
`Division` (see `bake/CLAUDE.md`), not as a hand-programmed record. Everything else it
derives is an exact duration; see the note-length invariant below.
## Invariants
@@ -26,9 +27,17 @@ derivation cannot supply is the Gate-over-a-loop note length, and that arrives a
directory — `Tempo` has no default and cannot be constructed without one.
- **Resolved times are rate-free seconds.** The standing ruling: no sample rate appears
here; the caller converts seconds to frames against the live rate.
- **Note length is musical-division-only.** Offsets carry the ms/beats duality; the note
length does not. A free-duration note length would make two records describe the same
performance at one tempo and different performances at another.
- **A note length is EITHER a musical division or an exact duration, and which one says who
produced it.** *(Amends the earlier "musical-division-only" rule, which was settled when
every length was hand-programmed through a picker.)* A PICKED length stays a `Division`: a
picker's rungs are the point, and the tempo-relative reading — the same record meaning a
different duration at a different tempo — is what the user asked for. A DERIVED length is
exact seconds, because the ladder is finite: a source longer than its top rung has no rung
that covers it, so quantizing up saturates and releases the note mid-sound, and on every
shorter source it buys trailing silence for nothing. `NoteLength` holds one or the other and
`noteLengthSeconds` resolves both, so no reader can pick the wrong denomination. Today the
bake is the only producer of each: its window derivations are exact, and the Gate-over-a-loop
Hold knob is the one picker.
- **A division persists as its `{quarterExponent, modifier}` pair, never as its picker
index.** The index is presentation order and would silently re-map every saved record if
the ladder ever gained a rung or a modifier.
@@ -64,9 +73,9 @@ derivation cannot supply is the Gate-over-a-loop note length, and that arrives a
to. `fromBpm` validates by running the extreme conversions rather than by testing the
`60/bpm` reciprocal they start from — that reciprocal stays finite well past the point the
multiply after it overflows.
- `note_program``Velocity` (clamped 1..127), the denominated `OffsetAmount` and its unit
toggle, the anchored `StartOffset` / `EndOffset`, the `NoteProgram` record, and
`resolveNote`.
- `note_program``Velocity` (clamped 1..127), the two-denomination `NoteLength` and its
resolver, the denominated `OffsetAmount` and its unit toggle, the anchored `StartOffset` /
`EndOffset`, the `NoteProgram` record, and `resolveNote`.
## Gotchas
@@ -68,7 +68,10 @@ Division shortestDivisionAtLeast(double beats) {
if (b > longestBeats) { longest = d; longestBeats = b; }
if (b >= beats && (!found || b < bestBeats)) { best = d; bestBeats = b; found = true; }
}
if (!(beats > 0.0)) return divisionAt(0); // also catches NaN
// NaN names no length to be at least, so it takes the never-short direction rather than
// the bottom rung: a corrupt value must not resolve to a near-instant note.
if (std::isnan(beats)) return longest;
if (!(beats > 0.0)) return divisionAt(0);
return found ? best : longest;
}
+5 -4
View File
@@ -69,10 +69,11 @@ double divisionBeats(Division d);
Division divisionAt(int index);
int divisionIndex(Division d);
// The shortest ladder length that is at least `beats` — the rung a caller reaches for when a
// derived duration has to be expressed as a programmable note and overshooting is the safe
// direction. Nothing long enough (or a non-finite `beats`) yields the top rung; a
// non-positive one yields the bottom.
// The shortest ladder length that is at least `beats` — for a caller quantizing a duration ONTO
// the ladder, where overshooting is the safe direction. It is NOT how a derived duration reaches
// the bake: nothing on a finite ladder covers an arbitrarily long source (see note/CLAUDE.md).
// Nothing long enough, or a non-finite `beats`, yields the top rung; a non-positive one yields
// the bottom.
Division shortestDivisionAtLeast(double beats);
// The notation divisions are named in: "1/16", "1/8.", "1/4t", "4/1".
+21 -1
View File
@@ -31,6 +31,26 @@ OffsetAmount offsetOf(double magnitude, Denomination denomination) {
return OffsetAmount(bounded, named ? denomination : Denomination::Milliseconds);
}
NoteLength lengthOfDivision(Division division) { return NoteLength(division, 0.0, false); }
NoteLength lengthOfSeconds(double seconds) {
const double bounded = std::isnan(seconds)
? 0.0
: (std::max)(0.0, (std::min)(kMaxLengthSeconds, seconds));
return NoteLength(Division{}, bounded, true);
}
bool operator==(NoteLength a, NoteLength b) {
if (a.exact_ != b.exact_) return false;
return a.exact_ ? a.seconds_ == b.seconds_ : a.division_ == b.division_;
}
bool operator!=(NoteLength a, NoteLength b) { return !(a == b); }
double noteLengthSeconds(NoteLength length, Tempo tempo) {
return length.exact_ ? length.seconds_ : tempo.beatsToSeconds(divisionBeats(length.division_));
}
OffsetAmount offsetFromMs(double ms) { return offsetOf(ms, Denomination::Milliseconds); }
OffsetAmount offsetFromBeats(double beats) { return offsetOf(beats, Denomination::Beats); }
@@ -94,7 +114,7 @@ bool operator!=(const NoteProgram& a, const NoteProgram& b) { return !(a == b);
ResolvedNote resolveNote(const NoteProgram& program, Tempo tempo) {
ResolvedNote out;
out.noteOffSeconds = tempo.beatsToSeconds(divisionBeats(program.length));
out.noteOffSeconds = noteLengthSeconds(program.length, tempo);
out.captureStartSeconds = offsetSeconds(program.start.amount(), tempo);
const double rawEndSeconds = out.noteOffSeconds + offsetSeconds(program.end.amount(), tempo);
// An inverted window has no meaning to a renderer, so a far-negative end offset yields a
+42 -1
View File
@@ -85,6 +85,47 @@ OffsetAmount redenominate(OffsetAmount amount, Denomination to, Tempo tempo);
OffsetAmount withMsView(OffsetAmount amount, double ms, Tempo tempo);
OffsetAmount withBeatsView(OffsetAmount amount, double beats, Tempo tempo);
// The largest exact note length, in seconds — the ms ceiling restated in the unit an exact
// length is entered in, so a length and an offset cap at the same instant.
inline constexpr double kMaxLengthSeconds = msToSeconds(kMaxConvertibleMagnitude);
class NoteLength;
// The two doors. A DERIVED length is exact: `lengthOfSeconds` is what every computed duration
// takes, and rounding one onto the ladder is what truncates a source longer than the ladder's
// top rung. A PICKED length is a `Division`, because a picker's rungs are the point. Both
// clamp: a negative or NaN duration names no length and becomes zero, a magnitude past
// kMaxLengthSeconds clamps to it, and `makeDivision` already holds the rung's own domain.
NoteLength lengthOfDivision(Division division);
NoteLength lengthOfSeconds(double seconds);
// One length, in whichever denomination its door established. There is no accessor per
// denomination: `noteLengthSeconds` resolves both, so no reader can pick the wrong one.
class NoteLength {
public:
NoteLength() = default; // a quarter note — Division's own default
private:
NoteLength(Division division, double seconds, bool exact)
: division_(division), seconds_(seconds), exact_(exact) {}
friend NoteLength lengthOfDivision(Division division);
friend NoteLength lengthOfSeconds(double seconds);
friend double noteLengthSeconds(NoteLength length, Tempo tempo);
friend bool operator==(NoteLength a, NoteLength b);
Division division_{};
double seconds_ = 0.0;
bool exact_ = false;
};
static_assert(!std::is_constructible_v<NoteLength, Division>,
"lengthOfDivision must be the only way to give a NoteLength a rung");
bool operator==(NoteLength a, NoteLength b);
bool operator!=(NoteLength a, NoteLength b);
double noteLengthSeconds(NoteLength length, Tempo tempo);
// Two types rather than one carrying an anchor field: the anchor is then unswappable at
// compile time. Sign is uniform — positive is later in time — so a capture that opens before
// the note is a negative start offset, and a negative end offset truncates before release.
@@ -114,7 +155,7 @@ static_assert(!std::is_convertible_v<OffsetAmount, StartOffset>,
"the anchor constructor must stay explicit");
struct NoteProgram {
Division length{};
NoteLength length{};
StartOffset start{};
EndOffset end{};
Velocity velocity{};
+42 -7
View File
@@ -3,23 +3,58 @@
#include "core/instrument/ui/bake_hold.h"
#include <algorithm>
#include <array>
namespace reasampler::instrument::ui {
namespace {
constexpr int kLastIndex = note::kDivisionCount - 1;
constexpr int kLastSlot = note::kDivisionCount - 1;
using Order = std::array<int, note::kDivisionCount>;
// Slot -> picker index, sorted by LENGTH. The ladder's own order is presentation order, in
// which a rung's triplet is shorter than the previous rung's dotted (musical_division.cpp) —
// so addressing it directly makes a knob whose whole meaning is duration shorten the note at
// every rung boundary. Built once; every length on the ladder is distinct, so the sort is total.
const Order& bySlot() {
static const Order order = [] {
Order a{};
for (int i = 0; i < note::kDivisionCount; ++i) a[static_cast<std::size_t>(i)] = i;
std::sort(a.begin(), a.end(), [](int l, int r) {
return note::divisionBeats(note::divisionAt(l)) <
note::divisionBeats(note::divisionAt(r));
});
return a;
}();
return order;
}
// The inverse: picker index -> slot.
const Order& toSlot() {
static const Order inverse = [] {
Order a{};
const Order& forward = bySlot();
for (int slot = 0; slot < note::kDivisionCount; ++slot)
a[static_cast<std::size_t>(forward[static_cast<std::size_t>(slot)])] = slot;
return a;
}();
return inverse;
}
} // namespace
note::Division bakeHoldFromNorm(double norm) {
if (!(norm > 0.0)) return note::divisionAt(0); // also catches NaN
if (norm >= 1.0) return note::divisionAt(kLastIndex);
// Round to nearest so each rung owns an equal slice of the knob's travel; divisionAt
// clamps, so the +0.5 landing on kDivisionCount at norm just under 1 is harmless.
return note::divisionAt(static_cast<int>(norm * kLastIndex + 0.5));
if (!(norm > 0.0)) return note::divisionAt(bySlot()[0]); // also catches NaN
if (norm >= 1.0) return note::divisionAt(bySlot()[kLastSlot]);
// Round to nearest so each rung owns an equal slice of the knob's travel.
const int slot = static_cast<int>(norm * kLastSlot + 0.5);
return note::divisionAt(bySlot()[static_cast<std::size_t>(slot)]);
}
double bakeHoldNorm(note::Division hold) {
return static_cast<double>(note::divisionIndex(hold)) / static_cast<double>(kLastIndex);
const int slot = toSlot()[static_cast<std::size_t>(note::divisionIndex(hold))];
return static_cast<double>(slot) / static_cast<double>(kLastSlot);
}
} // namespace reasampler::instrument::ui
+6 -4
View File
@@ -1,14 +1,16 @@
#pragma once
// bake_hold — how one radial knob addresses the note-length ladder: the Hold control's
// normalized [0,1] position mapped onto a Division and back. The ladder and its picker order
// are musical_division's; nothing about them is restated here.
// normalized [0,1] position mapped onto a Division and back. The ladder itself is
// musical_division's; only the knob's travel ORDER is decided here.
#include "core/instrument/note/musical_division.h"
namespace reasampler::instrument::ui {
// [0,1] across the ladder in picker order (shortest rung first). Out-of-range or non-finite
// input clamps to an end rather than wrapping — a knob cannot express anything else.
// [0,1] across the ladder ordered by LENGTH, shortest first — NOT the ladder's picker order,
// which is presentation order and would shorten the note at every rung boundary. Out-of-range
// or non-finite input clamps to an end rather than wrapping — a knob cannot express anything
// else.
note::Division bakeHoldFromNorm(double norm);
// The inverse: the position that reproduces `hold` exactly, so a knob painted from a stored
+5 -3
View File
@@ -19,9 +19,11 @@ struct ChromeRects {
Rect toolbar; // full-width top row
Rect title; // the title text slot: the toolbar left of the control run
// The bake Hold cell. Its width is RESERVED unconditionally even though the control is
// only load-bearing for a looped Gate sound (bake_plan.h's bakeWindowNeedsHold): the run
// is right-anchored, so laying it out conditionally would slide Bake and Preview out from
// under the pointer whenever a loop is dialled in or out.
// only drawn for a looped Gate sound (bake_plan.h's bakeWindowNeedsHold). It is the
// LEFTMOST member of the right-anchored run, so no other member moves either way — what
// the reservation buys is a title slot that holds still: dialling a loop in or out would
// otherwise re-measure and re-ellipsize the capture name. The cost is ~62 px of dead
// toolbar in the common non-looped case.
Rect holdCell; // ---- the right-anchored run, left to right ----
Rect holdKnob;
Rect holdLabel;
+7
View File
@@ -118,6 +118,13 @@ void ReaSamplerEditor::onMouseUp(int x, int y) {
invalidate();
return;
}
// A bare click on the Hold cell — no drag, no value change — would otherwise buy a bridge
// read, a WAV re-decode and an engine rebuild for a parameter the engine never reads.
if (kind == DragKind::kDeckKnob && paramId == kBakeHoldKnobId &&
params_.bakeHold == dragStartParams_.bakeHold) {
invalidate();
return;
}
// A live control already reached the voices during the drag; its release commits the
// final value through the same tier.
if (dragCommitsLive(kind, paramId)) {
+7 -3
View File
@@ -109,9 +109,13 @@ bool ReaSamplerEditor::doubleClickChrome(const FaceLayout& fl, int x, int y) {
if (selectedId_.empty() || !processor_) return false;
if (bakeHoldNeeded_ && inKnobFace(fl.chrome.holdKnob, x, y)) {
// The default is READ off a default-constructed parameter set, so there is no second
// table of defaults to drift from the codec's own lift.
params_.bakeHold = InstrumentParams{}.bakeHold;
commitAndReload();
// table of defaults to drift from the codec's own lift. A reset that changes nothing
// commits nothing — the same rule the release path applies.
const instrument::note::Division reset = InstrumentParams{}.bakeHold;
if (params_.bakeHold != reset) {
params_.bakeHold = reset;
commitAndReload();
}
invalidate();
return true;
}
+3 -1
View File
@@ -156,9 +156,11 @@ void ReaSamplerEditor::paintChrome(LICE_IBitmap* bmp, const FaceLayout& fl, bool
: (hov ? InteractionState::Hover
: InteractionState::Rest);
drawKnobFace(bmp, cr.holdKnob, bakeHoldNorm(), st);
// "Bake Hold", not "Hold": the AMP deck's AHDSR Hold knob is on screen in the same
// frame, and two knobs labelled the same are two knobs the user has to guess between.
const std::string label = dragging || hov
? instrument::note::divisionLabel(params_.bakeHold)
: std::string("Hold");
: std::string("Bake Hold");
kitTextCentered(bmp, cr.holdLabel, label.c_str(), Font::Micro, Role::TextDim);
}
+5 -3
View File
@@ -24,9 +24,11 @@ constexpr const wchar_t* kChildClassName = L"ReaSampler9000VstEditor";
// The change-detection poll (WM_TIMER on the child window). A low-frequency UI-thread
// timer: responsive enough that a recapture/ingest/assign refreshes within a bounded
// cadence, yet cheap — three small ext-state reads per tick, coalescing many bumps
// between ticks into one reload. 500 ms is a deliberate build-time residual. The id is a
// per-window SetTimer id (any nonzero).
// cadence, yet cheap — three small ext-state reads per tick in the steady state, coalescing
// many bumps between ticks into one reload. Anything costlier a tick answers (the bake-Hold
// predicate's bank parse) is memoized against its inputs, so keep it that way rather than
// letting a per-tick full read back in. 500 ms is a deliberate build-time residual. The id is
// a per-window SetTimer id (any nonzero).
constexpr UINT_PTR kSyncTimerId = 1;
constexpr UINT kSyncTimerIntervalMs = 500;
} // namespace
+33 -5
View File
@@ -57,6 +57,7 @@ void ReaSamplerEditor::refreshFromBank() {
// Main/UI thread only — reads the live bank over the bridge (allocates, calls REAPER).
thumbCache_.clear(); // a bank edit may have re-captured/removed a sample; drop stale peaks
pcmCache_.clear(); // and its decoded PCM (the waveform + snap source)
holdNeedValid_ = false; // …and the bake-Hold answer derived from the bank's loop intrinsic
channelPcmId_.clear();
channelPcm_ = ChannelPcm{};
if (!processor_) {
@@ -262,16 +263,43 @@ ReaSamplerEditor::SetupMarkers ReaSamplerEditor::pickedMarkers(std::int64_t fram
return m;
}
bool ReaSamplerEditor::HoldNeedKey::operator==(const HoldNeedKey& o) const {
if (sampleId != o.sampleId || crossfade != o.crossfade) return false;
if (loopOverride.has_value() != o.loopOverride.has_value()) return false;
if (!loopOverride) return true;
return loopOverride->hasLoop == o.loopOverride->hasLoop &&
loopOverride->start == o.loopOverride->start &&
loopOverride->end == o.loopOverride->end;
}
bool ReaSamplerEditor::resolveBakeHoldNeeded() {
// The mode test comes first so the common Trigger case never pays pickedMarkers' bridge
// read. `m.hasLoop` alone is not the answer — the engine's fold also refuses a span that
// reaches outside the PCM, which is exactly what the pure predicate is asked for.
if (selectedId_.empty() || params_.play.playMode != PlayMode::Gate) return false;
// effectivePlayMode, not the raw field: the bake reads the mode AFTER the drawn-EG fold
// (resolvePlay, via bakeSnapshot), so a restored or foreign blob carrying Gate together
// with an active spline would otherwise paint a control for a sound that bakes as Trigger.
// The mode test comes first so the common Trigger case never pays the resolve below.
const PlayMode mode = effectivePlayMode(params_.play);
if (selectedId_.empty() || mode != PlayMode::Gate) return false;
// Everything past here costs a WAV decode and — with no loop override set — a bridge read
// plus a bank parse, and the sync tick asks twice a second for as long as an editor is
// open. Answer once per distinct input; refreshFromBank drops the memo along with the rest
// of the bank-derived caches, which is the same edge a bank generation bump would give.
// The mode is not part of the key: the resolve below always asks about Gate, and the test
// above is what keeps a Trigger sound from reaching it.
const HoldNeedKey key{selectedId_, params_.loopOverride, params_.loopCrossfadeFrames};
if (holdNeedValid_ && key == holdNeedKey_) return holdNeedAnswer_;
holdNeedValid_ = true;
holdNeedKey_ = key;
holdNeedAnswer_ = false;
const auto frames = static_cast<std::int64_t>(monoPcmFor(selectedId_).size());
if (frames <= 0) return false;
// `m.hasLoop` alone is not the answer — the engine's fold also refuses a span that reaches
// outside the PCM, which is exactly what the pure predicate is asked for.
const SetupMarkers m = pickedMarkers(frames);
return instrument::bake::bakeWindowNeedsHold(
holdNeedAnswer_ = instrument::bake::bakeWindowNeedsHold(
PlayMode::Gate, SampleLoop{m.hasLoop, m.loopStart, m.loopEnd}, m.crossfade, frames);
return holdNeedAnswer_;
}
void ReaSamplerEditor::applyMarkers(const SetupMarkers& m) {
+1 -2
View File
@@ -132,8 +132,7 @@ BakeChainResult runBake(ReaSamplerProcessor& processor) {
// are live, so a sound dialed at 127 does not bake as one dialed at 40.
const Velocity velocity = Velocity::of(processor.previewVelocity());
const instrument::bake::PlannedBake planned = planBake(
resolveNote(defaultBakeProgram(*snapshot, sampleRate, *tempo, dialed.bakeHold,
velocity),
resolveNote(defaultBakeProgram(*snapshot, sampleRate, dialed.bakeHold, velocity),
*tempo),
sampleRate, rootNote);
if (!planned.plan) {
+14 -1
View File
@@ -342,9 +342,22 @@ private:
// Whether the loaded sound's bake window needs the user's Hold — the pure predicate
// (bake_plan.h) answered against the markers this face is showing. Decodes and reads the
// bank, so it is called on the sync tick, not per paint.
// bank, so it is called on the sync tick, not per paint, and memoized against the inputs
// below on top of that.
bool resolveBakeHoldNeeded();
// What that answer was last computed against. Invalidated wholesale by refreshFromBank,
// which is where the bank half of the input changes.
struct HoldNeedKey {
std::string sampleId;
std::optional<SampleLoop> loopOverride;
std::int64_t crossfade = 0;
bool operator==(const HoldNeedKey& other) const;
};
HoldNeedKey holdNeedKey_;
bool holdNeedValid_ = false;
bool holdNeedAnswer_ = false;
// Writes `m` into params_ as the loop/start override. Does NOT call commitAndReload —
// callers decide live-drag vs final commit.
void applyMarkers(const SetupMarkers& m);