hub75_framebuffer/lib.rs
1//! Framebuffer implementation for HUB75 LED matrix displays.
2//!
3//! ## How HUB75 LED Displays Work
4//!
5//! HUB75 RGB LED matrix panels are scanned, time-multiplexed displays that behave like a long
6//! daisy-chained shift register rather than a random-access framebuffer.
7//!
8//! ### Signal names
9//! - **R1 G1 B1 / R2 G2 B2** – Serial colour data for the upper and lower halves of the active scan line
10//! - **CLK** – Shift-register clock; every rising edge pushes the six colour bits one pixel to the right
11//! - **LAT / STB** – Latch; copies the shift-register contents to the LED drivers for the row currently selected by the address lines
12//! - **OE** – Output-Enable (active LOW): LEDs are lit while OE is LOW and blanked when it is HIGH
13//! - **A B C D (E)** – Row-address select lines (choose which pair of rows is lit)
14//! - **VCC & GND** – 5 V power for panel logic and LED drivers
15//!
16//! ### Row-pair scanning workflow (e.g., 1/16-scan panel)
17//! 1. While the panel is still displaying row pair N − 1, the controller shifts the six-bit colour data for row pair N into the chain (OE remains LOW so row N − 1 stays visible).
18//! 2. After the last pixel is clocked in, the controller raises OE HIGH to blank the LEDs.
19//! 3. With the panel blanked, it first changes the address lines to select row pair N, lets them settle for a few nanoseconds, and **then** pulses LAT to latch the freshly shifted data into the output drivers for that newly selected row.
20//! 4. OE is immediately driven LOW again, lighting row pair N.
21//! 5. Steps 1–4 repeat for every row pair fast enough (hundreds of Hz) that the human eye sees a steady image.
22//! - If the first row pair is being shifted, the panel continues showing the last row pair of the previous frame until the first blank-address-latch sequence occurs.
23//!
24//! ### Brightness and colour depth (Binary Code Modulation)
25//! - Full colour is typically achieved using **Binary Code Modulation (BCM)**, also known as *Bit-Angle Modulation (BAM)*. Each bit-plane is displayed for a period proportional to its binary weight (1, 2, 4, 8 …), yielding 2ⁿ intensity levels per channel. See [Batsocks – LED dimming using Binary Code Modulation](https://www.batsocks.co.uk/readme/art_bcm_1.htm) for a deeper explanation.
26//! - Because each LED is on for only a fraction of the total frame time, the driver can use relatively high peak currents without overheating while average brightness is preserved.
27//!
28//! ### Implications for software / hardware drivers
29//! - You don't simply "write a pixel" once; you must continuously stream the complete refresh data at MHz-range clock rates.
30//! - Precise timing of CLK, OE, address lines, and LAT is critical—especially the order: blank (OE HIGH) → set address → latch → un-blank (OE LOW).
31//! - Microcontrollers typically employ DMA, PIO, or parallel GPIO tricks, and FPGAs use dedicated logic, to sustain the data throughput while leaving processing resources free.
32//!
33//! In short: a HUB75 panel is a high-speed shift-register chain that relies on rapid row-pair scanning and **Binary Code Modulation (BCM)** to create a bright, full-colour image. Keeping OE LOW almost all the time—blanking only long enough to change the address and pulse LAT—maximises brightness without visible artefacts.
34//!
35//! ## Framebuffer Implementations
36//!
37//! Four framebuffer layouts are provided, covering two hardware variants and
38//! two BCM strategies:
39//!
40//! | Module | Word size | External latch? | BCM strategy |
41//! |--------|-----------|-----------------|--------------|
42//! | [`plain`] | 16-bit | No | Threshold frames |
43//! | [`latched`] | 8-bit | Yes | Threshold frames |
44//! | [`bitplane::plain`] | 16-bit | No | True bitplane |
45//! | [`bitplane::latched`] | 8-bit | Yes | True bitplane |
46//!
47//! ### Plain vs. Latched
48//! - **Plain** packs all HUB75 signals (address, latch, OE, colour) into each
49//! 16-bit word. No extra hardware beyond a parallel output peripheral.
50//! - **Latched** uses 8-bit words with a separate external latch circuit to
51//! hold the row address and gate the pixel clock, halving per-entry memory.
52//!
53//! ### Threshold Frames vs. True Bitplane
54//! The two BCM strategies differ in how they store colour data and how the DMA
55//! chain must be configured to render it.
56//!
57//! **Threshold frames** (`plain`, `latched`) -- the driver compares each
58//! channel's 8-bit value against per-frame thresholds and stores the resulting
59//! on/off bits. For a colour depth of `BITS`, this produces
60//! `2^BITS - 1` frames. Frame *n* is displayed for a duration proportional to
61//! `2^n`. Memory grows exponentially with colour depth.
62//!
63//! **True bitplane** (`bitplane::plain`, `bitplane::latched`) -- each of
64//! `PLANES` planes (typically 8) stores one bit of every colour channel
65//! directly. To render, configure the DMA descriptor chain so that each
66//! plane's data is output `2^(7 - plane_index)` times (plane 0 = MSB is
67//! scanned 128 times, plane 7 = LSB is scanned once). Memory scales linearly
68//! with the number of planes.
69//!
70//! All four variants have configurable row and column dimensions, support
71//! `embedded-graphics` via the `DrawTarget` trait, and expose per-plane
72//! pointers for DMA setup through the [`FrameBuffer`] trait.
73//!
74//! ## Multiple Panels
75//! Use [`tiling::TiledFrameBuffer`] to drive several HUB75 panels as one large
76//! virtual display. Combine it with a pixel-remapping policy such as
77//! [`tiling::ChainTopRightDown`] and any of the framebuffer flavours above.
78//! The wrapper exposes a single `embedded-graphics` canvas, so for example a
79//! 3 × 3 stack of 64 × 32 panels simply looks like a 192 × 96 screen while
80//! all coordinate translation happens transparently.
81//!
82//! ## Available Feature Flags
83//!
84//! ### `skip-black-pixels` Feature (disabled by default)
85//! When enabled, calls to `set_pixel()` with `Color::BLACK` return early without
86//! writing to the framebuffer. This provides a significant performance boost for
87//! UI applications that frequently draw black pixels (backgrounds, clearing, etc.)
88//! by assuming the framebuffer was already cleared.
89//!
90//! **Important**: This optimization assumes that black pixels represent "no change"
91//! rather than "explicitly set to black". By default, black pixels are written
92//! normally to ensure correct overwrite behavior. To enable the optimization:
93//!
94//! ```toml
95//! [dependencies]
96//! hub75-framebuffer = { version = "0.9.0", features = ["skip-black-pixels"] }
97//! ```
98//!
99//! ### `esp32-ordering` Feature (required for original ESP32 only)
100//! **Required** when targeting the original ESP32 chip (not ESP32-S3 or other variants).
101//! This feature adjusts byte ordering to accommodate the quirky requirements of the
102//! ESP32's I²S peripheral in 8-bit and 16-bit modes. The original ESP32 has different
103//! byte ordering requirements compared to other ESP32 variants (S2, S3, C3, etc.),
104//! which do **not** need this feature.
105//!
106//! ```toml
107//! [dependencies]
108//! hub75-framebuffer = { version = "0.9.0", features = ["esp32-ordering"] }
109//! ```
110//!
111//! ### `tail-closes-latch` Feature (plain framebuffers only)
112//! Appends a single extra "tail" word at the end of the DMA buffer that drives the
113//! LATCH signal LOW (de-asserted) on the final clock edge. Without this feature the
114//! last word in each row asserts LATCH HIGH to latch shifted data into the LED
115//! drivers, and the GPIO pins remain in that state after the DMA transfer completes.
116//! Some hardware configurations (e.g. free-running DMA loops or peripherals that
117//! continue clocking after the descriptor chain ends) can re-latch stale data or
118//! glitch if LATCH is left asserted.
119//!
120//! Enabling `tail-closes-latch` adds one 16-bit `Entry` (for `plain`) or one entry
121//! per bit-plane (for `bitplane::plain`) that parks the bus with LATCH=0 and
122//! OE=BLANK, cleanly terminating the transfer. The cost is a single extra word per
123//! DMA chunk, which is negligible compared to the frame data.
124//!
125//! ```toml
126//! [dependencies]
127//! hub75-framebuffer = { version = "0.9.0", features = ["tail-closes-latch"] }
128//! ```
129//!
130//! ### `defmt` Feature
131//! Implements `defmt::Format` for framebuffer types so they can be emitted with
132//! the `defmt` logging framework. No functional changes; purely adds a trait impl.
133//!
134//! ### `doc-images` Feature
135//! Embeds documentation images when building docs on docs.rs. Not needed for
136//! normal usage.
137#![no_std]
138#![warn(missing_docs)]
139#![warn(clippy::all)]
140#![warn(clippy::pedantic)]
141#![allow(clippy::cast_possible_truncation)]
142#![allow(clippy::cast_sign_loss)]
143
144use embedded_graphics::draw_target::DrawTarget;
145use embedded_graphics::pixelcolor::Rgb888;
146use embedded_graphics::prelude::Point;
147
148pub mod bitplane;
149pub mod latched;
150pub mod plain;
151pub mod tiling;
152
153/// Color type used in the framebuffer
154pub type Color = Rgb888;
155
156/// Word size configuration for the framebuffer
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum WordSize {
159 /// 8-bit word size
160 Eight,
161 /// 16-bit word size
162 Sixteen,
163}
164
165/// Computes the NROWS value from ROWS for `DmaFrameBuffer`
166///
167/// # Arguments
168///
169/// * `rows` - Total number of rows in the display
170///
171/// # Returns
172///
173/// Number of rows needed internally for `DmaFrameBuffer`
174#[must_use]
175pub const fn compute_rows(rows: usize) -> usize {
176 rows / 2
177}
178
179/// Computes the number of frames needed for a given bit depth
180///
181/// This is used to determine how many frames are needed to achieve
182/// the desired color depth through Binary Code Modulation (BCM).
183///
184/// # Arguments
185///
186/// * `bits` - Number of bits per color channel
187///
188/// # Returns
189///
190/// Number of frames required for the given bit depth
191#[must_use]
192pub const fn compute_frame_count(bits: u8) -> usize {
193 (1usize << bits) - 1
194}
195
196/// Trait for read-only framebuffers.
197pub trait FrameBuffer {
198 /// The word type used by this framebuffer.
199 type Word;
200
201 /// Returns the word size configuration for this framebuffer
202 fn get_word_size(&self) -> WordSize {
203 match size_of::<Self::Word>() {
204 1 => WordSize::Eight,
205 2 => WordSize::Sixteen,
206 _ => panic!("Unsupported word size"),
207 }
208 }
209
210 /// Returns the number of BCM bit-planes in this framebuffer.
211 ///
212 /// Contiguous (threshold-based) framebuffers return `1` — the entire
213 /// buffer is treated as a single plane. True bit-plane framebuffers
214 /// return the number of planes (typically equal to the colour depth in
215 /// bits).
216 fn plane_count(&self) -> usize;
217
218 /// Returns a raw pointer and byte length for the given plane.
219 ///
220 /// For a single-plane framebuffer (`plane_count() == 1`), `plane_idx`
221 /// must be `0` and the returned span covers the whole DMA-ready buffer.
222 ///
223 /// # Panics
224 ///
225 /// May panic if `plane_idx >= plane_count()`.
226 fn plane_ptr_len(&self, plane_idx: usize) -> (*const u8, usize);
227}
228
229/// Trait for mutable framebuffers
230///
231/// This trait extends `FrameBuffer` with the ability to draw to the framebuffer
232/// using the `embedded_graphics` drawing primitives.
233pub trait MutableFrameBuffer:
234 FrameBuffer + DrawTarget<Color = Color, Error = core::convert::Infallible>
235{
236}
237
238/// Trait for all operations a user may want to call on a framebuffer.
239pub trait FrameBufferOperations: FrameBuffer {
240 /// Erase pixel colors while preserving control bits.
241 /// This is much faster than `format()` and is the typical way to clear the display.
242 fn erase(&mut self);
243
244 /// Set a pixel in the framebuffer.
245 fn set_pixel(&mut self, p: Point, color: Color);
246}
247
248#[cfg(test)]
249mod tests {
250 extern crate std;
251
252 use std::format;
253
254 use super::*;
255 use embedded_graphics::pixelcolor::RgbColor;
256
257 #[test]
258 fn test_compute_rows() {
259 // Test typical panel sizes
260 assert_eq!(compute_rows(32), 16);
261 assert_eq!(compute_rows(64), 32);
262 assert_eq!(compute_rows(16), 8);
263 assert_eq!(compute_rows(128), 64);
264
265 // Test edge cases
266 assert_eq!(compute_rows(2), 1);
267 assert_eq!(compute_rows(0), 0);
268
269 // Test that it always divides by 2
270 for rows in [8, 16, 24, 32, 48, 64, 96, 128, 256] {
271 assert_eq!(compute_rows(rows), rows / 2);
272 }
273 }
274
275 #[test]
276 fn test_compute_frame_count() {
277 // Test common bit depths
278 assert_eq!(compute_frame_count(1), 1); // 2^1 - 1 = 1
279 assert_eq!(compute_frame_count(2), 3); // 2^2 - 1 = 3
280 assert_eq!(compute_frame_count(3), 7); // 2^3 - 1 = 7
281 assert_eq!(compute_frame_count(4), 15); // 2^4 - 1 = 15
282 assert_eq!(compute_frame_count(5), 31); // 2^5 - 1 = 31
283 assert_eq!(compute_frame_count(6), 63); // 2^6 - 1 = 63
284 assert_eq!(compute_frame_count(7), 127); // 2^7 - 1 = 127
285 assert_eq!(compute_frame_count(8), 255); // 2^8 - 1 = 255
286
287 // Test the formula: (2^bits) - 1
288 for bits in 1..=8 {
289 let expected = (1usize << bits) - 1;
290 assert_eq!(compute_frame_count(bits), expected);
291 }
292 }
293
294 #[test]
295 fn test_compute_frame_count_properties() {
296 // Test that frame count grows exponentially
297 assert!(compute_frame_count(2) > compute_frame_count(1));
298 assert!(compute_frame_count(3) > compute_frame_count(2));
299 assert!(compute_frame_count(4) > compute_frame_count(3));
300
301 // Test doubling property: each additional bit approximately doubles frame count
302 for bits in 1..=7 {
303 let current_frames = compute_frame_count(bits);
304 let next_frames = compute_frame_count(bits + 1);
305 // next_frames should be approximately 2 * current_frames + 1
306 assert_eq!(next_frames, 2 * current_frames + 1);
307 }
308 }
309
310 #[test]
311 fn test_word_size_enum() {
312 // Test enum values
313 let eight = WordSize::Eight;
314 let sixteen = WordSize::Sixteen;
315
316 assert_ne!(eight, sixteen);
317 assert_eq!(eight, WordSize::Eight);
318 assert_eq!(sixteen, WordSize::Sixteen);
319 }
320
321 #[test]
322 fn test_word_size_debug() {
323 let eight = WordSize::Eight;
324 let sixteen = WordSize::Sixteen;
325
326 let eight_debug = format!("{:?}", eight);
327 let sixteen_debug = format!("{:?}", sixteen);
328
329 assert_eq!(eight_debug, "Eight");
330 assert_eq!(sixteen_debug, "Sixteen");
331 }
332
333 #[test]
334 fn test_word_size_clone_copy() {
335 let original = WordSize::Eight;
336 let cloned = original.clone();
337 let copied = original;
338
339 assert_eq!(original, cloned);
340 assert_eq!(original, copied);
341 assert_eq!(cloned, copied);
342 }
343
344 #[test]
345 fn test_color_type_alias() {
346 // Test that Color is an alias for Rgb888
347 let red_color: Color = Color::RED;
348 let red_rgb888: Rgb888 = Rgb888::RED;
349
350 assert_eq!(red_color, red_rgb888);
351 assert_eq!(red_color.r(), 255);
352 assert_eq!(red_color.g(), 0);
353 assert_eq!(red_color.b(), 0);
354
355 // Test various colors
356 let colors = [
357 (Color::RED, (255, 0, 0)),
358 (Color::GREEN, (0, 255, 0)),
359 (Color::BLUE, (0, 0, 255)),
360 (Color::WHITE, (255, 255, 255)),
361 (Color::BLACK, (0, 0, 0)),
362 (Color::CYAN, (0, 255, 255)),
363 (Color::MAGENTA, (255, 0, 255)),
364 (Color::YELLOW, (255, 255, 0)),
365 ];
366
367 for (color, (r, g, b)) in colors {
368 assert_eq!(color.r(), r);
369 assert_eq!(color.g(), g);
370 assert_eq!(color.b(), b);
371 }
372 }
373
374 #[test]
375 fn test_color_construction() {
376 // Test Color construction from RGB values
377 let custom_color = Color::new(128, 64, 192);
378 assert_eq!(custom_color.r(), 128);
379 assert_eq!(custom_color.g(), 64);
380 assert_eq!(custom_color.b(), 192);
381
382 // Test that it behaves like Rgb888
383 let rgb888_color = Rgb888::new(128, 64, 192);
384 assert_eq!(custom_color, rgb888_color);
385 }
386
387 #[test]
388 fn test_helper_functions_const() {
389 // Test that helper functions can be used in const contexts
390 const ROWS: usize = 32;
391 const COMPUTED_NROWS: usize = compute_rows(ROWS);
392 const BITS: u8 = 4;
393 const COMPUTED_FRAME_COUNT: usize = compute_frame_count(BITS);
394
395 assert_eq!(COMPUTED_NROWS, 16);
396 assert_eq!(COMPUTED_FRAME_COUNT, 15);
397 }
398
399 #[test]
400 fn test_realistic_panel_configurations() {
401 // Test common HUB75 panel configurations
402 struct PanelConfig {
403 rows: usize,
404 cols: usize,
405 bits: u8,
406 }
407
408 let configs = [
409 PanelConfig {
410 rows: 32,
411 cols: 64,
412 bits: 3,
413 }, // 32x64 panel, 3-bit color
414 PanelConfig {
415 rows: 64,
416 cols: 64,
417 bits: 4,
418 }, // 64x64 panel, 4-bit color
419 PanelConfig {
420 rows: 32,
421 cols: 32,
422 bits: 5,
423 }, // 32x32 panel, 5-bit color
424 PanelConfig {
425 rows: 16,
426 cols: 32,
427 bits: 6,
428 }, // 16x32 panel, 6-bit color
429 ];
430
431 for config in configs {
432 let nrows = compute_rows(config.rows);
433 let frame_count = compute_frame_count(config.bits);
434
435 // Basic sanity checks for rows
436 assert!(nrows > 0);
437 assert!(nrows <= config.rows);
438 assert_eq!(nrows * 2, config.rows);
439
440 // Basic sanity checks for columns
441 assert!(config.cols > 0);
442 assert!(config.cols <= 256); // Reasonable upper limit for HUB75 panels
443
444 // Frame count checks
445 assert!(frame_count > 0);
446 assert!(frame_count < 256); // Should be reasonable for typical bit depths
447
448 // Frame count should grow with bit depth
449 let prev_frame_count = compute_frame_count(config.bits - 1);
450 assert!(frame_count > prev_frame_count);
451 }
452 }
453
454 #[test]
455 fn test_memory_calculations() {
456 // Test that we can calculate memory requirements using helper functions
457 const ROWS: usize = 64;
458 const COLS: usize = 64;
459 const BITS: u8 = 4;
460
461 const NROWS: usize = compute_rows(ROWS);
462 const FRAME_COUNT: usize = compute_frame_count(BITS);
463
464 // These should be compile-time constants
465 assert_eq!(NROWS, 32);
466 assert_eq!(FRAME_COUNT, 15);
467
468 // Verify the relationship between parameters
469 assert_eq!(NROWS * 2, ROWS);
470 assert_eq!(FRAME_COUNT, (1 << BITS) - 1);
471
472 // Verify COLS is reasonable for memory calculations
473 assert!(COLS > 0);
474 assert!(COLS <= 256); // Reasonable limit for HUB75 panels
475 }
476
477 #[test]
478 fn test_edge_cases() {
479 // Test minimum values
480 assert_eq!(compute_rows(2), 1);
481 assert_eq!(compute_frame_count(1), 1);
482
483 // Test maximum reasonable values
484 assert_eq!(compute_rows(512), 256);
485 assert_eq!(compute_frame_count(8), 255);
486
487 // Test zero (though not practical)
488 assert_eq!(compute_rows(0), 0);
489 }
490
491 // Note: We can't easily test the traits directly since they're abstract,
492 // but they are thoroughly tested through their implementations in
493 // the plain and latched modules.
494
495 #[test]
496 fn test_word_size_equality() {
497 // Test all combinations of equality
498 assert_eq!(WordSize::Eight, WordSize::Eight);
499 assert_eq!(WordSize::Sixteen, WordSize::Sixteen);
500 assert_ne!(WordSize::Eight, WordSize::Sixteen);
501 assert_ne!(WordSize::Sixteen, WordSize::Eight);
502 }
503
504 #[test]
505 fn test_bit_depth_limits() {
506 // Test that our bit depth calculations work for the full range
507 for bits in 1..=8 {
508 let frame_count = compute_frame_count(bits);
509
510 // Frame count should be positive
511 assert!(frame_count > 0);
512
513 // Frame count should be less than 2^bits
514 assert!(frame_count < (1 << bits));
515
516 // Frame count should be exactly (2^bits) - 1
517 assert_eq!(frame_count, (1 << bits) - 1);
518 }
519 }
520
521 #[test]
522 fn test_documentation_examples() {
523 // Test the example values from the documentation
524 const ROWS: usize = 32;
525 const COLS: usize = 64;
526 const NROWS: usize = ROWS / 2;
527 const BITS: u8 = 8;
528 const FRAME_COUNT: usize = (1 << BITS) - 1;
529
530 // Verify using our helper functions
531 assert_eq!(compute_rows(ROWS), NROWS);
532 assert_eq!(compute_frame_count(BITS), FRAME_COUNT);
533
534 // Verify the values match documentation
535 assert_eq!(ROWS, 32);
536 assert_eq!(COLS, 64);
537 assert_eq!(NROWS, 16);
538 assert_eq!(FRAME_COUNT, 255);
539
540 // Verify this matches typical panel dimensions
541 assert!(COLS > 0);
542 assert_eq!(NROWS * 2, ROWS);
543 }
544}