Skip to main content

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.10.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.10.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.10.0", features = ["tail-closes-latch"] }
128//! ```
129//!
130//! ### Blanking delay features (`lead-blank-*` / `trail-blank-*`)
131//!
132//! Control the number of pixel-clock cycles of blanking (`OE` HIGH) inserted
133//! around row-address changes. The lead blank controls how many cycles the
134//! output is blanked *before* the row address is changed, and the trail blank
135//! controls blanking *after* the row address is changed. Together they give
136//! the address lines time to settle and prevent ghosting or "bleeding"
137//! artifacts caused by the panel briefly displaying data on the wrong row
138//! during the transition.
139//!
140//! | Feature          | Blanking cycles | Position              |
141//! |------------------|-----------------|-----------------------|
142//! | *(none)*         | 1 (default)     | before & after change |
143//! | `lead-blank-1`   | 1               | before address change |
144//! | `lead-blank-2`   | 2               | before address change |
145//! | `lead-blank-4`   | 4               | before address change |
146//! | `lead-blank-8`   | 8               | before address change |
147//! | `lead-blank-16`  | 16              | before address change |
148//! | `trail-blank-1`  | 1               | after address change  |
149//! | `trail-blank-2`  | 2               | after address change  |
150//! | `trail-blank-4`  | 4               | after address change  |
151//! | `trail-blank-8`  | 8               | after address change  |
152//! | `trail-blank-16` | 16              | after address change  |
153//!
154//! Higher values reduce ghosting at the cost of slightly less brightness (the
155//! LEDs are on for less time per scan line). Start with the default and increase
156//! only if you observe row-transition artifacts on your particular panel
157//! hardware.
158//!
159//! ```toml
160//! [dependencies]
161//! hub75-framebuffer = { version = "0.10.0", features = ["lead-blank-4", "trail-blank-2"] }
162//! ```
163//!
164//! **Note:** At most one `lead-blank-*` and one `trail-blank-*` feature may be
165//! enabled at a time. If multiple are enabled for the same edge, compile-time cfg
166//! conflicts will result.
167//!
168//! ### `defmt` Feature
169//! Implements `defmt::Format` for framebuffer types so they can be emitted with
170//! the `defmt` logging framework. No functional changes; purely adds a trait impl.
171//!
172//! ### `doc-images` Feature
173//! Embeds documentation images when building docs on docs.rs. Not needed for
174//! normal usage.
175#![no_std]
176#![warn(missing_docs)]
177#![warn(clippy::all)]
178#![warn(clippy::pedantic)]
179#![allow(clippy::cast_possible_truncation)]
180#![allow(clippy::cast_sign_loss)]
181
182use embedded_graphics::draw_target::DrawTarget;
183use embedded_graphics::pixelcolor::Rgb888;
184use embedded_graphics::prelude::Point;
185
186pub mod bitplane;
187pub mod latched;
188pub mod plain;
189pub mod tiling;
190
191/// Color type used in the framebuffer
192pub type Color = Rgb888;
193
194/// Word size configuration for the framebuffer
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum WordSize {
197    /// 8-bit word size
198    Eight,
199    /// 16-bit word size
200    Sixteen,
201}
202
203/// Computes the NROWS value from ROWS for `DmaFrameBuffer`
204///
205/// # Arguments
206///
207/// * `rows` - Total number of rows in the display
208///
209/// # Returns
210///
211/// Number of rows needed internally for `DmaFrameBuffer`
212#[must_use]
213pub const fn compute_rows(rows: usize) -> usize {
214    rows / 2
215}
216
217/// Computes the number of frames needed for a given bit depth
218///
219/// This is used to determine how many frames are needed to achieve
220/// the desired color depth through Binary Code Modulation (BCM).
221///
222/// # Arguments
223///
224/// * `bits` - Number of bits per color channel
225///
226/// # Returns
227///
228/// Number of frames required for the given bit depth
229#[must_use]
230pub const fn compute_frame_count(bits: u8) -> usize {
231    (1usize << bits) - 1
232}
233
234/// Trait for read-only framebuffers.
235pub trait FrameBuffer {
236    /// The word type used by this framebuffer.
237    type Word;
238
239    /// Returns the word size configuration for this framebuffer
240    fn get_word_size(&self) -> WordSize {
241        match size_of::<Self::Word>() {
242            1 => WordSize::Eight,
243            2 => WordSize::Sixteen,
244            _ => panic!("Unsupported word size"),
245        }
246    }
247
248    /// Returns the number of BCM bit-planes in this framebuffer.
249    ///
250    /// Contiguous (threshold-based) framebuffers return `1` — the entire
251    /// buffer is treated as a single plane.  True bit-plane framebuffers
252    /// return the number of planes (typically equal to the colour depth in
253    /// bits).
254    fn plane_count(&self) -> usize;
255
256    /// Returns a raw pointer and byte length for the given plane.
257    ///
258    /// For a single-plane framebuffer (`plane_count() == 1`), `plane_idx`
259    /// must be `0` and the returned span covers the whole DMA-ready buffer.
260    ///
261    /// # Panics
262    ///
263    /// May panic if `plane_idx >= plane_count()`.
264    fn plane_ptr_len(&self, plane_idx: usize) -> (*const u8, usize);
265}
266
267/// Trait for mutable framebuffers
268///
269/// This trait extends `FrameBuffer` with the ability to draw to the framebuffer
270/// using the `embedded_graphics` drawing primitives.
271pub trait MutableFrameBuffer:
272    FrameBuffer + DrawTarget<Color = Color, Error = core::convert::Infallible>
273{
274}
275
276/// Trait for all operations a user may want to call on a framebuffer.
277pub trait FrameBufferOperations: FrameBuffer {
278    /// Erase pixel colors while preserving control bits.
279    /// This is much faster than `format()` and is the typical way to clear the display.
280    fn erase(&mut self);
281
282    /// Set a pixel in the framebuffer.
283    fn set_pixel(&mut self, p: Point, color: Color);
284}
285
286#[cfg(test)]
287mod tests {
288    extern crate std;
289
290    use std::format;
291
292    use super::*;
293    use embedded_graphics::pixelcolor::RgbColor;
294
295    #[test]
296    fn test_compute_rows() {
297        // Test typical panel sizes
298        assert_eq!(compute_rows(32), 16);
299        assert_eq!(compute_rows(64), 32);
300        assert_eq!(compute_rows(16), 8);
301        assert_eq!(compute_rows(128), 64);
302
303        // Test edge cases
304        assert_eq!(compute_rows(2), 1);
305        assert_eq!(compute_rows(0), 0);
306
307        // Test that it always divides by 2
308        for rows in [8, 16, 24, 32, 48, 64, 96, 128, 256] {
309            assert_eq!(compute_rows(rows), rows / 2);
310        }
311    }
312
313    #[test]
314    fn test_compute_frame_count() {
315        // Test common bit depths
316        assert_eq!(compute_frame_count(1), 1); // 2^1 - 1 = 1
317        assert_eq!(compute_frame_count(2), 3); // 2^2 - 1 = 3
318        assert_eq!(compute_frame_count(3), 7); // 2^3 - 1 = 7
319        assert_eq!(compute_frame_count(4), 15); // 2^4 - 1 = 15
320        assert_eq!(compute_frame_count(5), 31); // 2^5 - 1 = 31
321        assert_eq!(compute_frame_count(6), 63); // 2^6 - 1 = 63
322        assert_eq!(compute_frame_count(7), 127); // 2^7 - 1 = 127
323        assert_eq!(compute_frame_count(8), 255); // 2^8 - 1 = 255
324
325        // Test the formula: (2^bits) - 1
326        for bits in 1..=8 {
327            let expected = (1usize << bits) - 1;
328            assert_eq!(compute_frame_count(bits), expected);
329        }
330    }
331
332    #[test]
333    fn test_compute_frame_count_properties() {
334        // Test that frame count grows exponentially
335        assert!(compute_frame_count(2) > compute_frame_count(1));
336        assert!(compute_frame_count(3) > compute_frame_count(2));
337        assert!(compute_frame_count(4) > compute_frame_count(3));
338
339        // Test doubling property: each additional bit approximately doubles frame count
340        for bits in 1..=7 {
341            let current_frames = compute_frame_count(bits);
342            let next_frames = compute_frame_count(bits + 1);
343            // next_frames should be approximately 2 * current_frames + 1
344            assert_eq!(next_frames, 2 * current_frames + 1);
345        }
346    }
347
348    #[test]
349    fn test_word_size_enum() {
350        // Test enum values
351        let eight = WordSize::Eight;
352        let sixteen = WordSize::Sixteen;
353
354        assert_ne!(eight, sixteen);
355        assert_eq!(eight, WordSize::Eight);
356        assert_eq!(sixteen, WordSize::Sixteen);
357    }
358
359    #[test]
360    fn test_word_size_debug() {
361        let eight = WordSize::Eight;
362        let sixteen = WordSize::Sixteen;
363
364        let eight_debug = format!("{:?}", eight);
365        let sixteen_debug = format!("{:?}", sixteen);
366
367        assert_eq!(eight_debug, "Eight");
368        assert_eq!(sixteen_debug, "Sixteen");
369    }
370
371    #[test]
372    fn test_word_size_clone_copy() {
373        let original = WordSize::Eight;
374        let cloned = original.clone();
375        let copied = original;
376
377        assert_eq!(original, cloned);
378        assert_eq!(original, copied);
379        assert_eq!(cloned, copied);
380    }
381
382    #[test]
383    fn test_color_type_alias() {
384        // Test that Color is an alias for Rgb888
385        let red_color: Color = Color::RED;
386        let red_rgb888: Rgb888 = Rgb888::RED;
387
388        assert_eq!(red_color, red_rgb888);
389        assert_eq!(red_color.r(), 255);
390        assert_eq!(red_color.g(), 0);
391        assert_eq!(red_color.b(), 0);
392
393        // Test various colors
394        let colors = [
395            (Color::RED, (255, 0, 0)),
396            (Color::GREEN, (0, 255, 0)),
397            (Color::BLUE, (0, 0, 255)),
398            (Color::WHITE, (255, 255, 255)),
399            (Color::BLACK, (0, 0, 0)),
400            (Color::CYAN, (0, 255, 255)),
401            (Color::MAGENTA, (255, 0, 255)),
402            (Color::YELLOW, (255, 255, 0)),
403        ];
404
405        for (color, (r, g, b)) in colors {
406            assert_eq!(color.r(), r);
407            assert_eq!(color.g(), g);
408            assert_eq!(color.b(), b);
409        }
410    }
411
412    #[test]
413    fn test_color_construction() {
414        // Test Color construction from RGB values
415        let custom_color = Color::new(128, 64, 192);
416        assert_eq!(custom_color.r(), 128);
417        assert_eq!(custom_color.g(), 64);
418        assert_eq!(custom_color.b(), 192);
419
420        // Test that it behaves like Rgb888
421        let rgb888_color = Rgb888::new(128, 64, 192);
422        assert_eq!(custom_color, rgb888_color);
423    }
424
425    #[test]
426    fn test_helper_functions_const() {
427        // Test that helper functions can be used in const contexts
428        const ROWS: usize = 32;
429        const COMPUTED_NROWS: usize = compute_rows(ROWS);
430        const BITS: u8 = 4;
431        const COMPUTED_FRAME_COUNT: usize = compute_frame_count(BITS);
432
433        assert_eq!(COMPUTED_NROWS, 16);
434        assert_eq!(COMPUTED_FRAME_COUNT, 15);
435    }
436
437    #[test]
438    fn test_realistic_panel_configurations() {
439        // Test common HUB75 panel configurations
440        struct PanelConfig {
441            rows: usize,
442            cols: usize,
443            bits: u8,
444        }
445
446        let configs = [
447            PanelConfig {
448                rows: 32,
449                cols: 64,
450                bits: 3,
451            }, // 32x64 panel, 3-bit color
452            PanelConfig {
453                rows: 64,
454                cols: 64,
455                bits: 4,
456            }, // 64x64 panel, 4-bit color
457            PanelConfig {
458                rows: 32,
459                cols: 32,
460                bits: 5,
461            }, // 32x32 panel, 5-bit color
462            PanelConfig {
463                rows: 16,
464                cols: 32,
465                bits: 6,
466            }, // 16x32 panel, 6-bit color
467        ];
468
469        for config in configs {
470            let nrows = compute_rows(config.rows);
471            let frame_count = compute_frame_count(config.bits);
472
473            // Basic sanity checks for rows
474            assert!(nrows > 0);
475            assert!(nrows <= config.rows);
476            assert_eq!(nrows * 2, config.rows);
477
478            // Basic sanity checks for columns
479            assert!(config.cols > 0);
480            assert!(config.cols <= 256); // Reasonable upper limit for HUB75 panels
481
482            // Frame count checks
483            assert!(frame_count > 0);
484            assert!(frame_count < 256); // Should be reasonable for typical bit depths
485
486            // Frame count should grow with bit depth
487            let prev_frame_count = compute_frame_count(config.bits - 1);
488            assert!(frame_count > prev_frame_count);
489        }
490    }
491
492    #[test]
493    fn test_memory_calculations() {
494        // Test that we can calculate memory requirements using helper functions
495        const ROWS: usize = 64;
496        const COLS: usize = 64;
497        const BITS: u8 = 4;
498
499        const NROWS: usize = compute_rows(ROWS);
500        const FRAME_COUNT: usize = compute_frame_count(BITS);
501
502        // These should be compile-time constants
503        assert_eq!(NROWS, 32);
504        assert_eq!(FRAME_COUNT, 15);
505
506        // Verify the relationship between parameters
507        assert_eq!(NROWS * 2, ROWS);
508        assert_eq!(FRAME_COUNT, (1 << BITS) - 1);
509
510        // Verify COLS is reasonable for memory calculations
511        assert!(COLS > 0);
512        assert!(COLS <= 256); // Reasonable limit for HUB75 panels
513    }
514
515    #[test]
516    fn test_edge_cases() {
517        // Test minimum values
518        assert_eq!(compute_rows(2), 1);
519        assert_eq!(compute_frame_count(1), 1);
520
521        // Test maximum reasonable values
522        assert_eq!(compute_rows(512), 256);
523        assert_eq!(compute_frame_count(8), 255);
524
525        // Test zero (though not practical)
526        assert_eq!(compute_rows(0), 0);
527    }
528
529    // Note: We can't easily test the traits directly since they're abstract,
530    // but they are thoroughly tested through their implementations in
531    // the plain and latched modules.
532
533    #[test]
534    fn test_word_size_equality() {
535        // Test all combinations of equality
536        assert_eq!(WordSize::Eight, WordSize::Eight);
537        assert_eq!(WordSize::Sixteen, WordSize::Sixteen);
538        assert_ne!(WordSize::Eight, WordSize::Sixteen);
539        assert_ne!(WordSize::Sixteen, WordSize::Eight);
540    }
541
542    #[test]
543    fn test_bit_depth_limits() {
544        // Test that our bit depth calculations work for the full range
545        for bits in 1..=8 {
546            let frame_count = compute_frame_count(bits);
547
548            // Frame count should be positive
549            assert!(frame_count > 0);
550
551            // Frame count should be less than 2^bits
552            assert!(frame_count < (1 << bits));
553
554            // Frame count should be exactly (2^bits) - 1
555            assert_eq!(frame_count, (1 << bits) - 1);
556        }
557    }
558
559    #[test]
560    fn test_documentation_examples() {
561        // Test the example values from the documentation
562        const ROWS: usize = 32;
563        const COLS: usize = 64;
564        const NROWS: usize = ROWS / 2;
565        const BITS: u8 = 8;
566        const FRAME_COUNT: usize = (1 << BITS) - 1;
567
568        // Verify using our helper functions
569        assert_eq!(compute_rows(ROWS), NROWS);
570        assert_eq!(compute_frame_count(BITS), FRAME_COUNT);
571
572        // Verify the values match documentation
573        assert_eq!(ROWS, 32);
574        assert_eq!(COLS, 64);
575        assert_eq!(NROWS, 16);
576        assert_eq!(FRAME_COUNT, 255);
577
578        // Verify this matches typical panel dimensions
579        assert!(COLS > 0);
580        assert_eq!(NROWS * 2, ROWS);
581    }
582}