lib8tion 0.1.1

Rust port of FastLED lib8tion — fast 8-bit math primitives for embedded LED programming
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Beat generators — phase/value oscillators driven by a millisecond clock,
//! the building block FastLED animations use to "pulse" or "wave" values at a
//! given tempo (BPM).
//!
//! Direct port of the `beat8`/`beat16`/`beat88`/`beatsin8`/`beatsin16`/
//! `beatsin88` family in FastLED's `lib8tion.h`. The original reads the
//! current time from a global `millis()`; this port instead takes the
//! timestamp as an explicit `now_millis` argument — the same "no hidden
//! global state" shape as [`Rng16`](crate::Rng16), and the only sensible one
//! in `no_std` (there is no universal monotonic clock to reach for). Drive it
//! with whatever millisecond counter your platform provides (a `SysTick`,
//! an RTC, a simulation clock, ...).

use crate::scale8::{scale8, scale16};
use crate::trig8::{sin8, sin16};
use crate::{Accum88, Fract8, Fract16};

/// Generates a 16-bit "beat" ramp from a Q8.8 fixed-point BPM value.
///
/// `bpm88` is beats-per-minute in [`Accum88`] (`Q8.8`) format (high byte =
/// whole BPM, low byte = fractional BPM in 1/256ths — e.g. `Accum88(120 << 8)`
/// for "120.0 BPM", or `Accum88((120 << 8) | 128)` for "120.5 BPM").
/// `timebase` shifts the phase — the ramp restarts when `now_millis ==
/// timebase`. Returns a value that ramps from `0` to `65535` and wraps,
/// completing one cycle per beat.
#[inline]
pub const fn beat88(bpm88: Accum88, timebase: u32, now_millis: u32) -> u16 {
    // 65536 ticks-per-beat-cycle : 60000 ms-per-minute reduces to ~280:256;
    // rounding to 280 keeps this a cheap multiply-and-shift (see FastLED's
    // comment in lib8tion.h) at the cost of beats running ~0.07% fast.
    let elapsed = now_millis.wrapping_sub(timebase);
    let scaled = elapsed.wrapping_mul(bpm88.0 as u32).wrapping_mul(280);
    (scaled >> 16) as u16
}

/// Generates a 16-bit "beat" ramp from a plain BPM value.
///
/// `bpm` may be a whole-number BPM (`< 256`, promoted to `Q8.8` by shifting
/// into the high byte) or an already-`Q8.8` value (`>= 256`) — see [`beat88`].
#[inline]
pub const fn beat16(bpm: u16, timebase: u32, now_millis: u32) -> u16 {
    let bpm88 = if bpm < 256 { bpm << 8 } else { bpm };
    beat88(Accum88(bpm88), timebase, now_millis)
}

/// Generates an 8-bit "beat" ramp from a plain BPM value — see [`beat16`],
/// truncated to its high byte.
#[inline]
pub const fn beat8(bpm: u16, timebase: u32, now_millis: u32) -> u8 {
    (beat16(bpm, timebase, now_millis) >> 8) as u8
}

/// Generates a 16-bit sine wave oscillating at `bpm88` (a [`beat88`]-format
/// BPM), scaled to swing between `lowest` and `highest`.
///
/// `phase_offset` shifts the wave's phase (added to the beat ramp before
/// taking its sine — wraps at `65536`). Pass `lowest = 0, highest = 65535`
/// for the full output range.
#[inline]
pub const fn beatsin88(
    bpm88: Accum88,
    lowest: u16,
    highest: u16,
    timebase: u32,
    phase_offset: u16,
    now_millis: u32,
) -> u16 {
    let beat = beat88(bpm88, timebase, now_millis);
    let beatsin = (sin16(beat.wrapping_add(phase_offset)) as i32 + 32768) as u16;
    let rangewidth = highest.wrapping_sub(lowest);
    let scaledbeat = scale16(beatsin, Fract16(rangewidth));
    lowest.wrapping_add(scaledbeat)
}

/// Generates a 16-bit sine wave oscillating at `bpm` (a [`beat16`]-format
/// BPM), scaled to swing between `lowest` and `highest` — see [`beatsin88`].
#[inline]
pub const fn beatsin16(
    bpm: u16,
    lowest: u16,
    highest: u16,
    timebase: u32,
    phase_offset: u16,
    now_millis: u32,
) -> u16 {
    let beat = beat16(bpm, timebase, now_millis);
    let beatsin = (sin16(beat.wrapping_add(phase_offset)) as i32 + 32768) as u16;
    let rangewidth = highest.wrapping_sub(lowest);
    let scaledbeat = scale16(beatsin, Fract16(rangewidth));
    lowest.wrapping_add(scaledbeat)
}

