DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
SmoothedValue.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
18#include "DspMath.h"
19
20#include <cmath>
21#include <algorithm>
22#include <span>
23
24namespace dspark {
25
70template <FloatType T>
72{
73public:
74 enum class SmoothingType
75 {
77 Linear,
78 Disabled,
79 Chase
80 };
81
83 SmoothedValue(const SmoothedValue&) = delete;
85
86 SmoothedValue() noexcept { prepare(sampleRate_, rampTimeMs_); }
87
96 void prepare(double sampleRate, double rampTimeMs = 20.0) noexcept
97 {
98 sampleRate_ = std::max(1.0, sampleRate);
99 // (a NaN ramp time also lands on 0: std::max returns its first argument.)
100 rampTimeMs_ = std::max(0.0, rampTimeMs);
101
102 // Exponential: 1-pole coefficient. A zero ramp used to be floored at
103 // 0.1 ms, so a caller asking for "no smoothing" (Gain documents
104 // non-positive ramps as 0) still got a few samples of glide.
105 const double tauSamples = sampleRate_ * rampTimeMs_ / 1000.0;
106 expCoeff_ = (tauSamples > 0.0) ? std::exp(-1.0 / tauSamples) : 0.0;
107
108 // Linear: ramp length in samples; the per-sample rate is sized from
109 // the remaining distance so an in-flight ramp keeps its new duration.
110 rampSamples_ = std::max(1.0, rampTimeMs_ * sampleRate_ / 1000.0);
111 updateLinearRate();
112
113 // Chase: the speed constants are tuned at 44.1 kHz in samples, where
114 // they cover 99% of a step in kChaseNaturalMs. The decay of the speed
115 // and the speed itself both scale with the rate, so the curve takes
116 // the same time at any rate (unscaled, 0 -> 0.99 took 171 ms at
117 // 44.1 kHz but 53 ms at 192 kHz), and with the ramp time: the whole
118 // curve is stretched by stretch = rampTimeMs / kChaseNaturalMs. The
119 // speed recursion v <- m v - a is affine, so its exact stretched step
120 // is v <- m^(1/stretch) v - a stretch (1 - m^(1/stretch)) / (1 - m)
121 // with the speed itself (a time constant in samples) and its bounds
122 // scaled by stretch.
123 const double srRatio = 44100.0 / sampleRate_;
124 const double m = std::pow(0.9999, srRatio);
125 const double stretch = std::max(rampTimeMs_, 1e-3) / kChaseNaturalMs;
126 if (stretch == 1.0)
127 {
128 chaseMultDecay_ = m;
129 chaseAddDecay_ = 0.01 * srRatio;
130 }
131 else
132 {
133 const double ms = std::pow(m, 1.0 / stretch);
134 chaseMultDecay_ = ms;
135 chaseAddDecay_ = 0.01 * srRatio * stretch * (1.0 - ms) / (1.0 - m);
136 }
137 chaseMinSpeed_ = kChaseMinSpeed * stretch;
138 chaseMaxSpeed_ = kChaseMaxSpeed * stretch;
139 chaseRateScale_ = 1.0 / srRatio;
140 if (chaseSpeed_ < chaseMinSpeed_ || chaseSpeed_ > chaseMaxSpeed_) chaseSpeed_ = chaseMinSpeed_;
141 }
142
144 void setSmoothingType(SmoothingType type) noexcept
145 {
146 type_ = type;
147 updateLinearRate(); // a switch to Linear mid-flight keeps the full ramp time
148 }
149
151 [[nodiscard]] SmoothingType getSmoothingType() const noexcept { return type_; }
152
169 void setAdaptiveRamp(double span, double fastMs, double slowMs) noexcept
170 {
171 if (!(span > 0.0) || !std::isfinite(span) || !std::isfinite(fastMs) || !std::isfinite(slowMs))
172 {
173 adaptiveSpan_ = 0.0;
174 }
175 else
176 {
177 adaptiveSpan_ = span;
178 adaptiveFastMs_ = std::max(0.0, fastMs);
179 adaptiveSlowMs_ = std::max(0.0, slowMs);
180 }
181 updateLinearRate();
182 }
183
185 [[nodiscard]] bool hasAdaptiveRamp() const noexcept { return adaptiveSpan_ > 0.0; }
186
193 void setTargetValue(T newTarget) noexcept
194 {
195 if (!std::isfinite(newTarget)) return;
196 if (newTarget != target_)
197 {
198 target_ = newTarget;
199 snapEps_ = snapEpsilonFor(newTarget);
200 updateLinearRate();
201 if (type_ == SmoothingType::Chase)
202 chaseSpeed_ = chaseMaxSpeed_; // Reset chase velocity on target change
203 }
204 }
205
210 [[nodiscard]] T getNextValue() noexcept
211 {
212 const double target = static_cast<double>(target_);
213 if (current_ == target) return target_;
214
215 switch (type_)
216 {
218 {
219 current_ = target + expCoeff_ * (current_ - target);
220 break;
221 }
223 {
224 if (current_ < target)
225 current_ = std::min(current_ + linearRate_, target);
226 else
227 current_ = std::max(current_ - linearRate_, target);
228 break;
229 }
231 {
232 current_ = target;
233 break;
234 }
236 {
237 if (rampTimeMs_ <= 0.0) { current_ = target; break; }
238 // The speed only falls after its reset to the maximum, so the
239 // upper bound never binds: only the floor is applied.
240 chaseSpeed_ = std::max(chaseMinSpeed_, chaseSpeed_ * chaseMultDecay_ - chaseAddDecay_);
241 const double speed = chaseSpeed_ * chaseRateScale_;
242 current_ = (current_ * speed + target) / (speed + 1.0);
243 break;
244 }
245 }
246
247 // Exact arrival: snap once within a relative epsilon of the target.
248 // Relative because with large magnitudes (e.g. a frequency of 10000)
249 // a purely absolute threshold would be finer than the float ulp.
250 if (std::abs(current_ - target) < snapEps_)
251 current_ = target;
252
253 return static_cast<T>(current_);
254 }
255
267 void processBlock(std::span<T> buffer) noexcept
268 {
269 const double target = static_cast<double>(target_);
270 const size_t n = buffer.size();
271 if (current_ == target)
272 {
273 std::fill(buffer.begin(), buffer.end(), target_);
274 return;
275 }
276
277 // Work on locals: the compiler cannot prove the span does not alias
278 // the members, so member accesses would be re-loaded each iteration.
279 // The per-sample arrival snap matches getNextValue(); once settled,
280 // the rest of the block is a plain fill.
281 double current = current_;
282 const double eps = snapEps_;
283 size_t i = 0;
284
285 switch (type_)
286 {
288 {
289 const double coeff = expCoeff_;
290 for (; i < n; ++i)
291 {
292 current = target + coeff * (current - target);
293 if (std::abs(current - target) < eps) { current = target; break; }
294 buffer[i] = static_cast<T>(current);
295 }
296 break;
297 }
298
300 {
301 const double rate = linearRate_;
302 for (; i < n; ++i)
303 {
304 if (current < target) current = std::min(current + rate, target);
305 else if (current > target) current = std::max(current - rate, target);
306 if (std::abs(current - target) < eps) { current = target; break; }
307 buffer[i] = static_cast<T>(current);
308 }
309 break;
310 }
311
313 current = target;
314 break;
315
317 {
318 if (rampTimeMs_ <= 0.0) { current = target; break; }
319 double speed = chaseSpeed_;
320 const double multDecay = chaseMultDecay_;
321 const double addDecay = chaseAddDecay_;
322 const double rateScale = chaseRateScale_;
323 const double lo = chaseMinSpeed_;
324 for (; i < n; ++i)
325 {
326 speed = std::max(lo, speed * multDecay - addDecay); // falls only: no ceiling needed
327 const double scaled = speed * rateScale;
328 current = (current * scaled + target) / (scaled + 1.0);
329 if (std::abs(current - target) < eps) { current = target; break; }
330 buffer[i] = static_cast<T>(current);
331 }
332 chaseSpeed_ = speed;
333 break;
334 }
335 }
336
337 // Settled (or Disabled): the remainder of the block is the target.
338 for (; i < n; ++i)
339 buffer[i] = target_;
340
341 current_ = current;
342 }
343
345 [[nodiscard]] T getCurrentValue() const noexcept { return static_cast<T>(current_); }
346
348 [[nodiscard]] T getTargetValue() const noexcept { return target_; }
349
351 [[nodiscard]] bool isSmoothing() const noexcept { return current_ != static_cast<double>(target_); }
352
354 void skip() noexcept { current_ = static_cast<double>(target_); chaseSpeed_ = chaseMinSpeed_; }
355
357 void reset(T value = T(0)) noexcept
358 {
359 target_ = value;
360 snapEps_ = snapEpsilonFor(value);
361 current_ = static_cast<double>(value);
362 chaseSpeed_ = chaseMinSpeed_;
363 }
364
366 void setRampTime(double sampleRate, double rampTimeMs) noexcept
367 {
368 prepare(sampleRate, rampTimeMs);
369 }
370
371private:
373 [[nodiscard]] static double snapEpsilonFor(T target) noexcept
374 {
375 return kEpsilon * std::max(1.0, std::abs(static_cast<double>(target)));
376 }
377
378 void updateLinearRate() noexcept
379 {
380 const double distance = std::abs(static_cast<double>(target_) - current_);
381 double samples = rampSamples_;
382 if (adaptiveSpan_ > 0.0)
383 {
384 const double closeness = std::max(0.0, 1.0 - distance / adaptiveSpan_);
385 const double ms = adaptiveFastMs_ + (adaptiveSlowMs_ - adaptiveFastMs_) * closeness * closeness;
386 samples = std::max(1.0, ms * sampleRate_ / 1000.0);
387 }
388 linearRate_ = distance / samples;
389 }
390
391 double current_{ 0.0 };
392 T target_{ T(0) };
394
395 // DSP coefficients (double: recursive state and its drivers, see @class)
396 double expCoeff_{ 0.0 };
397 double linearRate_{ 0.0 };
398 double rampSamples_{ 882.0 };
399
400 // Step-dependent linear ramps (off while the span is zero)
401 double adaptiveSpan_{ 0.0 };
402 double adaptiveFastMs_{ 20.0 };
403 double adaptiveSlowMs_{ 150.0 };
404
405 // Chase state & coefficients
406 static constexpr double kChaseNaturalMs = 171.0;
407 static constexpr double kChaseMinSpeed = 350.0;
408 static constexpr double kChaseMaxSpeed = 2500.0;
409 double chaseSpeed_{ 350.0 };
410 double chaseMultDecay_{ 0.9999 };
411 double chaseAddDecay_{ 0.01 };
412 double chaseRateScale_{ 1.0 };
413 double chaseMinSpeed_{ 350.0 };
414 double chaseMaxSpeed_{ 2500.0 };
415
416 double sampleRate_{ 44100.0 };
417 double rampTimeMs_{ 20.0 };
418
419 static constexpr double kEpsilon = 1e-7;
420 double snapEps_ { kEpsilon };
421};
422
423} // namespace dspark
Zero-allocation parameter smoother for real-time audio.
void setSmoothingType(SmoothingType type) noexcept
Sets the smoothing algorithm.
SmoothedValue & operator=(const SmoothedValue &)=delete
void reset(T value=T(0)) noexcept
Hard-resets both current and target states to a specific value.
void setRampTime(double sampleRate, double rampTimeMs) noexcept
Updates sample rate and/or ramp time, recalculating internal steps.
T getNextValue() noexcept
Calculates and returns the next smoothed value.
T getCurrentValue() const noexcept
Returns the current internal value without advancing the state.
bool hasAdaptiveRamp() const noexcept
Whether step-dependent ramps are on (see setAdaptiveRamp()).
void skip() noexcept
Forces the current value to instantly match the target, bypassing time.
bool isSmoothing() const noexcept
Evaluates if the smoother is actively transitioning.
void setTargetValue(T newTarget) noexcept
Updates the target value. Safe to call continuously (e.g., from host automation).
@ Linear
Rate-limited ramp. Constant velocity, exact target arrival.
@ Disabled
Instant snapping, no smoothing applied.
@ Exponential
One-pole IIR. Natural, musical interpolation.
@ Chase
Adaptive speed. Gentle start after a jump, accelerating settle.
void processBlock(std::span< T > buffer) noexcept
Computes a block of smoothed values into an output buffer.
SmoothedValue(const SmoothedValue &)=delete
Prevents accidental copying of stateful DSP objects.
SmoothingType getSmoothingType() const noexcept
Returns the current smoothing algorithm.
T getTargetValue() const noexcept
Returns the set target value.
void prepare(double sampleRate, double rampTimeMs=20.0) noexcept
Precalculates internal coefficients based on sample rate and timing.
void setAdaptiveRamp(double span, double fastMs, double slowMs) noexcept
Makes the duration of every Linear ramp depend on its step.
Main namespace for the DSPark framework.