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
phase_saw.hpp
Go to the documentation of this file.
1/**
2 * @file phase_saw.hpp
3 * @brief A band-limited slope shape driven by a signed phase, from a falling saw through a triangle to a rising saw
4 */
5
6#ifndef SBL_DSP_OSCILLATORS_PHASE_SAW_HPP_
7#define SBL_DSP_OSCILLATORS_PHASE_SAW_HPP_
8
9#include <cmath>
10#include <cstdint>
15#include <sbl/math/clamp.hpp>
16#include <sbl/math/finite.hpp>
17
18namespace sbl::dsp {
19
20/**
21 * @brief A band-limited slope shape driven by a signed phase, from a falling saw through a triangle to a rising saw
22 *
23 * The shape rises from -1 to +1 over w of the cycle, on [rise, fall), and
24 * falls from +1 to -1 over the rest. Its corners sit where PhasePulse's edges
25 * sit for the same width and anchor: the trough at PhasePulse::rise(w, a),
26 * the peak at PhasePulse::fall(w, a). Width 0.5 is a triangle; toward 0 the
27 * shape is a falling saw, toward 1 a rising saw. The anchor means what it
28 * means for the pulse: which corner holds as width changes, and how far a
29 * change dw moves the fundamental's phase, -a dw/2 of a cycle.
30 *
31 * The shape's slope is the pulse's, less its mean, times K = 2 / (w (1 - w)),
32 * so each harmonic is K / (2 pi k) times PhasePulse's and a quarter cycle
33 * behind it. Its mean is 0 at every width; it carries no
34 * DC. Width 1 - w is the shape at w inverted and shifted, so mirrored widths
35 * in a pair keep the pulse's relation.
36 *
37 * The core owns no phase accumulator and walks each frame as PhasePulse does,
38 * through a PhaseWalk: the driver gives the phase, in [0, 1), the
39 * signed step that led there, in cycles, and a phase offset at the end of
40 * each of SUBSTEPS parts of the frame, and the core reads the phase plus the
41 * offset. Forward, backward and through zero, across the wrap, with the
42 * offset as phase modulation; every corner crossed in the frame is corrected
43 * at its own time through a BlepCorrector over the Kernel, so the output
44 * trails the naive shape by LATENCY frames.
45 *
46 * A corner's correction is a slope change: K times the phase's speed relative
47 * to the corner, in cycles per frame, K taken at the width at the crossing. A
48 * trough is a trough in either direction of travel, so the sign is the
49 * corner's, not the direction's: +K |speed| at the trough, -K |speed| at the
50 * peak. Under phase modulation the speed is each sub-step's. Each correction
51 * is a change from the slope before it, so the first frame after a reset
52 * starts the count: the shape's slope at the starting phase times the first
53 * speed, corrected at the reset's instant. Without it a start on the short
54 * segment, or on its trough, leaves the next corner unpaired.
55 *
56 * The phase is linear within each sub-step, and the shape's slope is not
57 * zero, so where the phase's speed changes between sub-steps or frames the
58 * shape's slope changes by its slope times the change: 2 / w on the rising
59 * segment. Those changes are not corrected, as BlepOsc leaves a frequency
60 * change's. Under phase modulation they leave aliasing that grows
61 * with the depth, the pitch and the narrowness of the short segment.
62 *
63 * Width and anchor take effect across the next frame, moving linearly, as
64 * PhasePulse's do, and nothing is ramped, so a pulse and a saw given the same
65 * width and anchor stay in step. A corner a change moves past the phase is
66 * corrected like any other crossing. Unlike the pulse's level, the shape's
67 * value also changes along a segment when width changes, and the slope
68 * changes where that motion starts and stops are not corrected. Near the
69 * floor the value at a phase goes as 1 / w, so a large step of width within
70 * one frame is no longer a straight segment between corners, and its
71 * correction overshoots. Ramped over 48 frames, as a driver's ramp moves
72 * it, the peak is no higher than the static one (test_phase_saw.hpp). A driver ramps width, and sets
73 * it before reset() for the first frame to start from it.
74 *
75 * The core is below the signal transport. Its
76 * inputs are natural units, set by the driver that owns it.
77 *
78 * Inputs and their handling, per frame:
79 * - The step, the offset's change included, is clamped to [-MAX_STEP,
80 * MAX_STEP], one cycle per frame (PhaseWalk).
81 * - A phase outside [0, 1) is wrapped into it. A non-finite phase or step
82 * counts as no motion: the phase holds. A non-finite offset holds the
83 * previous one.
84 * - Width is clamped to [WIDTH_FLOOR, 1 - WIDTH_FLOOR]; non-finite counts as
85 * 0.5. Toward 0 and 1 the slope of the short segment grows as 1/w, and
86 * with it the naive value's sensitivity to the phase's rounding: against
87 * the same shape and corrections worked in double, the error stays under
88 * 2.4e-4 at the floor (test_phase_saw.hpp), and grows as 1/w below it.
89 * Under phase modulation the slope changes on the short
90 * segment are not corrected and also grow as 1/w: with a sine at the
91 * pitch half a cycle deep at 1.1 kHz the output stays within the naive
92 * range at width 0.001 and under 1.4 at the floor (test_phase_saw.hpp).
93 * - The anchor is clamped to [-1, 1]; non-finite counts as 0.
94 *
95 * With Bspline4 or Linear2, kernels that never overshoot, output is in
96 * [-1, 1]. With Sinc16 the corners ring, and the peak grows as the short
97 * segment shortens toward a step, whose overshoot is 8.2 % of its height
98 * (polyblep.hpp). From 110 Hz to 4.4 kHz the peak stays at or under 1.165
99 * at every width (test_phase_saw.hpp).
100 *
101 * Output does not depend on how the stream is split into calls: all state
102 * advances per frame.
103 *
104 * @tparam Kernel The BLEP kernel; math::Sinc16 by default
105 */
106template<class Kernel = math::Sinc16>
107class PhaseSaw {
108public:
109 static constexpr float MAX_STEP = PhaseWalk::MAX_STEP; /**< cycles per frame, either direction */
110 static constexpr float WIDTH_FLOOR = 0.0005f; /**< the narrowest segment, a two-thousandth of the cycle */
111 static constexpr uint8_t LATENCY = Kernel::LATENCY; /**< frames the output trails the naive shape */
112
113 /**
114 * @brief Set the rising segment's share of the cycle. Takes effect next frame.
115 *
116 * @param fraction_of_cycle Width, clamped to [WIDTH_FLOOR, 1 - WIDTH_FLOOR]; non-finite counts as 0.5
117 * @context Same thread as process(); real-time safe.
118 */
119 void set_width(float fraction_of_cycle) {
120 width_target_ =
121 sbl::math::clamp(sbl::math::finite_or(fraction_of_cycle, 0.5f), WIDTH_FLOOR, 1.0f - WIDTH_FLOOR);
122 }
123
124 /**
125 * @brief Set where width acts. Takes effect next frame.
126 *
127 * @param anchor Clamped to [-1, 1]: -1 holds the trough at the wrap, 0 the center at 1/2, +1 the peak at the
128 * wrap; non-finite counts as 0
129 * @context Same thread as process(); real-time safe.
130 */
131 void set_anchor(float anchor) {
132 anchor_target_ = sbl::math::clamp(sbl::math::finite_or(anchor, 0.0f), -1.0f, 1.0f);
133 }
134
135 /**
136 * @brief One frame: the corrected sample LATENCY frames back
137 *
138 * @param phase The frame's phase, in [0, 1)
139 * @param step The signed step from the previous frame's phase, in cycles
140 * @param offset The frame's phase offset, in cycles; its change since the previous frame adds to the step
141 * @return The corrected sample LATENCY frames back
142 * @context Audio thread; real-time safe.
143 */
144 // cppcheck-suppress functionStatic ; cppcheck does not resolve the call to the offsets overload, which uses members
145 float process(float phase, float step, float offset) {
146 const float offsets[1] = {offset};
147 return process(phase, step, offsets);
148 }
149
150 /**
151 * @brief One frame in SUBSTEPS equal parts, the offset given at the end of each, as PhasePulse's
152 *
153 * Each part is a segment of its own, so an offset that curves within the
154 * frame is followed SUBSTEPS times more closely than by one segment. Width
155 * and anchor move linearly across the frame.
156 *
157 * @tparam SUBSTEPS Parts per frame, at least 1
158 * @param phase The frame's phase, in [0, 1)
159 * @param step The signed step from the previous frame's phase, in cycles
160 * @param offsets The phase offset at the end of each part, in cycles
161 * @return The corrected sample LATENCY frames back
162 * @context Audio thread; real-time safe.
163 */
164 template<uint8_t SUBSTEPS>
165 float process(float phase, float step, const float (&offsets)[SUBSTEPS]) {
166 static_assert(SUBSTEPS > 0, "SBL ERROR: a frame has at least one part");
167 const float width0 = width_;
168 const float rise0 = rise(width_, anchor_);
169 const float fall0 = fall(width_, anchor_);
170 width_ = width_target_;
171 anchor_ = anchor_target_;
172 const float rise1 = rise(width_, anchor_);
173 const float fall1 = fall(width_, anchor_);
174 float rise_from = rise0;
175 float fall_from = fall0;
176 float width_from = width0;
177 walk_.frame(phase, step, offsets, [&](const PhaseWalk::Segment& s) {
178 if (starting_) {
179 start(s, rise_from, fall_from, width_from);
180 }
181 // The last part ends on the corners the naive value is read with.
182 const float rise_to = s.last ? rise1 : rise0 + (rise1 - rise0) * s.through;
183 const float fall_to = s.last ? fall1 : fall0 + (fall1 - fall0) * s.through;
184 const float width_to = s.last ? width_ : width0 + (width_ - width0) * s.through;
185 corner(s, rise_from, rise_to, width_from, width_to, 1.0f);
186 corner(s, fall_from, fall_to, width_from, width_to, -1.0f);
187 rise_from = rise_to;
188 fall_from = fall_to;
189 width_from = width_to;
190 });
191 return corrector_.process(shape(walk_.phase(), rise1, fall1, width_));
192 }
193
194 /**
195 * @brief One frame with no offset: an offset carried before moves back to zero, as phase modulation.
196 *
197 * @param phase The frame's phase, in [0, 1)
198 * @param step The signed step from the previous frame's phase, in cycles
199 * @return The corrected sample LATENCY frames back
200 * @context Audio thread; real-time safe.
201 */
202 float process(float phase, float step) { return process(phase, step, 0.0f); }
203
204 /** @brief The ports, in the order the buffer call takes them, as PhasePulse's. */
205 static constexpr transport::Port PORTS[] = {
208 {"width"},
209 {"anchor"},
210 {"offset"},
211 };
212
213 /**
214 * @brief A buffer of frames: phase and step per frame, then width, anchor and offset, which may be left off
215 *
216 * As PhasePulse's: width and anchor as blocks are set each frame, as
217 * scalars once before the first frame; left off, they hold. The offset is
218 * per frame as a block and constant as a scalar; left off, it is zero.
219 *
220 * @tparam Ports Blocks for phase and step, then a block or an arithmetic scalar for each of the rest
221 * @param[out] out Output buffer, `frames` long
222 * @param frames Frame count
223 * @param ports phase in [0, 1) and step in cycles per frame, then width, anchor and offset in cycles
224 * @context Audio thread; real-time safe.
225 */
226 template<class... Ports>
227 void process(float* out, uint16_t frames, Ports... ports) {
228 static_assert(transport::fits_v<PhaseSaw, Ports...> && sizeof...(Ports) >= 2,
229 "SBL ERROR: PhaseSaw takes phase and step (blocks), then width, anchor and offset "
230 "(blocks or scalars)");
231 const auto phase = transport::arg<0>(ports...);
232 const auto step = transport::arg<1>(ports...);
233 const auto width = transport::arg<2>(ports...);
234 const auto anchor = transport::arg<3>(ports...);
235 const auto offset = transport::arg<4>(ports...);
236 if constexpr (transport::is_scalar_v<decltype(width)>) {
237 set_width(static_cast<float>(width));
238 }
239 if constexpr (transport::is_scalar_v<decltype(anchor)>) {
240 set_anchor(static_cast<float>(anchor));
241 }
242 for (uint16_t i = 0; i < frames; ++i) {
243 if constexpr (transport::is_block_v<decltype(width)>) {
244 set_width(width[i]);
245 }
246 if constexpr (transport::is_block_v<decltype(anchor)>) {
247 set_anchor(anchor[i]);
248 }
249 if constexpr (transport::is_block_v<decltype(offset)>) {
250 out[i] = process(phase[i], step[i], offset[i]);
251 } else if constexpr (transport::is_scalar_v<decltype(offset)>) {
252 out[i] = process(phase[i], step[i], static_cast<float>(offset));
253 } else {
254 out[i] = process(phase[i], step[i]);
255 }
256 }
257 }
258
259 /**
260 * @brief Move to a phase plus an offset; width and anchor to their targets, corrections dropped.
261 *
262 * @param phase Phase in cycles; a non-finite phase counts as 0
263 * @param offset Offset in cycles, kept as the last frame's; a non-finite offset counts as 0
264 */
265 void reset(float phase = 0.0f, float offset = 0.0f) {
266 walk_.reset(phase, offset);
267 width_ = width_target_;
268 anchor_ = anchor_target_;
269 corrector_.reset();
270 starting_ = true;
271 }
272
273 /** @brief The phase the core read last frame, the offset included. */
274 float phase() const { return walk_.phase(); }
275 /** @brief The offset the core read last frame, in cycles. */
276 float offset() const { return walk_.offset(); }
277 /** @brief The width set for the next frame. */
278 float width() const { return width_target_; }
279 /** @brief The anchor set for the next frame. */
280 float anchor() const { return anchor_target_; }
281
282 /**
283 * @brief The trough, where the shape starts to rise, as PhasePulse::rise().
284 *
285 * @param width Width, in [0, 1]
286 * @param anchor Anchor, in [-1, 1]
287 * @return (1 - w)(1 + a)/2, in [0, 1]
288 */
289 static constexpr float rise(float width, float anchor) { return 0.5f * (1.0f - width) * (1.0f + anchor); }
290
291 /**
292 * @brief The peak, where the shape starts to fall, as PhasePulse::fall().
293 *
294 * @param width Width, in [0, 1]
295 * @param anchor Anchor, in [-1, 1]
296 * @return 1 - (1 - w)(1 - a)/2, in [0, 1]
297 */
298 static constexpr float fall(float width, float anchor) { return 1.0f - 0.5f * (1.0f - width) * (1.0f - anchor); }
299
300 /**
301 * @brief The naive shape at a phase.
302 *
303 * @param phase Phase, in [0, 1)
304 * @param rise The trough, from rise()
305 * @param fall The peak, from fall()
306 * @param width The width the corners were taken at
307 * @return The shape's value, in [-1, 1]
308 */
309 static float shape(float phase, float rise, float fall, float width) {
310 if (phase >= rise && phase < fall) {
311 return -1.0f + 2.0f * (phase - rise) / width;
312 }
313 const float past = phase >= fall ? phase - fall : phase - fall + 1.0f; // past the peak, wrapped
314 return 1.0f - 2.0f * past / (1.0f - width);
315 }
316
317private:
318 /**
319 * @brief The first segment after a reset: the slope's change from the flat history to the shape's
320 *
321 * Every later correction is a change of the slope from the one before it, so the first must start the
322 * count: the shape's slope at the starting phase times the segment's speed, at the reset's instant.
323 * Without it a start on the short segment, or on its trough, leaves the next corner unpaired.
324 */
325 void start(const PhaseWalk::Segment& s, float rise, float fall, float width) {
326 starting_ = false;
327 const float speed = (s.end + static_cast<float>(s.wraps) - s.start) / s.part;
328 const bool rising = s.start >= rise && s.start < fall;
329 const float slope = rising ? 2.0f / width : -2.0f / (1.0f - width);
330 const float t = s.before + s.part; // the segment's start, from the frame's end
331 corrector_.corner(t < 1.0f ? t : math::POLYBLEP_T_MAX, slope * speed);
332 }
333
334 /**
335 * @brief Correct every image of a corner the segment crossed while the corner moved c0 -> c1
336 *
337 * The slope changes by sign K |speed| per frame, K = 2 / (w (1 - w)): +1 at the trough,
338 * -1 at the peak, whichever way the phase passed it. Width moves w0 -> w1 across the
339 * segment, and K takes the width at the crossing's own time.
340 */
341 void corner(const PhaseWalk::Segment& s, float c0, float c1, float w0, float w1, float sign) {
342 PhaseWalk::crossings(s, c0, c1, [&](float t, int, float speed) {
343 const float into = 1.0f - (t - s.before) / s.part; // of the segment, before the crossing
344 const float w = w0 + (w1 - w0) * into;
345 corrector_.corner(t, sign * std::fabs(speed) * 2.0f / (w * (1.0f - w)));
346 });
347 }
348
349 float width_target_ = 0.5f;
350 float width_ = 0.5f; /**< the width used last frame */
351 float anchor_target_ = 0.0f;
352 float anchor_ = 0.0f; /**< the anchor used last frame */
353 bool starting_ = true; /**< no frame since the reset: the next starts the slope's count */
354 PhaseWalk walk_{};
355 BlepCorrector<Kernel> corrector_{};
356};
357
358} // namespace sbl::dsp
359
360#endif // SBL_DSP_OSCILLATORS_PHASE_SAW_HPP_
The correction buffer behind a band-limited edge, over a BLEP kernel.
Clamping.
A band-limited slope shape driven by a signed phase, from a falling saw through a triangle to a risin...
float process(float phase, float step)
One frame with no offset: an offset carried before moves back to zero, as phase modulation.
static constexpr float MAX_STEP
float offset() const
The offset the core read last frame, in cycles.
float phase() const
The phase the core read last frame, the offset included.
static float shape(float phase, float rise, float fall, float width)
The naive shape at a phase.
float width() const
The width set for the next frame.
float anchor() const
The anchor set for the next frame.
static constexpr uint8_t LATENCY
static constexpr transport::Port PORTS[]
The ports, in the order the buffer call takes them, as PhasePulse's.
void process(float *out, uint16_t frames, Ports... ports)
A buffer of frames: phase and step per frame, then width, anchor and offset, which may be left off.
static constexpr float rise(float width, float anchor)
The trough, where the shape starts to rise, as PhasePulse::rise().
void set_width(float fraction_of_cycle)
Set the rising segment's share of the cycle. Takes effect next frame.
void set_anchor(float anchor)
Set where width acts. Takes effect next frame.
float process(float phase, float step, const float(&offsets)[SUBSTEPS])
One frame in SUBSTEPS equal parts, the offset given at the end of each, as PhasePulse's.
static constexpr float fall(float width, float anchor)
The peak, where the shape starts to fall, as PhasePulse::fall().
void reset(float phase=0.0f, float offset=0.0f)
Move to a phase plus an offset; width and anchor to their targets, corrections dropped.
static constexpr float WIDTH_FLOOR
float process(float phase, float step, float offset)
One frame: the corrected sample LATENCY frames back.
void reset(float phase=0.0f, float offset=0.0f)
Move to a phase plus an offset, the offset kept as the last part's.
static constexpr float MAX_STEP
void frame(float phase, float step, const float(&offsets)[SUBSTEPS], OnSegment &&on_segment)
One frame in SUBSTEPS equal parts, each given to on_segment as a Segment.
float phase() const
The phase the last part ended on, the offset included, in [0, 1).
static void crossings(const Segment &s, float c0, float c1, OnCrossing &&on_crossing)
Report every image of a threshold crossed by a segment while the threshold moved c0 -> c1.
float offset() const
The offset the last part ended on, in cycles.
Finiteness of a float, read from its bits, and a fallback for a value that is not finite.
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
A modulated phase walked frame by frame as segments, and the crossings of moving thresholds on them.
Polynomial BLEP kernels, and the sub-frame time of a crossing.
One part of a frame: the phase moving linearly from start to end plus wraps cycles.
The processing call's shape as a checked contract.