/// Generates an 8-bit sine wave oscillating at `bpm` (a [`beat8`]-format
/// BPM), scaled to swing between `lowest` and `highest`.
///
/// `phase_offset` shifts the wave's phase (added to the beat ramp before
/// taking its sine — wraps at `256`). Pass `lowest = 0, highest = 255` for
/// the full output range.
#[inline]
pub const fn beatsin8(
    bpm: u16,
    lowest: u8,
    highest: u8,
    timebase: u32,
    phase_offset: u8,
    now_millis: u32,
) -> u8 {
    let beat = beat8(bpm, timebase, now_millis);
    let beatsin = sin8(beat.wrapping_add(phase_offset));
    let rangewidth = highest.wrapping_sub(lowest);
    let scaledbeat = scale8(beatsin, Fract8(rangewidth));
    lowest.wrapping_add(scaledbeat)
}

/// Builder for [`beatsin8`] — lets a sine-wave oscillator's tempo, output
/// range, timebase and phase offset be configured once and then sampled
/// repeatedly via [`at`](Self::at), instead of threading all five parameters
/// through every call site.
///
/// ```
/// use lib8tion::BeatSin8;
///
/// let wave = BeatSin8::new(120).range(10, 200).phase_offset(64);
/// let v = wave.at(1234);
/// assert!((10..=200).contains(&v));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BeatSin8 {
    bpm: u16,
    lowest: u8,
    highest: u8,
    timebase: u32,
    phase_offset: u8,
}

impl BeatSin8 {
    /// Starts building an oscillator at `bpm` (see [`beat8`]), with the full
    /// `0..=255` output range, zero timebase and zero phase offset.
    #[inline]
    pub const fn new(bpm: u16) -> Self {
        Self {
            bpm,
            lowest: 0,
            highest: 255,
            timebase: 0,
            phase_offset: 0,
        }
    }

    /// Sets the output range the wave swings between (inclusive).
    #[inline]
    pub const fn range(mut self, lowest: u8, highest: u8) -> Self {
        self.lowest = lowest;
        self.highest = highest;
        self
    }

    /// Sets the phase timebase — the wave restarts when `now_millis ==
    /// timebase`.
    #[inline]
    pub const fn timebase(mut self, timebase: u32) -> Self {
        self.timebase = timebase;
        self
    }

    /// Sets the phase offset added to the beat ramp before taking its sine.
    #[inline]
    pub const fn phase_offset(mut self, phase_offset: u8) -> Self {
        self.phase_offset = phase_offset;
        self
    }

    /// Samples the wave at `now_millis` — see [`beatsin8`].
    #[inline]
    pub const fn at(&self, now_millis: u32) -> u8 {
        beatsin8(
            self.bpm,
            self.lowest,
            self.highest,
            self.timebase,
            self.phase_offset,
            now_millis,
        )
    }
}

/// Builder for [`beatsin16`] — see [`BeatSin8`] for the rationale; same shape,
/// 16-bit output range and phase offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BeatSin16 {
    bpm: u16,
    lowest: u16,
    highest: u16,
    timebase: u32,
    phase_offset: u16,
}

impl BeatSin16 {
    /// Starts building an oscillator at `bpm` (see [`beat16`]), with the full
    /// `0..=65535` output range, zero timebase and zero phase offset.
    #[inline]
    pub const fn new(bpm: u16) -> Self {
        Self {
            bpm,
            lowest: 0,
            highest: 65535,
            timebase: 0,
            phase_offset: 0,
        }
    }

    /// Sets the output range the wave swings between (inclusive).
    #[inline]
    pub const fn range(mut self, lowest: u16, highest: u16) -> Self {
        self.lowest = lowest;
        self.highest = highest;
        self
    }

    /// Sets the phase timebase — the wave restarts when `now_millis ==
    /// timebase`.
    #[inline]
    pub const fn timebase(mut self, timebase: u32) -> Self {
        self.timebase = timebase;
        self
    }

    /// Sets the phase offset added to the beat ramp before taking its sine.
    #[inline]
    pub const fn phase_offset(mut self, phase_offset: u16) -> Self {
        self.phase_offset = phase_offset;
        self
    }

    /// Samples the wave at `now_millis` — see [`beatsin16`].
    #[inline]
    pub const fn at(&self, now_millis: u32) -> u16 {
        beatsin16(
            self.bpm,
            self.lowest,
            self.highest,
            self.timebase,
            self.phase_offset,
            now_millis,
        )
    }
}

/// Builder for [`beatsin88`] — see [`BeatSin8`] for the rationale; takes its
/// tempo as an [`Accum88`] (`Q8.8` BPM) for fractional-BPM precision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BeatSin88 {
    bpm88: Accum88,
    lowest: u16,
    highest: u16,
    timebase: u32,
    phase_offset: u16,
}

impl BeatSin88 {
    /// Starts building an oscillator at `bpm88` (see [`beat88`]), with the
    /// full `0..=65535` output range, zero timebase and zero phase offset.
    #[inline]
    pub const fn new(bpm88: Accum88) -> Self {
        Self {
            bpm88,
            lowest: 0,
            highest: 65535,
            timebase: 0,
            phase_offset: 0,
        }
    }

    /// Sets the output range the wave swings between (inclusive).
    #[inline]
    pub const fn range(mut self, lowest: u16, highest: u16) -> Self {
        self.lowest = lowest;
        self.highest = highest;
        self
    }

    /// Sets the phase timebase — the wave restarts when `now_millis ==
    /// timebase`.
    #[inline]
    pub const fn timebase(mut self, timebase: u32) -> Self {
        self.timebase = timebase;
        self
    }

