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_pulse.hpp
Go to the documentation of this file.
1/**
2 * @file phase_pulse.hpp
3 * @brief A band-limited pulse driven by a signed phase, its width placed by a bipolar anchor
4 */
5
6#ifndef SBL_DSP_OSCILLATORS_PHASE_PULSE_HPP_
7#define SBL_DSP_OSCILLATORS_PHASE_PULSE_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 pulse driven by a signed phase, its width placed by a bipolar anchor
22 *
23 * The pulse is high for w of the cycle, on [c - w/2, c + w/2) with its center
24 * at c = 1/2 + a (1 - w)/2, and low elsewhere. The anchor a, in [-1, 1], says
25 * which edges a change of width moves: at 0 the pulse is centered on phase
26 * 1/2 and both edges move; at +1 its fall sits at the wrap and only the rise
27 * moves, as in BlepOsc's pulse; at -1 its rise sits at the wrap and only the
28 * fall moves. A change
29 * dw in width moves the center by -a dw/2 of a cycle, and the fundamental's
30 * phase with it, so the anchor sets how far PWM moves the pitch. Both edges
31 * stay in [0, 1] at every width and anchor. Every edge is corrected at its
32 * sub-frame time through a BlepCorrector over the Kernel, so the output trails
33 * the naive waveform by LATENCY frames, as in BlepOsc.
34 *
35 * The core owns no phase accumulator. Each frame its driver gives it the
36 * phase, in [0, 1), and the signed step that led there in cycles; one
37 * accumulator can drive several cores, each reading it plus its own offset.
38 * The step is signed: the phase may run forward, backward and
39 * through zero. The core keeps the previous frame's phase, and the step says
40 * how many wraps lie between the two, round(previous + step - phase). The
41 * phases are the segment's endpoints, so the crossings always agree with the
42 * naive samples, whatever rounding the driver's accumulator did.
43 *
44 * Crossings are found on the unwrapped segment against each edge and its
45 * images one cycle up and down, in either direction and across the wrap, and
46 * every image crossed in the frame is corrected at its own time. The frame's
47 * segments and their crossings are a PhaseWalk. An edge at
48 * the wrap is corrected like any other, and width therefore needs no margin
49 * for the bookkeeping and reaches [0, 1] at every step: at 0 and at 1 the
50 * edges coincide and their corrections cancel. A change of width or anchor
51 * moves the edges across the next frame; nothing is ramped.
52 *
53 * Each frame may carry a phase offset, in cycles: the core
54 * reads the phase plus the offset, and its step is the given step plus the
55 * offset's change since the previous frame. A moving offset is phase
56 * modulation, and the edges it moves are corrected like any other motion; a
57 * constant offset is a time shift. Each core keeps its own previous offset,
58 * so cores reading one accumulator can each carry their own.
59 *
60 * A frame call can also report the edges it corrected, each at its time
61 * within the frame and with the level's change, and level() gives the naive
62 * level at the frame's end. Together they are the naive pulse as a level that
63 * steps at exact times, with none of the corrector's latency: what a
64 * modulator that listens to the pulse within the same frames needs.
65 *
66 * The core is below the signal transport. Its
67 * inputs are natural units, set by the driver that owns it.
68 *
69 * Inputs and their handling, per frame:
70 * - The step, the offset's change included, is clamped to [-MAX_STEP,
71 * MAX_STEP], one cycle per frame. With edge jumps of up to one cycle,
72 * a frame holds at most three crossings per edge. Past the clamp the frame's
73 * two phases stay exact and the segment between them loses whole cycles,
74 * whose crossings go uncorrected. Band-limiting degrades well before the
75 * clamp; a driver for pitch alone caps its step lower, as BlepOsc caps at
76 * fs/4.
77 * - Phase is linear within a frame: an edge is timed on the segment
78 * between the frame's two phases, so a pulse born and closed within one
79 * frame is not seen.
80 * - A phase outside [0, 1) is wrapped into it. A non-finite phase or step
81 * counts as no motion: the phase holds. A non-finite offset holds the
82 * previous one.
83 * - Width is clamped to [0, 1]; non-finite counts as 0.5.
84 * - The anchor is clamped to [-1, 1]; non-finite counts as 0.
85 *
86 * With Bspline4 or Linear2, kernels that never overshoot, output is in
87 * [-1, 1]. With Sinc16 a step overshoots by 8.2 % of its height, so the pulse
88 * reaches 1.16 (polyblep.hpp). A pulse of width w carries a mean of 2w - 1;
89 * the core removes no DC.
90 *
91 * Output does not depend on how the stream is split into calls: all state
92 * advances per frame.
93 *
94 * @tparam Kernel The BLEP kernel; math::Sinc16 by default
95 */
96template<class Kernel = math::Sinc16>
98public:
99 static constexpr float MAX_STEP = PhaseWalk::MAX_STEP; /**< cycles per frame, either direction */
100 static constexpr uint8_t LATENCY = Kernel::LATENCY; /**< frames the output trails the naive pulse */
101
102 /**
103 * @brief Set the pulse width. Takes effect next frame as moving edges.
104 *
105 * @param fraction_of_cycle Width as a fraction of the cycle, clamped to [0, 1]; non-finite counts as 0.5
106 * @context Same thread as process(); real-time safe.
107 */
108 void set_width(float fraction_of_cycle) {
109 width_target_ = sbl::math::clamp(sbl::math::finite_or(fraction_of_cycle, 0.5f), 0.0f, 1.0f);
110 }
111
112 /**
113 * @brief Set where width acts. Takes effect next frame as moving edges.
114 *
115 * @param anchor Clamped to [-1, 1]: -1 holds the rise at the wrap, 0 the center at 1/2, +1 the fall at the
116 * wrap; non-finite counts as 0
117 * @context Same thread as process(); real-time safe.
118 */
119 void set_anchor(float anchor) {
120 anchor_target_ = sbl::math::clamp(sbl::math::finite_or(anchor, 0.0f), -1.0f, 1.0f);
121 }
122
123 /**
124 * @brief One frame: the corrected sample LATENCY frames back
125 *
126 * @param phase The frame's phase, in [0, 1)
127 * @param step The signed step from the previous frame's phase, in cycles
128 * @param offset The frame's phase offset, in cycles; its change since the previous frame adds to the step
129 * @return The corrected sample LATENCY frames back
130 * @context Audio thread; real-time safe.
131 */
132 // cppcheck-suppress functionStatic ; cppcheck does not resolve the call to the offsets overload, which uses members
133 float process(float phase, float step, float offset) {
134 const float offsets[1] = {offset};
135 return process(phase, step, offsets);
136 }
137
138 /**
139 * @brief One frame in SUBSTEPS equal parts, the offset given at the end of each
140 *
141 * Through the frame the phase moves linearly by `step` to `phase`, plus the
142 * offset at the end of each part; `offsets[SUBSTEPS - 1]` is the frame's.
143 * Each part is a segment of its own, so an offset that curves within the
144 * frame is followed SUBSTEPS times more closely than by one segment. Width
145 * and anchor move linearly across the frame. One part is the one-segment
146 * call above.
147 *
148 * @tparam SUBSTEPS Parts per frame, at least 1
149 * @param phase The frame's phase, in [0, 1)
150 * @param step The signed step from the previous frame's phase, in cycles
151 * @param offsets The phase offset at the end of each part, in cycles
152 * @return The corrected sample LATENCY frames back
153 * @context Audio thread; real-time safe.
154 */
155 template<uint8_t SUBSTEPS>
156 float process(float phase, float step, const float (&offsets)[SUBSTEPS]) {
157 return process(phase, step, offsets, [](float, float) {});
158 }
159
160 /**
161 * @brief The frame call above, reporting each edge the phase crossed
162 *
163 * The edges are those the corrector is given, so over a frame their
164 * heights sum to the change in level(). Parts come in time order; within
165 * a part the rising edge's crossings come before the falling edge's,
166 * whatever their times.
167 *
168 * @tparam SUBSTEPS Parts per frame, at least 1
169 * @tparam OnEdge A callable taking `(float t, float height)`
170 * @param phase The frame's phase, in [0, 1)
171 * @param step The signed step from the previous frame's phase, in cycles
172 * @param offsets The phase offset at the end of each part, in cycles
173 * @param on_edge Called once per crossing as `on_edge(t, height)`: `t` the time from the crossing to the
174 * frame's end, in frames, in [0, 1]; `height` the naive level's change, +2 or -2
175 * @return The corrected sample LATENCY frames back
176 * @context Audio thread; real-time safe.
177 */
178 template<uint8_t SUBSTEPS, class OnEdge>
179 float process(float phase, float step, const float (&offsets)[SUBSTEPS], OnEdge&& on_edge) {
180 static_assert(SUBSTEPS > 0, "SBL ERROR: a frame has at least one part");
181 const float rise0 = rise(width_, anchor_);
182 const float fall0 = fall(width_, anchor_);
183 width_ = width_target_;
184 anchor_ = anchor_target_;
185 const float rise1 = rise(width_, anchor_);
186 const float fall1 = fall(width_, anchor_);
187 float rise_from = rise0;
188 float fall_from = fall0;
189 walk_.frame(phase, step, offsets, [&](const PhaseWalk::Segment& s) {
190 // The last part ends on the thresholds the naive level is read with.
191 const float rise_to = s.last ? rise1 : rise0 + (rise1 - rise0) * s.through;
192 const float fall_to = s.last ? fall1 : fall0 + (fall1 - fall0) * s.through;
193 edge(s, rise_from, rise_to, 2.0f, on_edge);
194 edge(s, fall_from, fall_to, -2.0f, on_edge);
195 rise_from = rise_to;
196 fall_from = fall_to;
197 });
198 level_ = naive(walk_.phase(), rise1, fall1);
199 return corrector_.process(level_);
200 }
201
202 /**
203 * @brief One frame with no offset: an offset carried before moves back to zero, as phase modulation.
204 *
205 * @param phase The frame's phase, in [0, 1)
206 * @param step The signed step from the previous frame's phase, in cycles
207 * @return The corrected sample LATENCY frames back
208 * @context Audio thread; real-time safe.
209 */
210 float process(float phase, float step) { return process(phase, step, 0.0f); }
211
212 /** @brief The ports, in the order the buffer call takes them; width and anchor set what their setters set. */
213 static constexpr transport::Port PORTS[] = {
216 {"width"},
217 {"anchor"},
218 {"offset"},
219 };
220
221 /**
222 * @brief A buffer of frames: phase and step per frame, then width, anchor and offset, which may be left off
223 *
224 * Width and anchor as blocks are set each frame; as scalars they are set
225 * once, before the block's first frame. Either way they take effect as
226 * moving edges, as their setters say. Left off, they hold. The offset, in
227 * cycles, is per frame as a block and constant as a scalar; left off, it
228 * is zero.
229 *
230 * @tparam Ports Blocks for phase and step, then a block or an arithmetic scalar for each of the rest
231 * @param[out] out Output buffer, `frames` long
232 * @param frames Frame count
233 * @param ports phase in [0, 1) and step in cycles per frame, then width, anchor and offset in cycles
234 * @context Audio thread; real-time safe.
235 */
236 template<class... Ports>
237 void process(float* out, uint16_t frames, Ports... ports) {
238 static_assert(transport::fits_v<PhasePulse, Ports...> && sizeof...(Ports) >= 2,
239 "SBL ERROR: PhasePulse takes phase and step (blocks), then width, anchor and offset "
240 "(blocks or scalars)");
241 const auto phase = transport::arg<0>(ports...);
242 const auto step = transport::arg<1>(ports...);
243 const auto width = transport::arg<2>(ports...);
244 const auto anchor = transport::arg<3>(ports...);
245 const auto offset = transport::arg<4>(ports...);
246 if constexpr (transport::is_scalar_v<decltype(width)>) {
247 set_width(static_cast<float>(width));
248 }
249 if constexpr (transport::is_scalar_v<decltype(anchor)>) {
250 set_anchor(static_cast<float>(anchor));
251 }
252 for (uint16_t i = 0; i < frames; ++i) {
253 if constexpr (transport::is_block_v<decltype(width)>) {
254 set_width(width[i]);
255 }
256 if constexpr (transport::is_block_v<decltype(anchor)>) {
257 set_anchor(anchor[i]);
258 }
259 if constexpr (transport::is_block_v<decltype(offset)>) {
260 out[i] = process(phase[i], step[i], offset[i]);
261 } else if constexpr (transport::is_scalar_v<decltype(offset)>) {
262 out[i] = process(phase[i], step[i], static_cast<float>(offset));
263 } else {
264 out[i] = process(phase[i], step[i]);
265 }
266 }
267 }
268
269 /**
270 * @brief Move to a phase plus an offset; width and anchor to their targets, corrections dropped.
271 *
272 * @param phase Phase in cycles; a non-finite phase counts as 0
273 * @param offset Offset in cycles, kept as the last frame's; a non-finite offset counts as 0
274 */
275 void reset(float phase = 0.0f, float offset = 0.0f) {
276 walk_.reset(phase, offset);
277 width_ = width_target_;
278 anchor_ = anchor_target_;
279 corrector_.reset();
280 level_ = naive(walk_.phase(), rise(width_, anchor_), fall(width_, anchor_));
281 }
282
283 /** @brief The phase the core read last frame, the offset included. */
284 float phase() const { return walk_.phase(); }
285
286 /** @brief The naive level at the end of the last frame, +1 or -1: the pulse before its corrections, with no latency. */
287 float level() const { return level_; }
288 /** @brief The offset the core read last frame, in cycles. */
289 float offset() const { return walk_.offset(); }
290 /** @brief The width set for the next frame. */
291 float width() const { return width_target_; }
292 /** @brief The anchor set for the next frame. */
293 float anchor() const { return anchor_target_; }
294
295 /**
296 * @brief The phase where the pulse rises.
297 *
298 * @param width Width, in [0, 1]
299 * @param anchor Anchor, in [-1, 1]
300 * @return (1 - w)(1 + a)/2, in [0, 1]
301 */
302 static constexpr float rise(float width, float anchor) { return 0.5f * (1.0f - width) * (1.0f + anchor); }
303
304 /**
305 * @brief The phase where the pulse falls.
306 *
307 * @param width Width, in [0, 1]
308 * @param anchor Anchor, in [-1, 1]
309 * @return 1 - (1 - w)(1 - a)/2, in [0, 1]
310 */
311 static constexpr float fall(float width, float anchor) { return 1.0f - 0.5f * (1.0f - width) * (1.0f - anchor); }
312
313 /**
314 * @brief Advance a phase by a signed step and wrap it into [0, 1)
315 *
316 * For a driver's accumulator. A small negative step from just above zero
317 * would round to 1.0f on adding a cycle; the result is kept below 1.
318 *
319 * @param phase Phase, in cycles
320 * @param step Signed step, in cycles
321 * @return The wrapped phase, in [0, 1)
322 */
323 static float advance(float phase, float step) { return PhaseWalk::wrap(phase + step); }
324
325private:
326 /**
327 * @brief Correct every image of an edge the segment crossed while the edge moved c0 -> c1
328 *
329 * The level steps by `height` each time the phase passes an image of the edge upward,
330 * relative to the edge's motion, and by -height downward.
331 */
332 template<class OnEdge>
333 void edge(const PhaseWalk::Segment& s, float c0, float c1, float height, OnEdge& on_edge) {
334 PhaseWalk::crossings(s, c0, c1, [&](float t, int direction, float) {
335 const float change = direction > 0 ? height : -height;
336 corrector_.step(t, change);
337 on_edge(t, change);
338 });
339 }
340
341 static float naive(float phase, float rise, float fall) { return phase >= rise && phase < fall ? 1.0f : -1.0f; }
342
343 float width_target_ = 0.5f;
344 float width_ = 0.5f; /**< the width used last frame */
345 float anchor_target_ = 0.0f;
346 float anchor_ = 0.0f; /**< the anchor used last frame */
347 float level_ = -1.0f; /**< the naive level at the end of the last frame */
348 PhaseWalk walk_{};
349 BlepCorrector<Kernel> corrector_{};
350};
351
352} // namespace sbl::dsp
353
354#endif // SBL_DSP_OSCILLATORS_PHASE_PULSE_HPP_
The correction buffer behind a band-limited edge, over a BLEP kernel.
Clamping.
A band-limited pulse driven by a signed phase, its width placed by a bipolar anchor.
float process(float phase, float step, float offset)
One frame: the corrected sample LATENCY frames back.
float process(float phase, float step, const float(&offsets)[SUBSTEPS])
One frame in SUBSTEPS equal parts, the offset given at the end of each.
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.
float process(float phase, float step, const float(&offsets)[SUBSTEPS], OnEdge &&on_edge)
The frame call above, reporting each edge the phase crossed.
float width() const
The width set for the next frame.
float anchor() const
The anchor set for the next frame.
float process(float phase, float step)
One frame with no offset: an offset carried before moves back to zero, as phase modulation.
static float advance(float phase, float step)
Advance a phase by a signed step and wrap it into [0, 1)
static constexpr float rise(float width, float anchor)
The phase where the pulse rises.
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 MAX_STEP
float phase() const
The phase the core read last frame, the offset included.
void set_anchor(float anchor)
Set where width acts. Takes effect next frame as moving edges.
float offset() const
The offset the core read last frame, in cycles.
float level() const
The naive level at the end of the last frame, +1 or -1: the pulse before its corrections,...
void set_width(float fraction_of_cycle)
Set the pulse width. Takes effect next frame as moving edges.
static constexpr uint8_t LATENCY
static constexpr transport::Port PORTS[]
The ports, in the order the buffer call takes them; width and anchor set what their setters set.
static constexpr float fall(float width, float anchor)
The phase where the pulse falls.
static float wrap(float x)
Wrap into [0, 1); a value that rounds up to 1 is 0.
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.