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
scheduler.hpp
Go to the documentation of this file.
1/**
2 * @file scheduler.hpp
3 * @brief The control context: one base period, divider slots,
4 * fixed stage order per run
5 */
6
7#ifndef SBL_CONTROL_SCHEDULER_HPP_
8#define SBL_CONTROL_SCHEDULER_HPP_
9
10#include <cstdint>
11
12namespace sbl::control {
13
14/** Intra-run order. Every due subscriber of a stage runs before any of the next. */
15enum class Stage : uint8_t {
16 Drain,
17 Update,
18 Merge,
19 Publish,
20};
21
22inline constexpr uint8_t STAGE_COUNT = 4; /**< number of Stage values */
23
24/** Subscriber callback: context pointer and clock ticks elapsed since its slot last ran. */
25using SubscriberFn = void (*)(void* context, uint32_t elapsed_ticks);
26
27/**
28 * @brief Divider slots over one base period, run in a fixed stage order
29 *
30 * The app drives run() once per base period - the 1 kHz timer ISR on
31 * hardware, the timer thread on the workbench - and passes the control
32 * clock's tick (control/clock.hpp). Each slot runs every Nth base period.
33 * Subscribers are told how many ticks elapsed since their slot last ran,
34 * read from the clock, so an irregular base period never skews time-constant
35 * math: components are told elapsed time and never assume a call rate.
36 *
37 * Every run goes through the stages in order, so the update order is
38 * enforced by construction:
39 *
40 * - Drain: event queues -> converters (MIDI parsed elsewhere arrives here).
41 * - Update: sources and components: advance(elapsed_ticks).
42 * - Merge: per-parameter merge policies resolve.
43 * - Publish: bridge writes, the only state the audio context reads.
44 *
45 * Within a stage, due subscribers run in subscription order. Apps subscribe;
46 * components never self-register. Static storage, no allocation.
47 *
48 * Timing. Told its base period in clock ticks (set_timing()), the scheduler
49 * counts per slot the runs that came late and the periods that passed with
50 * no run, and keeps the worst delay. Each slot is measured against a fixed
51 * grid on the clock, one due instant every period (its divider times the
52 * base period). The slot's first run after set_timing() anchors the grid. A
53 * run's delay is its time past the due instant, and the due instant then
54 * advances by whole periods, so a run that is on time does not move the
55 * grid. A run later than the tolerance is late, and each whole period in
56 * its delay is a skipped period. A run that comes early moves the grid
57 * earlier, to that run, and is not late: this is what corrects a grid that
58 * was anchored on a delayed run.
59 *
60 * The grid is fixed because, on a target whose tick is a hardware timer on
61 * the same oscillator as the clock, the two do not drift, so the grid gives
62 * a run's true delay behind its timer instant. Measured against the
63 * previous run instead, a delay that creeps up within the tolerance at each
64 * step would be under-read. A tick source that runs steadily slower than
65 * the clock is therefore counted: its delay grows until its runs are late,
66 * and a period is counted as skipped each time the delay reaches one.
67 *
68 * The counting never changes which slots run or what they are told.
69 *
70 * Usage:
71 * @code
72 * using Clock = sbl::control::TargetClock;
73 * enum : uint8_t { k1kHz, k200Hz, k60Hz };
74 * sbl::control::Scheduler<3> sched{{1, 5, 17}};
75 * sched.subscribe<MyWidget, &MyWidget::advance>(Stage::Update, k200Hz, widget);
76 * sched.subscribe(Stage::Drain, k1kHz, drain_midi, nullptr);
77 *
78 * sched.set_timing(Clock::ticks_from_us(1000), Clock::ticks_from_us(100));
79 *
80 * // once per base period (1 kHz timer ISR / timer thread)
81 * sched.run(Clock::now());
82 *
83 * // from the main loop
84 * sched.late_runs(k1kHz); sched.skipped_periods(k1kHz); sched.worst_delay_ticks(k1kHz);
85 * @endcode
86 *
87 * @context run() from exactly one context. subscribe() and set_timing() at
88 * init, before the first run(). The timing accessors read one word each and
89 * may be called from another context while run() counts.
90 *
91 * @tparam Slots Number of divider slots, at least 1
92 * @tparam Capacity Maximum subscribers across all slots, at least 1
93 */
94template<uint8_t Slots, uint8_t Capacity = 16>
95class Scheduler {
96 static_assert(Slots > 0, "Scheduler needs at least one slot");
97 static_assert(Capacity > 0, "Scheduler needs subscriber capacity");
98
99public:
100 /**
101 * @brief Construct with one divider per slot
102 * @param dividers Base periods between a slot's runs, per slot (0 is treated as 1)
103 */
104 explicit Scheduler(const uint16_t (&dividers)[Slots]) {
105 for (uint8_t s = 0; s < Slots; ++s) {
106 divider_[s] = dividers[s] ? dividers[s] : 1;
107 }
108 }
109
110 /**
111 * @brief Add a subscriber
112 * @param stage Stage it runs in
113 * @param slot Slot index, 0 to Slots - 1
114 * @param fn Callback
115 * @param context Passed to fn unchanged
116 * @return false if full, the slot is out of range, or fn is null
117 */
118 bool subscribe(Stage stage, uint8_t slot, SubscriberFn fn, void* context) {
119 if (count_ >= Capacity || slot >= Slots || fn == nullptr) {
120 return false;
121 }
122 subs_[count_++] = {fn, context, stage, slot};
123 return true;
124 }
125
126 /**
127 * @brief Give the base period, so late and skipped runs are counted
128 *
129 * @param base_period_ticks Clock ticks in one base period; 0 turns the counting off
130 * @param late_ticks A run is late when it comes more than this past its due instant;
131 * held below the base period
132 *
133 * Without this call nothing is counted. At init; after a later call each slot's next run anchors its grid again.
134 */
135 void set_timing(uint32_t base_period_ticks, uint32_t late_ticks) {
136 late_tolerance_ =
137 (base_period_ticks > 0 && late_ticks >= base_period_ticks) ? base_period_ticks - 1 : late_ticks;
138 for (uint8_t s = 0; s < Slots; ++s) {
139 period_[s] = base_period_ticks * divider_[s];
140 scheduled_[s] = false;
141 }
142 }
143
144 /**
145 * @brief Subscribe a member `void T::method(uint32_t elapsed_ticks)`
146 * @tparam T Object type
147 * @tparam Method Member function called with the elapsed ticks
148 * @param stage Stage it runs in
149 * @param slot Slot index, 0 to Slots - 1
150 * @param object Object the method is called on; it must outlive the scheduler
151 * @return false if full or the slot is out of range
152 */
153 template<typename T, void (T::*Method)(uint32_t)>
154 bool subscribe(Stage stage, uint8_t slot, T& object) {
155 return subscribe(
156 stage, slot, [](void* c, uint32_t elapsed) { (static_cast<T*>(c)->*Method)(elapsed); }, &object);
157 }
158
159 /**
160 * @brief One run, once per base period
161 *
162 * The first call establishes the baseline: every slot runs, told 0.
163 *
164 * @param now The control clock's tick (wrapping; unsigned deltas)
165 */
166 void run(uint32_t now) {
167 if (!started_) {
168 for (uint8_t s = 0; s < Slots; ++s) {
169 last_[s] = now;
170 }
171 started_ = true;
172 }
173
174 bool due[Slots] = {};
175 uint32_t elapsed[Slots] = {};
176 for (uint8_t s = 0; s < Slots; ++s) {
177 due[s] = (phase_[s] == 0);
178 elapsed[s] = 0;
179 if (due[s]) {
180 elapsed[s] = now - last_[s];
181 last_[s] = now;
182 if (period_[s] != 0) {
183 time_run(s, now);
184 }
185 }
186 if (++phase_[s] >= divider_[s]) {
187 phase_[s] = 0;
188 }
189 }
190
191 for (uint8_t st = 0; st < STAGE_COUNT; ++st) {
192 const Stage stage = static_cast<Stage>(st);
193 for (uint8_t i = 0; i < count_; ++i) {
194 const Subscriber& sub = subs_[i];
195 if (sub.stage == stage && due[sub.slot]) {
196 sub.fn(sub.context, elapsed[sub.slot]);
197 }
198 }
199 }
200 }
201
202 /**
203 * @brief Runs of the slot that came later than the tolerance past their due instant; wraps at 2^32
204 * @param slot Slot index
205 * @return The count, or 0 for a slot out of range
206 */
207 uint32_t late_runs(uint8_t slot) const { return slot < Slots ? late_[slot] : 0; }
208
209 /**
210 * @brief Periods of the slot that passed with no run; wraps at 2^32
211 * @param slot Slot index
212 * @return The count, or 0 for a slot out of range
213 */
214 uint32_t skipped_periods(uint8_t slot) const { return slot < Slots ? skipped_[slot] : 0; }
215
216 /**
217 * @brief The longest a run of the slot came past its due instant, since the start or reset_timing()
218 * @param slot Slot index
219 * @return The delay in clock ticks, or 0 for a slot out of range
220 */
221 uint32_t worst_delay_ticks(uint8_t slot) const { return slot < Slots ? worst_delay_[slot] : 0; }
222
223 /** Zero the counts and the worst delays. From run()'s context, or while it does not run. */
225 for (uint8_t s = 0; s < Slots; ++s) {
226 late_[s] = 0;
227 skipped_[s] = 0;
228 worst_delay_[s] = 0;
229 }
230 }
231
232 /** @brief Subscribers added */
233 uint8_t subscriber_count() const { return count_; }
234 /** @brief The slot's divider, or 0 for a slot out of range */
235 uint16_t divider(uint8_t slot) const { return slot < Slots ? divider_[slot] : 0; }
236 /** @brief Slots */
237 static constexpr uint8_t slots() { return Slots; }
238 /** @brief Maximum subscribers */
239 static constexpr uint8_t capacity() { return Capacity; }
240
241private:
242 struct Subscriber {
243 SubscriberFn fn = nullptr;
244 void* context = nullptr;
245 Stage stage = Stage::Update;
246 uint8_t slot = 0;
247 };
248
249 /** Count a due run of slot `s` at `now` against the slot's grid (see the class comment). */
250 void time_run(uint8_t s, uint32_t now) {
251 if (!scheduled_[s]) {
252 scheduled_[s] = true;
253 due_[s] = now + period_[s]; // the first run anchors the grid
254 return;
255 }
256 const int32_t delay = static_cast<int32_t>(now - due_[s]); // wrapping clock, signed distance
257 if (delay < 0) {
258 // Early: the grid was anchored on a run that was itself delayed. Move it earlier, to this run.
259 due_[s] = now + period_[s];
260 return;
261 }
262 // On the grid or behind it: the due instant advances by whole periods only, so the grid stays put.
263 const uint32_t behind = static_cast<uint32_t>(delay);
264 const uint32_t whole = behind >= period_[s] ? behind / period_[s] : 0;
265 due_[s] += (whole + 1) * period_[s];
266 if (behind > late_tolerance_) {
267 ++late_[s];
268 skipped_[s] += whole;
269 }
270 if (behind > worst_delay_[s]) {
271 worst_delay_[s] = behind;
272 }
273 }
274
275 Subscriber subs_[Capacity]{};
276 uint16_t divider_[Slots]{};
277 uint16_t phase_[Slots]{};
278 uint32_t last_[Slots]{};
279 uint32_t period_[Slots]{}; /**< the slot's period in clock ticks; 0 until set_timing() */
280 uint32_t due_[Slots]{}; /**< the grid's next due instant for the slot */
281 uint32_t late_[Slots]{};
282 uint32_t skipped_[Slots]{};
283 uint32_t worst_delay_[Slots]{};
284 uint32_t late_tolerance_ = 0;
285 bool scheduled_[Slots]{}; /**< due_ is set: the slot has run since set_timing() */
286 uint8_t count_ = 0;
287 bool started_ = false;
288};
289
290} // namespace sbl::control
291
292#endif // SBL_CONTROL_SCHEDULER_HPP_
Divider slots over one base period, run in a fixed stage order.
Definition scheduler.hpp:95
static constexpr uint8_t capacity()
Maximum subscribers.
static constexpr uint8_t slots()
Slots.
uint32_t worst_delay_ticks(uint8_t slot) const
The longest a run of the slot came past its due instant, since the start or reset_timing()
bool subscribe(Stage stage, uint8_t slot, T &object)
Subscribe a member void T::method(uint32_t elapsed_ticks)
bool subscribe(Stage stage, uint8_t slot, SubscriberFn fn, void *context)
Add a subscriber.
Scheduler(const uint16_t(&dividers)[Slots])
Construct with one divider per slot.
uint16_t divider(uint8_t slot) const
The slot's divider, or 0 for a slot out of range.
uint32_t late_runs(uint8_t slot) const
Runs of the slot that came later than the tolerance past their due instant; wraps at 2^32.
void set_timing(uint32_t base_period_ticks, uint32_t late_ticks)
Give the base period, so late and skipped runs are counted.
void run(uint32_t now)
One run, once per base period.
uint32_t skipped_periods(uint8_t slot) const
Periods of the slot that passed with no run; wraps at 2^32.
uint8_t subscriber_count() const
Subscribers added.
The control stack: scheduler, event queue, merge, CC mapping, calibration.
void(*)(void *context, uint32_t elapsed_ticks) SubscriberFn
Definition scheduler.hpp:25
constexpr uint8_t STAGE_COUNT
Definition scheduler.hpp:22