    /// Sets the phase offset added to the beat ramp before taking its sine.
    #[inline]
    pub const fn phase_offset(mut self, phase_offset: u16) -> Self {
        self.phase_offset = phase_offset;
        self
    }

    /// Samples the wave at `now_millis` — see [`beatsin88`].
    #[inline]
    pub const fn at(&self, now_millis: u32) -> u16 {
        beatsin88(
            self.bpm88,
            self.lowest,
            self.highest,
            self.timebase,
            self.phase_offset,
            now_millis,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn beat88_ramps_and_wraps_with_time() {
        assert_eq!(beat88(Accum88(120 << 8), 0, 0), 0);
        // 250 * (120<<8) * 280 == 2_150_400_000; >> 16 == 32812 (a beat at
        // 120 BPM lasts 60000/120 = 500ms, so this is ~halfway through it).
        assert_eq!(beat88(Accum88(120 << 8), 0, 250), 32812);
        // 500 * (120<<8) * 280 == 4_300_800_000, which overflows u32 and
        // wraps to 5_832_704 before the shift — exactly like the original
        // C, which computes this chain in 32-bit and relies on the wrap.
        assert_eq!(beat88(Accum88(120 << 8), 0, 500), 89);
    }

    #[test]
    fn beat16_promotes_plain_bpm_to_q88() {
        assert_eq!(beat16(120, 0, 250), beat16(120 << 8, 0, 250));
        assert_eq!(beat16(120, 0, 250), beat88(Accum88(120 << 8), 0, 250));
    }

    #[test]
    fn beat8_is_high_byte_of_beat16() {
        for ms in (0..=2000u32).step_by(37) {
            assert_eq!(beat8(120, 0, ms), (beat16(120, 0, ms) >> 8) as u8);
        }
    }

    #[test]
    fn timebase_shifts_phase() {
        // Shifting the timebase forward by `d` is the same as looking `d`
        // milliseconds further into the future from timebase zero.
        assert_eq!(
            beat88(Accum88(120 << 8), 1000, 1500),
            beat88(Accum88(120 << 8), 0, 500)
        );
    }

    #[test]
    fn beatsin_outputs_stay_within_their_range() {
        for ms in (0..=10_000u32).step_by(73) {
            let v8 = beatsin8(120, 10, 200, 0, 0, ms);
            assert!((10..=200).contains(&v8), "beatsin8 out of range: {v8}");

            let v16 = beatsin16(120, 1000, 60000, 0, 0, ms);
            assert!(
                (1000..=60000).contains(&v16),
                "beatsin16 out of range: {v16}"
            );

            let v88 = beatsin88(Accum88(120 << 8), 1000, 60000, 0, 0, ms);
            assert!(
                (1000..=60000).contains(&v88),
                "beatsin88 out of range: {v88}"
            );
        }
    }

    #[test]
    fn beatsin_full_range_hits_both_ends() {
        let mut min8 = u8::MAX;
        let mut max8 = 0u8;
        for ms in (0..=2000u32).step_by(5) {
            let v = beatsin8(120, 0, 255, 0, 0, ms);
            min8 = min8.min(v);
            max8 = max8.max(v);
        }
        assert!(min8 < 10, "min8={min8}");
        assert!(max8 > 245, "max8={max8}");
    }

    #[test]
    fn phase_offset_shifts_the_wave() {
        let ms = 1234;
        let unshifted = beatsin8(120, 0, 255, 0, 0, ms);
        let shifted = beatsin8(120, 0, 255, 0, 128, ms);
        // A half-cycle phase offset should land on (roughly) the opposite
        // side of the wave.
        assert_ne!(unshifted, shifted);
    }

    #[test]
    fn builders_match_their_function_counterparts() {
        for ms in (0..=2000u32).step_by(37) {
            assert_eq!(
                BeatSin8::new(120)
                    .range(10, 200)
                    .timebase(50)
                    .phase_offset(64)
                    .at(ms),
                beatsin8(120, 10, 200, 50, 64, ms)
            );
            assert_eq!(
                BeatSin16::new(120)
                    .range(1000, 60000)
                    .timebase(50)
                    .phase_offset(1234)
                    .at(ms),
                beatsin16(120, 1000, 60000, 50, 1234, ms)
            );
            assert_eq!(
                BeatSin88::new(Accum88(120 << 8))
                    .range(1000, 60000)
                    .timebase(50)
                    .phase_offset(1234)
                    .at(ms),
                beatsin88(Accum88(120 << 8), 1000, 60000, 50, 1234, ms)
            );
        }
    }

    #[test]
    fn builder_defaults_cover_the_full_output_range() {
        assert_eq!(BeatSin8::new(120).at(0), beatsin8(120, 0, 255, 0, 0, 0));
        assert_eq!(BeatSin16::new(120).at(0), beatsin16(120, 0, 65535, 0, 0, 0));
        assert_eq!(
            BeatSin88::new(Accum88(120 << 8)).at(0),
            beatsin88(Accum88(120 << 8), 0, 65535, 0, 0, 0)
        );
    }
}