Sound Byte Libs 0.5.1-340-gab5b79a
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
blep_osc.hpp
Go to the documentation of this file.
1/**
2 * @file blep_osc.hpp
3 * @brief The BLEP oscillator core: one phase, three waveform parts, band-limited edges
4 */
5
6#ifndef SBL_DSP_OSCILLATORS_BLEP_OSC_HPP_
7#define SBL_DSP_OSCILLATORS_BLEP_OSC_HPP_
8
9#include <cmath>
10#include <cstdint>
11#include <initializer_list>
16#include <sbl/math/clamp.hpp>
17#include <sbl/math/finite.hpp>
18
19namespace sbl::dsp {
20
21/**
22 * @brief The BLEP oscillator core: one phase, three waveform parts, band-limited edges
23 *
24 * One phase accumulator drives a saw with a movable knee, a pulse of
25 * variable width and a triangle with a variable peak position. The naive
26 * output is the weighted sum of the three; every step and corner in it is corrected at its
27 * sub-frame time through a BlepCorrector over the Kernel, so the output
28 * trails the naive waveform by LATENCY frames and a harmonic at f is scaled
29 * by the kernel's response. The kernel is a compile-time choice
30 * (dsp/math/polyblep.hpp): the default is math::Sinc16; math::Bspline4 and
31 * math::Linear2 never overshoot.
32 *
33 * The core is below the signal transport: its inputs are natural units,
34 * set by the composition that owns it, which carries the ports and does the
35 * one conversion. Frequency is cycles per frame, so
36 * the core holds no sample rate.
37 *
38 * Inputs and their handling, per frame:
39 * - Frequency is clamped to [0, MAX_FREQUENCY], a quarter cycle per frame
40 * (fs/4). At zero the phase holds. A non-finite value counts as zero.
41 * - Pulse width, saw knee and triangle peak are fractions of a cycle. Each
42 * frame they are kept at least one frame's travel away from the wrap, in
43 * [frequency, 1 - frequency], so a frame holds at most one event per part
44 * besides the wrap and the event times stay exact. The margin is for the
45 * event bookkeeping, not for band-limiting; it narrows the pulse's reach
46 * at high frequency (a quarter to three quarters at the cap). The knee and the peak also stay in
47 * [MIN_BREAKPOINT, 1 - MIN_BREAKPOINT], which keeps the slopes finite.
48 * - The saw knee is phase distortion: the phase runs to the knee over the
49 * first half of the saw's range and from it over the second, so the saw
50 * is a two-slope ramp with a corner at the knee and a second corner at
51 * the wrap. At 0.5 it is the plain saw. Its mean is 0.5 - knee; the core
52 * removes no DC.
53 * - A pulse-width change is a moving threshold: the edge it moves is
54 * band-limited at its new time and nothing is ramped.
55 * - Blend weights, the saw knee and the triangle peak change the naive value
56 * directly, so they ramp linearly over RAMP_FRAMES frames from the frame
57 * after the call, carried across process() calls.
58 * - A frequency change takes effect at the next frame. The slope change it
59 * gives the saw and triangle is not corrected.
60 *
61 * Output is nominally [-1, 1] per part. With Bspline4 or Linear2, kernels
62 * that never overshoot, the peak cannot exceed the sum of the weights'
63 * magnitudes; with Sinc16 a step overshoots by 8.2 % of its height
64 * (polyblep.hpp). The pulse is low before its edge and high after it, as in
65 * Plaits, so it shares the saw's drop at the wrap and a saw-to-pulse blend
66 * morphs without a dip. A pulse with its edge at w carries a mean of 1 - 2w;
67 * the core removes no DC.
68 *
69 * Output does not depend on how the stream is split into calls: all state
70 * advances per frame.
71 *
72 * @tparam Kernel The BLEP kernel; math::Sinc16 by default
73 */
74template<class Kernel = math::Sinc16>
75class BlepOsc {
76public:
77 static constexpr float MAX_FREQUENCY = 0.25f; /**< cycles per frame: fs/4 */
78 static constexpr float MIN_BREAKPOINT = 1.0f / 32.0f; /**< the knee's and the peak's distance from either end */
79 static constexpr uint16_t RAMP_FRAMES = 64; /**< blend and peak changes ramp over this many frames */
80 static constexpr uint8_t LATENCY = Kernel::LATENCY; /**< frames the output trails the naive waveform */
81
82 /** @brief A saw at zero frequency until set; blend, knee and peak changes ramp over RAMP_FRAMES. */
84 for (Ramp* r : {&saw_, &pulse_, &triangle_, &peak_, &knee_}) {
85 r->set_length(RAMP_FRAMES);
86 }
87 }
88
89 /**
90 * @brief Set the frequency. Takes effect at the next frame.
91 *
92 * @param cycles_per_frame Frequency in cycles per frame, clamped to [0, MAX_FREQUENCY]; non-finite counts as zero
93 * @context Same thread as process(); real-time safe.
94 */
95 void set_frequency(float cycles_per_frame) {
96 frequency_ = sbl::math::clamp(sbl::math::finite_or(cycles_per_frame, 0.0f), 0.0f, MAX_FREQUENCY);
97 }
98
99 /**
100 * @brief Set where the pulse's rising edge falls in the cycle. Takes effect next frame as a moving edge.
101 *
102 * @param fraction_of_cycle Edge position, clamped to [0, 1]: low before it, high from it to the wrap;
103 * non-finite counts as 0.5
104 * @context Same thread as process(); real-time safe.
105 */
106 void set_pulse_width(float fraction_of_cycle) {
107 width_target_ = sbl::math::clamp(sbl::math::finite_or(fraction_of_cycle, 0.5f), 0.0f, 1.0f);
108 }
109
110 /**
111 * @brief Set where the saw's phase bends. Ramps over RAMP_FRAMES.
112 *
113 * @param fraction_of_cycle Knee, clamped to [MIN_BREAKPOINT, 1 - MIN_BREAKPOINT]; 0.5 is the plain saw;
114 * non-finite counts as 0.5
115 * @context Same thread as process(); real-time safe.
116 */
117 void set_saw_knee(float fraction_of_cycle) {
118 knee_.set(
119 sbl::math::clamp(sbl::math::finite_or(fraction_of_cycle, 0.5f), MIN_BREAKPOINT, 1.0f - MIN_BREAKPOINT));
120 }
121
122 /**
123 * @brief Set where the triangle peaks within the cycle. Ramps over RAMP_FRAMES.
124 *
125 * @param fraction_of_cycle Peak, clamped to [MIN_BREAKPOINT, 1 - MIN_BREAKPOINT]; non-finite counts as 0.5
126 * @context Same thread as process(); real-time safe.
127 */
128 void set_triangle_peak(float fraction_of_cycle) {
129 peak_.set(
130 sbl::math::clamp(sbl::math::finite_or(fraction_of_cycle, 0.5f), MIN_BREAKPOINT, 1.0f - MIN_BREAKPOINT));
131 }
132
133 /**
134 * @brief Set the weights of the three parts in the sum. Ramp over RAMP_FRAMES.
135 *
136 * @param saw Weight of the saw; non-finite counts as zero
137 * @param pulse Weight of the pulse; non-finite counts as zero
138 * @param triangle Weight of the triangle; non-finite counts as zero
139 * @context Same thread as process(); real-time safe.
140 */
141 void set_blend(float saw, float pulse, float triangle) {
142 saw_.set(sbl::math::finite_or(saw, 0.0f));
143 pulse_.set(sbl::math::finite_or(pulse, 0.0f));
144 triangle_.set(sbl::math::finite_or(triangle, 0.0f));
145 }
146
147 /**
148 * @brief One frame.
149 *
150 * @return The corrected sample LATENCY frames back
151 * @context Audio thread; real-time safe.
152 */
153 float process() {
154 const float f = frequency_;
155 const float p0 = phase_;
156 float p = p0 + f;
157 const bool wrapped = p >= 1.0f;
158 if (wrapped) {
159 p -= 1.0f;
160 }
161 phase_ = p;
162
163 const float ws = saw_.step();
164 const float wp = pulse_.step();
165 const float wt = triangle_.step();
166 const float w_prev = width_;
167 const float k_prev = peak_now_;
168 const float c_prev = knee_now_;
169 const float w = sbl::math::clamp(width_target_, f, 1.0f - f);
170 const float margin = f > MIN_BREAKPOINT ? f : MIN_BREAKPOINT;
171 const float k = sbl::math::clamp(peak_.step(), margin, 1.0f - margin);
172 const float c = sbl::math::clamp(knee_.step(), margin, 1.0f - margin);
173 width_ = w;
174 peak_now_ = k;
175 knee_now_ = c;
176
177 const float triangle_corner = 2.0f / k + 2.0f / (1.0f - k); // slope change per cycle at the wrap
178 const float saw_corner = 1.0f / (1.0f - c) - 1.0f / c; // slope change per cycle at the knee; zero at 0.5
179
180 if (wrapped) {
181 // Below the wrap the pulse is high and the triangle falls, since w and k are at
182 // least a frame short of 1; above it the pulse is low and the triangle rises.
183 const float t = math::polyblep_time(p0 - 1.0f, p, 0.0f);
184 corrector_.step(t, ws * -2.0f);
185 corrector_.corner(t, ws * f * -saw_corner); // back from the slow slope to the fast one
186 corrector_.step(t, wp * -2.0f);
187 corrector_.corner(t, wt * f * triangle_corner);
188 } else {
189 const bool low_before = p0 < w_prev;
190 const bool low_after = p < w;
191 if (low_before != low_after) {
192 const float t = math::polyblep_time(p0, p, w_prev, w);
193 corrector_.step(t, wp * (low_after ? -2.0f : 2.0f));
194 }
195 const bool rising_before = p0 < k_prev;
196 const bool rising_after = p < k;
197 if (rising_before != rising_after) {
198 const float t = math::polyblep_time(p0, p, k_prev, k);
199 corrector_.corner(t, wt * f * (rising_after ? triangle_corner : -triangle_corner));
200 }
201 const bool fast_before = p0 < c_prev;
202 const bool fast_after = p < c;
203 if (fast_before != fast_after) {
204 const float t = math::polyblep_time(p0, p, c_prev, c);
205 corrector_.corner(t, ws * f * (fast_after ? -saw_corner : saw_corner));
206 }
207 }
208
209 const float saw = p < c ? (-1.0f + p / c) : ((p - c) / (1.0f - c));
210 const float pulse = p < w ? -1.0f : 1.0f;
211 const float triangle = p < k ? (-1.0f + 2.0f * p / k) : (1.0f - 2.0f * (p - k) / (1.0f - k));
212 return corrector_.process(ws * saw + wp * pulse + wt * triangle);
213 }
214
215 /** @brief The ports, in the order the buffer call takes them; each sets the quantity of the setter of its name. */
216 static constexpr transport::Port PORTS[] = {
218 {"pulse_width"},
219 {"saw_knee", transport::Spelling::Scalar},
222 {"triangle", transport::Spelling::Scalar},
223 {"triangle_peak", transport::Spelling::Scalar},
224 };
225
226 /**
227 * @brief A buffer of frames, the ports in PORTS' order, any trailing ones left off
228 *
229 * Frequency and pulse width as blocks are set each frame: the audio-rate
230 * FM and PWM paths. As scalars they are set once, before the block's first
231 * frame, and take effect as their setters say. The knee, the blend weights
232 * and the triangle peak are scalars and ramp over RAMP_FRAMES. A port left
233 * off holds its last value.
234 *
235 * @tparam Ports A block or an arithmetic scalar for frequency and pulse_width; scalars for the rest
236 * @param[out] out Output buffer, `frames` long
237 * @param frames Frame count
238 * @param ports frequency in cycles per frame, pulse_width, saw_knee, saw, pulse, triangle, triangle_peak, as their setters take them
239 * @context Audio thread; real-time safe.
240 */
241 template<class... Ports>
242 void process(float* out, uint16_t frames, Ports... ports) {
243 static_assert(transport::fits_v<BlepOsc, Ports...>,
244 "SBL ERROR: BlepOsc takes frequency and pulse_width (blocks or scalars), then saw_knee, saw, "
245 "pulse, triangle and triangle_peak (scalars)");
246 const auto frequency = transport::arg<0>(ports...);
247 const auto width = transport::arg<1>(ports...);
248 const auto knee = transport::arg<2>(ports...);
249 const auto saw = transport::arg<3>(ports...);
250 const auto pulse = transport::arg<4>(ports...);
251 const auto triangle = transport::arg<5>(ports...);
252 const auto peak = transport::arg<6>(ports...);
253 if constexpr (transport::is_scalar_v<decltype(knee)>) {
254 set_saw_knee(static_cast<float>(knee));
255 }
256 if constexpr (transport::is_scalar_v<decltype(saw)>) {
257 saw_.set(sbl::math::finite_or(static_cast<float>(saw), 0.0f));
258 }
259 if constexpr (transport::is_scalar_v<decltype(pulse)>) {
260 pulse_.set(sbl::math::finite_or(static_cast<float>(pulse), 0.0f));
261 }
262 if constexpr (transport::is_scalar_v<decltype(triangle)>) {
263 triangle_.set(sbl::math::finite_or(static_cast<float>(triangle), 0.0f));
264 }
265 if constexpr (transport::is_scalar_v<decltype(peak)>) {
266 set_triangle_peak(static_cast<float>(peak));
267 }
268 if constexpr (transport::is_scalar_v<decltype(frequency)>) {
269 set_frequency(static_cast<float>(frequency));
270 }
271 if constexpr (transport::is_scalar_v<decltype(width)>) {
272 set_pulse_width(static_cast<float>(width));
273 }
274 for (uint16_t i = 0; i < frames; ++i) {
275 if constexpr (transport::is_block_v<decltype(frequency)>) {
277 }
278 if constexpr (transport::is_block_v<decltype(width)>) {
279 set_pulse_width(width[i]);
280 }
281 out[i] = process();
282 }
283 }
284
285 /** @brief Phase to zero, ramps to their targets, corrections dropped. */
286 void reset() {
287 phase_ = 0.0f;
288 saw_.jump(saw_.target());
289 pulse_.jump(pulse_.target());
290 triangle_.jump(triangle_.target());
291 peak_.jump(peak_.target());
292 knee_.jump(knee_.target());
293 width_ = width_target_;
294 peak_now_ = peak_.value();
295 knee_now_ = knee_.value();
296 corrector_.reset();
297 }
298
299 /** @brief The phase after the last frame, in [0, 1). */
300 float phase() const { return phase_; }
301 /** @brief The frequency, in cycles per frame. */
302 float frequency() const { return frequency_; }
303
304private:
305 float phase_ = 0.0f;
306 float frequency_ = 0.0f;
307 float width_target_ = 0.5f;
308 float width_ = 0.5f; /**< the clamped width used last frame */
309 float peak_now_ = 0.5f; /**< the clamped peak used last frame */
310 float knee_now_ = 0.5f; /**< the clamped knee used last frame */
311 Ramp saw_{1.0f};
312 Ramp pulse_{0.0f};
313 Ramp triangle_{0.0f};
314 Ramp peak_{0.5f};
315 Ramp knee_{0.5f};
316 BlepCorrector<Kernel> corrector_{};
317};
318
319} // namespace sbl::dsp
320
321#endif // SBL_DSP_OSCILLATORS_BLEP_OSC_HPP_
The correction buffer behind a band-limited edge, over a BLEP kernel.
Clamping.
The BLEP oscillator core: one phase, three waveform parts, band-limited edges.
Definition blep_osc.hpp:75
void set_pulse_width(float fraction_of_cycle)
Set where the pulse's rising edge falls in the cycle. Takes effect next frame as a moving edge.
Definition blep_osc.hpp:106
void set_blend(float saw, float pulse, float triangle)
Set the weights of the three parts in the sum. Ramp over RAMP_FRAMES.
Definition blep_osc.hpp:141
BlepOsc()
A saw at zero frequency until set; blend, knee and peak changes ramp over RAMP_FRAMES.
Definition blep_osc.hpp:83
static constexpr transport::Port PORTS[]
The ports, in the order the buffer call takes them; each sets the quantity of the setter of its name.
Definition blep_osc.hpp:216
static constexpr uint16_t RAMP_FRAMES
Definition blep_osc.hpp:79
float frequency() const
The frequency, in cycles per frame.
Definition blep_osc.hpp:302
void set_frequency(float cycles_per_frame)
Set the frequency. Takes effect at the next frame.
Definition blep_osc.hpp:95
float phase() const
The phase after the last frame, in [0, 1).
Definition blep_osc.hpp:300
static constexpr uint8_t LATENCY
Definition blep_osc.hpp:80
void set_saw_knee(float fraction_of_cycle)
Set where the saw's phase bends. Ramps over RAMP_FRAMES.
Definition blep_osc.hpp:117
static constexpr float MIN_BREAKPOINT
Definition blep_osc.hpp:78
float process()
One frame.
Definition blep_osc.hpp:153
void set_triangle_peak(float fraction_of_cycle)
Set where the triangle peaks within the cycle. Ramps over RAMP_FRAMES.
Definition blep_osc.hpp:128
static constexpr float MAX_FREQUENCY
Definition blep_osc.hpp:77
void reset()
Phase to zero, ramps to their targets, corrections dropped.
Definition blep_osc.hpp:286
void process(float *out, uint16_t frames, Ports... ports)
A buffer of frames, the ports in PORTS' order, any trailing ones left off.
Definition blep_osc.hpp:242
A linear ramp to a target over a fixed number of frames.
Definition ramp.hpp:25
float step()
One frame.
Definition ramp.hpp:90
float target() const
The value the ramp heads for.
Definition ramp.hpp:103
void set(float target)
Head for a target from the current value.
Definition ramp.hpp:48
float value() const
The current value.
Definition ramp.hpp:101
void jump(float value)
Arrive at a value at once.
Definition ramp.hpp:77
Finiteness of a float, read from its bits, and a fallback for a value that is not finite.
constexpr float polyblep_time(float before, float after, float threshold_before, float threshold_after)
Sub-frame time at which a linear segment crossed a moving threshold.
Definition polyblep.hpp:242
The audio stack.
Definition dry_wet.hpp:15
float finite_or(float x, float fallback)
x, or fallback when x is an infinity or a NaN.
Definition finite.hpp:36
constexpr T clamp(T x, T lo, T hi)
x held to [lo, hi]; a NaN goes to lo.
Definition clamp.hpp:24
constexpr bool fits_v
Polynomial BLEP kernels, and the sub-frame time of a crossing.
A linear ramp to a target over a fixed number of frames.
The processing call's shape as a checked contract.