instrument: spline EGs — hard points on the one shared spline, a drawn contour per envelope beside its staged state, payload v13
This commit is contained in:
@@ -65,6 +65,20 @@ struct AhdParams {
|
||||
double decayCurve = util::kCurveNeutral;
|
||||
};
|
||||
|
||||
// Which shape an envelope takes: the STAGED knobs, or a free-drawn SPLINE contour. Both states
|
||||
// are stored side by side and neither converts into the other, so a mode flip is reversible and
|
||||
// lossless — the inactive one is saved but inert, edited only by switching back to it.
|
||||
enum class EnvMode { Staged, Spline };
|
||||
|
||||
// The free-drawn alternative to a staged envelope: a contour over NORMALIZED sample time,
|
||||
// covering the full sample length. Normalized is what makes it length-independent — a
|
||||
// different-length capture replays the same shape proportionally, with no stored seconds to
|
||||
// rescale. The default is the smooth y = 1 - x downward slope.
|
||||
struct SplineEnv {
|
||||
EnvMode mode = EnvMode::Staged;
|
||||
VelocityCurve contour = VelocityCurve::rampDown();
|
||||
};
|
||||
|
||||
// GATE = classic held note (AHDSR + sustain loop + note-off release). TRIGGER = one-shot:
|
||||
// note-off-immune, no sustain loop, plays a % of sample length shaped by the AHD. Both honor
|
||||
// the start point. Default Gate so an instrument with no params set plays as before.
|
||||
@@ -150,8 +164,31 @@ struct PlayParams {
|
||||
// baseRatio_ at note-on — it is fixed for the note's lifetime, so it costs no per-frame work.
|
||||
VelocityCurve pitchVelocityCurve = VelocityCurve::zero();
|
||||
FilterParams filter;
|
||||
// The three drawn contours: the alternative to adsr/trigAhd, to pitchEnv.shape, and to
|
||||
// filter.env/trigEnv respectively. They sit HERE rather than inside the three envelope
|
||||
// structs because those are copied whole into the live block, which must stay trivially
|
||||
// copyable (live_params.h) — and a contour is not a live control anyway: like the velocity
|
||||
// curves it travels by reload.
|
||||
SplineEnv ampSpline;
|
||||
SplineEnv pitchSpline;
|
||||
SplineEnv filterSpline;
|
||||
};
|
||||
|
||||
// Whether ANY of the three envelopes is drawn rather than staged. Templated over the two
|
||||
// parameter representations (frames and the editor's seconds mirror) because both spell the
|
||||
// three fields identically and the rule must not be written twice — compile-time dispatch,
|
||||
// no runtime cost, off every hot path.
|
||||
//
|
||||
// THE consequence, and its one home: a spline contour is a pure time function over the full
|
||||
// sample length, which IS the Trigger/one-shot playback model — so Gate is not available while
|
||||
// any spline EG is active. resolvePlay enforces it on the way to the engine; the editor's
|
||||
// play-mode toggle refuses the Gate segment so the two agree.
|
||||
template <class Play>
|
||||
bool splineActive(const Play& p) {
|
||||
return p.ampSpline.mode == EnvMode::Spline || p.pitchSpline.mode == EnvMode::Spline ||
|
||||
p.filterSpline.mode == EnvMode::Spline;
|
||||
}
|
||||
|
||||
// [start, end) frames, half-open. A zero-length loop (start == end) is the "no sustain loop"
|
||||
// marker — a held note past the sample end goes silent rather than looping a zero span.
|
||||
struct SampleLoop {
|
||||
|
||||
@@ -62,9 +62,18 @@ VelocityCurve VelocityCurve::zero() {
|
||||
return c;
|
||||
}
|
||||
|
||||
VelocityCurve VelocityCurve::rampDown() {
|
||||
VelocityCurve c;
|
||||
c.points_ = {{kVelMin, kCurveYMax, false}, {kVelMax, 0.0, false}};
|
||||
return c;
|
||||
}
|
||||
|
||||
VelocityCurve VelocityCurve::fromPoints(std::vector<VelocityPoint> pts, CurveDomain domain) {
|
||||
// Stable sort so coincident-X points keep their wire order (eval stays well-defined for
|
||||
// duplicate-X knots).
|
||||
// Trim before the endpoint synthesis below can add up to two more, then again after, so a
|
||||
// corrupt over-long blob lands at exactly the ceiling with its two endpoints intact.
|
||||
if (pts.size() > kMaxCurvePoints) pts.resize(kMaxCurvePoints);
|
||||
for (VelocityPoint& p : pts) {
|
||||
p.velocity = clampVelocity(p.velocity);
|
||||
p.value = clampValue(p.value, domain);
|
||||
@@ -77,42 +86,34 @@ VelocityCurve VelocityCurve::fromPoints(std::vector<VelocityPoint> pts, CurveDom
|
||||
return domain == CurveDomain::Bipolar ? zero() : flat();
|
||||
}
|
||||
if (pts.front().velocity > kVelMin) {
|
||||
pts.insert(pts.begin(), VelocityPoint{kVelMin, pts.front().value});
|
||||
pts.insert(pts.begin(), VelocityPoint{kVelMin, pts.front().value, pts.front().hard});
|
||||
} else {
|
||||
pts.front().velocity = kVelMin;
|
||||
}
|
||||
if (pts.back().velocity < kVelMax) {
|
||||
pts.push_back(VelocityPoint{kVelMax, pts.back().value});
|
||||
pts.push_back(VelocityPoint{kVelMax, pts.back().value, pts.back().hard});
|
||||
} else {
|
||||
pts.back().velocity = kVelMax;
|
||||
}
|
||||
if (pts.size() > kMaxCurvePoints) {
|
||||
// Drop the interior points nearest the end, never an endpoint.
|
||||
pts.erase(pts.begin() + static_cast<std::ptrdiff_t>(kMaxCurvePoints) - 1,
|
||||
pts.end() - 1);
|
||||
}
|
||||
VelocityCurve c;
|
||||
c.domain_ = domain;
|
||||
c.points_ = std::move(pts);
|
||||
return c;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// Fritsch-Carlson monotone-cubic tangent: a sign change (or flat) neighbour is a local extremum,
|
||||
// so the tangent pins to 0 to avoid overshoot; otherwise the weighted-harmonic-mean tangent,
|
||||
// which for collinear knots (dPrev==dNext) reduces exactly to the shared secant — this is what
|
||||
// makes the spline reproduce a straight line for linear()-style input.
|
||||
double fritschCarlsonTangent(double dPrev, double dNext, double spanPrev, double spanNext) {
|
||||
if (dPrev * dNext <= 0.0) return 0.0;
|
||||
const double w1 = 2.0 * spanNext + spanPrev;
|
||||
const double w2 = spanNext + 2.0 * spanPrev;
|
||||
return (w1 + w2) / (w1 / dPrev + w2 / dNext);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
double VelocityCurve::eval(double velocity) const {
|
||||
if (points_.empty()) return curveNeutral(domain_);
|
||||
if (points_.size() == 1) return clampValue(points_[0].value, domain_);
|
||||
const double v = clampVelocity(velocity);
|
||||
if (v <= points_.front().velocity) return clampValue(points_.front().value, domain_);
|
||||
if (v >= points_.back().velocity) return clampValue(points_.back().value, domain_);
|
||||
// Linear walk: this overload is the COLD one (a note-on, a paint column). The per-sample
|
||||
// reader is SplineCursor, which shares the same tangent + Hermite functions.
|
||||
for (std::size_t i = 0; i + 1 < points_.size(); ++i) {
|
||||
const VelocityPoint& a = points_[i];
|
||||
const VelocityPoint& b = points_[i + 1];
|
||||
@@ -120,55 +121,38 @@ double VelocityCurve::eval(double velocity) const {
|
||||
const double span = b.velocity - a.velocity;
|
||||
// Coincident-X neighbours (a step): zero-width segment, no interior to blend.
|
||||
if (span <= 0.0) return clampValue(b.value, domain_);
|
||||
|
||||
// Monotone cubic Hermite (Fritsch-Carlson): provably stays within [a.value, b.value]
|
||||
// between the two knots (no overshoot), reproducing a straight line for collinear input.
|
||||
const double d = (b.value - a.value) / span;
|
||||
|
||||
double mA = d;
|
||||
if (i > 0) {
|
||||
const VelocityPoint& prev = points_[i - 1];
|
||||
const double spanPrev = a.velocity - prev.velocity;
|
||||
if (spanPrev > 0.0) {
|
||||
const double dPrev = (a.value - prev.value) / spanPrev;
|
||||
mA = fritschCarlsonTangent(dPrev, d, spanPrev, span);
|
||||
} else {
|
||||
mA = 0.0;
|
||||
}
|
||||
}
|
||||
double mB = d;
|
||||
if (i + 2 < points_.size()) {
|
||||
const VelocityPoint& next = points_[i + 2];
|
||||
const double spanNext = next.velocity - b.velocity;
|
||||
if (spanNext > 0.0) {
|
||||
const double dNext = (next.value - b.value) / spanNext;
|
||||
mB = fritschCarlsonTangent(d, dNext, span, spanNext);
|
||||
} else {
|
||||
mB = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
const double t = (v - a.velocity) / span;
|
||||
const double t2 = t * t;
|
||||
const double t3 = t2 * t;
|
||||
const double h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
|
||||
const double h10 = t3 - 2.0 * t2 + t;
|
||||
const double h01 = -2.0 * t3 + 3.0 * t2;
|
||||
const double h11 = t3 - t2;
|
||||
const double y = h00 * a.value + h10 * span * mA + h01 * b.value + h11 * span * mB;
|
||||
const SegmentTangents m = segmentTangents(points_.data(), points_.size(), i, d, span);
|
||||
const double y = hermiteAt(a.value, b.value, span, m.mA, m.mB,
|
||||
(v - a.velocity) / span);
|
||||
return clampValue(y, domain_);
|
||||
}
|
||||
}
|
||||
return clampValue(points_.back().value, domain_); // unreachable (v is between the endpoints)
|
||||
}
|
||||
|
||||
std::size_t VelocityCurve::addPoint(double velocity, double value) {
|
||||
const VelocityPoint p{clampVelocity(velocity), clampValue(value, domain_)};
|
||||
int VelocityCurve::addPoint(double velocity, double value) {
|
||||
// At the ceiling the add is REFUSED outright rather than trading a point away — the existing
|
||||
// contour must come through an over-add bit-identical.
|
||||
if (points_.size() >= kMaxCurvePoints) return -1;
|
||||
const VelocityPoint p{clampVelocity(velocity), clampValue(value, domain_), false};
|
||||
// First index strictly greater, so a duplicate-X point lands immediately after the existing one.
|
||||
std::size_t i = 0;
|
||||
while (i < points_.size() && points_[i].velocity <= p.velocity) ++i;
|
||||
points_.insert(points_.begin() + static_cast<std::ptrdiff_t>(i), p);
|
||||
return i;
|
||||
return static_cast<int>(i);
|
||||
}
|
||||
|
||||
bool VelocityCurve::toggleHard(std::size_t index) {
|
||||
if (index >= points_.size()) return false;
|
||||
points_[index].hard = !points_[index].hard;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool VelocityCurve::setHard(std::size_t index, bool hard) {
|
||||
if (index >= points_.size()) return false;
|
||||
points_[index].hard = hard;
|
||||
return true;
|
||||
}
|
||||
|
||||
VelocityPoint VelocityCurve::movePoint(std::size_t index, double velocity, double value) {
|
||||
@@ -187,7 +171,7 @@ VelocityPoint VelocityCurve::movePoint(std::size_t index, double velocity, doubl
|
||||
const double hi = points_[index + 1].velocity;
|
||||
newVel = std::clamp(clampVelocity(velocity), lo, hi);
|
||||
}
|
||||
points_[index] = VelocityPoint{newVel, newValue};
|
||||
points_[index] = VelocityPoint{newVel, newValue, points_[index].hard};
|
||||
return points_[index];
|
||||
}
|
||||
|
||||
@@ -255,6 +239,7 @@ bool VelocityCurve::equals(const VelocityCurve& other, double eps) const {
|
||||
for (std::size_t i = 0; i < points_.size(); ++i) {
|
||||
if (std::fabs(points_[i].velocity - other.points_[i].velocity) > eps) return false;
|
||||
if (std::fabs(points_[i].value - other.points_[i].value) > eps) return false;
|
||||
if (points_[i].hard != other.points_[i].hard) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,21 +1,32 @@
|
||||
// velocity_curve.h — the velocity->modulation transfer curve, shared by all three
|
||||
// destinations (amp gain, pitch offset, filter cutoff offset). eval(velocity) is called once
|
||||
// per note-on in Voice::start(), never per frame. Editor hit-test/inverse-map take an explicit
|
||||
// pixel Box rather than a Rect: this module sits below sampler_core in the link graph and must
|
||||
// not gain a transitive dependency on editor-layout types.
|
||||
// velocity_curve.h — THE monotone spline, shared by every consumer: the three velocity
|
||||
// transfer curves (amp gain, pitch offset, filter cutoff offset), evaluated once per note-on,
|
||||
// and the spline EGs, evaluated per voice per sample through SplineCursor. Editor
|
||||
// hit-test/inverse-map take an explicit pixel Box rather than a Rect: this module sits below
|
||||
// sampler_core in the link graph and must not gain a dependency on editor-layout types.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace reasampler::instrument::engine {
|
||||
|
||||
// The MIDI velocity domain [0,127] — the X span every point clamps into.
|
||||
inline constexpr double kVelMin = 0.0;
|
||||
inline constexpr double kVelMax = 127.0;
|
||||
// The curve's canonical X span. For the three velocity consumers it IS the MIDI velocity
|
||||
// domain; a spline EG maps normalized sample time onto the same span, which is what lets one
|
||||
// implementation serve both without a second X domain to keep in sync.
|
||||
inline constexpr double kCurveXMin = 0.0;
|
||||
inline constexpr double kCurveXMax = 127.0;
|
||||
inline constexpr double kVelMin = kCurveXMin; // the velocity consumers' spelling of the span
|
||||
inline constexpr double kVelMax = kCurveXMax;
|
||||
inline constexpr double kCurveYMax = 1.0;
|
||||
|
||||
// Point-count ceiling. A MUSICAL bound, not a performance one: long rhythmic phrases need the
|
||||
// resolution, and at roughly two points per articulation event 128 is about four bars of 16ths.
|
||||
// Segment lookup is logarithmic and the editor's node separation is the real density limit, so
|
||||
// there is nothing to buy by lowering it. DO NOT LOWER.
|
||||
inline constexpr std::size_t kMaxCurvePoints = 128;
|
||||
|
||||
// The curve's Y range. UNIPOLAR [0,1] is a GAIN — the amp's domain, where the do-nothing
|
||||
// curve is flat at 1. BIPOLAR [-1,1] is a SIGNED modulation shape — the pitch and filter
|
||||
// domains, where the do-nothing curve is flat at 0 and the sign picks the direction. A
|
||||
@@ -34,19 +45,75 @@ constexpr double curveNeutral(CurveDomain d) { return d == CurveDomain::Bipolar
|
||||
// A raw-constructed point is NOT auto-clamped (the mutators own that invariant) — build curves
|
||||
// through the named constructors / addPoint rather than pushing raw points.
|
||||
struct VelocityPoint {
|
||||
double velocity = 0.0; // X, [0,127]
|
||||
double velocity = 0.0; // X, over the canonical span
|
||||
double value = 0.0; // Y, in the owning curve's domain
|
||||
// A HARD point does no smoothing on either side: it terminates the monotone sub-curve, so
|
||||
// the two adjacent segments meet at their own natural angle instead of a shared derivative.
|
||||
// Points are smooth by default; see segmentTangents for the mechanism.
|
||||
bool hard = false;
|
||||
};
|
||||
|
||||
// Fritsch-Carlson monotone-cubic tangent: a sign change (or flat) neighbour is a local extremum,
|
||||
// so the tangent pins to 0 to avoid overshoot; otherwise the weighted-harmonic-mean tangent,
|
||||
// which for collinear knots (dPrev==dNext) reduces exactly to the shared secant — this is what
|
||||
// makes the spline reproduce a straight line for linear()-style input.
|
||||
inline double fritschCarlsonTangent(double dPrev, double dNext, double spanPrev, double spanNext) {
|
||||
if (dPrev * dNext <= 0.0) return 0.0;
|
||||
const double w1 = 2.0 * spanNext + spanPrev;
|
||||
const double w2 = spanNext + 2.0 * spanPrev;
|
||||
return (w1 + w2) / (w1 / dPrev + w2 / dNext);
|
||||
}
|
||||
|
||||
struct SegmentTangents {
|
||||
double mA = 0.0;
|
||||
double mB = 0.0;
|
||||
};
|
||||
|
||||
// The Hermite tangents for segment [i, i+1] of an X-ordered point array, where `d` is that
|
||||
// segment's secant slope and `span` its X width (> 0).
|
||||
//
|
||||
// A HARD point is treated exactly as the array's own end is: the tangent there is the segment's
|
||||
// own secant, so smoothing stops at it. That single rule is the whole hard-point enhancement —
|
||||
// the contour becomes one or more monotone splines joined at their natural angles, and each
|
||||
// sub-curve keeps Fritsch-Carlson's no-overshoot guarantee because m == d satisfies its bound.
|
||||
inline SegmentTangents segmentTangents(const VelocityPoint* p, std::size_t n, std::size_t i,
|
||||
double d, double span) {
|
||||
SegmentTangents t{d, d};
|
||||
if (i > 0 && !p[i].hard) {
|
||||
const double spanPrev = p[i].velocity - p[i - 1].velocity;
|
||||
t.mA = (spanPrev > 0.0)
|
||||
? fritschCarlsonTangent((p[i].value - p[i - 1].value) / spanPrev, d, spanPrev,
|
||||
span)
|
||||
: 0.0;
|
||||
}
|
||||
if (i + 2 < n && !p[i + 1].hard) {
|
||||
const double spanNext = p[i + 2].velocity - p[i + 1].velocity;
|
||||
t.mB = (spanNext > 0.0)
|
||||
? fritschCarlsonTangent(d, (p[i + 2].value - p[i + 1].value) / spanNext, span,
|
||||
spanNext)
|
||||
: 0.0;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
// The cubic Hermite basis evaluated at t in [0,1] across a segment of width `span`.
|
||||
inline double hermiteAt(double y0, double y1, double span, double mA, double mB, double t) {
|
||||
const double t2 = t * t;
|
||||
const double t3 = t2 * t;
|
||||
return (2.0 * t3 - 3.0 * t2 + 1.0) * y0 + (t3 - 2.0 * t2 + t) * span * mA +
|
||||
(-2.0 * t3 + 3.0 * t2) * y1 + (t3 - t2) * span * mB;
|
||||
}
|
||||
|
||||
// Pick radius (px) around a node's drawn point for the editor hit-test.
|
||||
inline constexpr int kCurveNodeGrabRadius = 6;
|
||||
|
||||
// An X-ordered list of control points spanning [0,127], evaluated by a monotone cubic Hermite
|
||||
// spline (Fritsch-Carlson slope limiting) — a genuine curve, not a polyline, that provably never
|
||||
// overshoots a segment's value range. For collinear knots the tangents reduce to the secant
|
||||
// slope, so the spline reproduces linear()'s straight line to within ~1e-15. The two endpoints
|
||||
// (velocity 0 and 127) are load-bearing: they keep eval total over the domain and are never
|
||||
// deletable.
|
||||
// An X-ordered list of control points spanning the canonical X span, evaluated as ONE OR MORE
|
||||
// monotone cubic Hermite splines (Fritsch-Carlson slope limiting) joined at the hard points — a
|
||||
// genuine curve, not a polyline, that provably never overshoots any segment's value range. The
|
||||
// guarantee is PER SEGMENT, so a contour is free to rise and fall. For collinear knots the
|
||||
// tangents reduce to the secant slope, so the spline reproduces linear()'s straight line to
|
||||
// within ~1e-15. The two endpoints are load-bearing: they keep eval total over the domain and
|
||||
// are never deletable.
|
||||
class VelocityCurve {
|
||||
public:
|
||||
// flat() (endpoints (0,1)/(127,1), every velocity -> unity) is the unipolar default — see
|
||||
@@ -56,6 +123,10 @@ public:
|
||||
static VelocityCurve linear();
|
||||
// The bipolar default: flat at 0, so velocity modulates nothing until a curve is drawn.
|
||||
static VelocityCurve zero();
|
||||
// y = 1 - x: the smooth downward slope a freshly created spline EG opens on. Two collinear
|
||||
// knots, so it is straight — and straight is smooth. NOT a change to any velocity curve's
|
||||
// own default.
|
||||
static VelocityCurve rampDown();
|
||||
|
||||
// Rebuilds from a deserialized point list, repairing the invariant defensively: box-clamps
|
||||
// each point into `domain`, stable-sorts by velocity, forces both endpoints present
|
||||
@@ -73,8 +144,15 @@ public:
|
||||
double eval(double velocity) const;
|
||||
|
||||
// Inserted at a velocity duplicating an existing point lands immediately after it, so a
|
||||
// subsequent move can separate them. Returns the inserted index.
|
||||
std::size_t addPoint(double velocity, double value);
|
||||
// subsequent move can separate them. Returns the inserted index, or -1 when the curve is
|
||||
// already at kMaxCurvePoints — a refusal leaves the contour bit-identical.
|
||||
int addPoint(double velocity, double value);
|
||||
|
||||
// Flips a point between hard and smooth. Out-of-range index is a no-op returning false.
|
||||
// Permitted on the endpoints, where it changes nothing evaluable: an endpoint's outward
|
||||
// tangent is already its own secant, which is what hard means.
|
||||
bool toggleHard(std::size_t index);
|
||||
bool setHard(std::size_t index, bool hard);
|
||||
|
||||
// Box-clamped and X-clamped between immediate neighbours (monotonic-X grammar). The two
|
||||
// endpoints are pinned in X (only their value moves); out-of-range index is a no-op.
|
||||
@@ -130,4 +208,71 @@ private:
|
||||
CurveDomain domain_ = CurveDomain::Unipolar;
|
||||
};
|
||||
|
||||
// The RT read head over a contour: an indexed segment search plus one Hermite evaluation, with
|
||||
// the segment and its two tangents cached across samples so a monotone read costs one compare.
|
||||
// Header-inline, branch-only, NO allocation and NO virtual dispatch — it runs per voice per
|
||||
// sample. A jump (a loop wrap, a fresh note) falls back to a binary search, <= 7 steps at the
|
||||
// 128-point ceiling.
|
||||
//
|
||||
// Holds a RAW POINTER into the bound curve's point array: the caller guarantees the curve
|
||||
// outlives the cursor. The voice binds against its SampleData, which has exactly that lifetime.
|
||||
class SplineCursor {
|
||||
public:
|
||||
// Binds `c` if it has an evaluable segment; a shorter curve leaves the cursor inactive so
|
||||
// the caller's `if (active())` skips the whole spline path.
|
||||
void bind(const VelocityCurve& c) {
|
||||
const std::vector<VelocityPoint>& pts = c.points();
|
||||
if (pts.size() < 2) { clear(); return; }
|
||||
pts_ = pts.data();
|
||||
n_ = pts.size();
|
||||
select(0);
|
||||
}
|
||||
void clear() { pts_ = nullptr; n_ = 0; }
|
||||
bool active() const { return n_ >= 2; }
|
||||
|
||||
// `phase` is normalized position over the contour's whole span, [0,1]; out-of-range clamps
|
||||
// to the terminal values (a note past its span holds the contour's last level).
|
||||
double eval(double phase) {
|
||||
const double x = (phase <= 0.0) ? kCurveXMin
|
||||
: (phase >= 1.0) ? kCurveXMax
|
||||
: kCurveXMin + phase * (kCurveXMax - kCurveXMin);
|
||||
if (x <= x0_ && seg_ == 0) return y0_;
|
||||
if (x >= x1_ && seg_ + 2 == n_) return y1_;
|
||||
if (x < x0_ || x > x1_) locate(x);
|
||||
if (span_ <= 0.0) return y1_; // coincident-X knots: a step, no interior to blend
|
||||
return hermiteAt(y0_, y1_, span_, mA_, mB_, (x - x0_) / span_);
|
||||
}
|
||||
|
||||
private:
|
||||
// The common case is the next segment (a monotone read walking forward); anything else is a
|
||||
// binary search over the X-ordered array.
|
||||
void locate(double x) {
|
||||
if (x > x1_ && seg_ + 2 < n_ && x <= pts_[seg_ + 2].velocity) { select(seg_ + 1); return; }
|
||||
std::size_t lo = 0, hi = n_ - 2;
|
||||
while (lo < hi) {
|
||||
const std::size_t mid = lo + (hi - lo + 1) / 2;
|
||||
if (pts_[mid].velocity <= x) lo = mid; else hi = mid - 1;
|
||||
}
|
||||
select(lo);
|
||||
}
|
||||
|
||||
void select(std::size_t i) {
|
||||
seg_ = i;
|
||||
x0_ = pts_[i].velocity;
|
||||
x1_ = pts_[i + 1].velocity;
|
||||
y0_ = pts_[i].value;
|
||||
y1_ = pts_[i + 1].value;
|
||||
span_ = x1_ - x0_;
|
||||
const SegmentTangents t =
|
||||
segmentTangents(pts_, n_, i, span_ > 0.0 ? (y1_ - y0_) / span_ : 0.0, span_);
|
||||
mA_ = t.mA;
|
||||
mB_ = t.mB;
|
||||
}
|
||||
|
||||
const VelocityPoint* pts_ = nullptr;
|
||||
std::size_t n_ = 0;
|
||||
std::size_t seg_ = 0;
|
||||
double x0_ = 0.0, x1_ = 0.0, y0_ = 0.0, y1_ = 0.0, span_ = 0.0, mA_ = 0.0, mB_ = 0.0;
|
||||
};
|
||||
|
||||
} // namespace reasampler::instrument::engine
|
||||
|
||||
@@ -72,6 +72,26 @@ void Voice::start(int note, int velocity, const SampleData& sample, bool declick
|
||||
loop_ = instrument::engine::loop::resolveLoop(sample.loop, sample.loopCrossfadeFrames,
|
||||
frameCount, playMode_ == PlayMode::Gate);
|
||||
|
||||
// Bind whichever EGs are drawn. Rebound on EVERY note-on rather than cached: a reload hands
|
||||
// the engine a fresh SampleData, so a stale pointer into the previous one is the bug this
|
||||
// avoids. A Staged EG clears its cursor, which is what keeps the per-sample path off the
|
||||
// spline branch entirely.
|
||||
splineScale_ = frameCount > 0 ? 1.0 / static_cast<double>(frameCount) : 0.0;
|
||||
if (p.ampSpline.mode == EnvMode::Spline) ampSplineCur_.bind(p.ampSpline.contour);
|
||||
else ampSplineCur_.clear();
|
||||
if (p.pitchEnv.enabled && p.pitchSpline.mode == EnvMode::Spline) {
|
||||
pitchSplineCur_.bind(p.pitchSpline.contour);
|
||||
pitchSplineDepth_ = p.pitchEnv.peakSemitones;
|
||||
} else {
|
||||
pitchSplineCur_.clear();
|
||||
pitchSplineDepth_ = 0.0;
|
||||
}
|
||||
if (p.filter.enabled && p.filterSpline.mode == EnvMode::Spline) {
|
||||
filterSplineCur_.bind(p.filterSpline.contour);
|
||||
} else {
|
||||
filterSplineCur_.clear();
|
||||
}
|
||||
|
||||
// Amplitude envelope: Gate = AHDSR (all five fields read from play.adsr, resolved to
|
||||
// frames from stored seconds at load time); Trigger = the staged AHD over the % play span.
|
||||
const std::int64_t postStart = frameCount - start; // >= 1 (start clamped < frameCount)
|
||||
|
||||
@@ -25,6 +25,7 @@ namespace reasampler {
|
||||
|
||||
using audio::AudioSample;
|
||||
using instrument::engine::PitchShifter;
|
||||
using instrument::engine::SplineCursor;
|
||||
using instrument::engine::VelocityCurve;
|
||||
using instrument::engine::VelocityPoint;
|
||||
using instrument::engine::loop::ResolvedLoop;
|
||||
@@ -164,14 +165,24 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
// This frame's amplitude in [0,1] from the active envelope. Gate: AHDSR ticks once per
|
||||
// output frame (envelope time is wall-clock, independent of read rate). Trigger: the AHD
|
||||
// The read head as a fraction of the whole sample — the domain every spline EG is a pure
|
||||
// function of. Zero-length sample leaves splineScale_ at 0, which parks every contour on
|
||||
// its opening value.
|
||||
double splinePhase() const { return readPos_ * splineScale_; }
|
||||
|
||||
// This frame's amplitude in [0,1] from the active envelope. Spline: the drawn contour read
|
||||
// at the normalized position (one cached-segment compare per frame). Gate: AHDSR ticks once
|
||||
// per output frame (envelope time is wall-clock, independent of read rate). Trigger: the AHD
|
||||
// is evaluated at the source offset (readPos - startFrame) so its stages anchor to source
|
||||
// frames regardless of pitch engine. Sets amplitudeDone_ on finish so advanceFrame frees
|
||||
// the voice.
|
||||
double tickAmplitude() {
|
||||
double amp;
|
||||
if (playMode_ == PlayMode::Gate) {
|
||||
if (ampSplineCur_.active()) {
|
||||
// A contour covers the sample end to end, so the head leaving the span IS the end of
|
||||
// the note — the exhaustion path in advanceFrame is what frees the voice.
|
||||
amp = ampSplineCur_.eval(splinePhase());
|
||||
} else if (playMode_ == PlayMode::Gate) {
|
||||
amp = env_.tick();
|
||||
if (env_.finished()) amplitudeDone_ = true;
|
||||
} else {
|
||||
@@ -202,9 +213,11 @@ private:
|
||||
// The filter envelope takes the amp's shape under the active mode — AHDSR in Gate,
|
||||
// the source-offset AHD in Trigger. playMode_ is fixed for the note's lifetime, so the
|
||||
// branch is perfectly predicted.
|
||||
const double envOut = (playMode_ == PlayMode::Gate)
|
||||
? filterEnv_.tick()
|
||||
: filterAhd_.amplitudeAt(sourceOffset());
|
||||
const double envOut = filterSplineCur_.active()
|
||||
? filterSplineCur_.eval(splinePhase())
|
||||
: ((playMode_ == PlayMode::Gate)
|
||||
? filterEnv_.tick()
|
||||
: filterAhd_.amplitudeAt(sourceOffset()));
|
||||
double cut = static_cast<double>(filterBaseCutoff_) + filterModAmount_ * envOut;
|
||||
if (cut < 0.0) cut = 0.0;
|
||||
if (cut > 1.0) cut = 1.0;
|
||||
@@ -394,7 +407,9 @@ private:
|
||||
seedTerminalDeclick();
|
||||
}
|
||||
const double gain = amp * velocityGain_;
|
||||
const double pitchEnvSemis = pitchEnv_.tick();
|
||||
const double pitchEnvSemis = pitchSplineCur_.active()
|
||||
? pitchSplineDepth_ * pitchSplineCur_.eval(splinePhase())
|
||||
: pitchEnv_.tick();
|
||||
|
||||
// 2^(semis/12); when the envelope is off (semis exactly 0) this is 1.0 and skips the
|
||||
// pow entirely — no per-frame transcendental on the common path.
|
||||
@@ -585,6 +600,17 @@ private:
|
||||
std::int64_t playEnd_ = 0; // Trigger: source-frame end; Gate: unused
|
||||
bool amplitudeDone_ = false; // set when the active amplitude envelope finished
|
||||
|
||||
// The three drawn contours, bound at note-on to the loaded capture's own point arrays (the
|
||||
// SampleData outlives the voice — same contract as sample_). A Staged EG leaves its cursor
|
||||
// inactive, so a purely staged instrument's per-sample path gains three predicted branches
|
||||
// and nothing else. splineScale_ is 1/frameCount, the readPos -> [0,1] map every contour
|
||||
// shares; pitchSplineDepth_ is the pitch envelope's peak, zero while it is disabled.
|
||||
SplineCursor ampSplineCur_;
|
||||
SplineCursor pitchSplineCur_;
|
||||
SplineCursor filterSplineCur_;
|
||||
double splineScale_ = 0.0;
|
||||
double pitchSplineDepth_ = 0.0;
|
||||
|
||||
// The sustain loop folded ONCE at note-on: the sample, the play mode and the stored span
|
||||
// are all fixed for the note's lifetime, so re-deriving validity per frame bought nothing.
|
||||
// Shared by the output anchor, the Preserve feed, and the start()-time ring prime.
|
||||
|
||||
Reference in New Issue
Block a user