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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
//! Framebuffer implementation for HUB75 LED matrix displays.
//!
//! ## How HUB75 LED Displays Work
//!
//! HUB75 RGB LED matrix panels are scanned, time-multiplexed displays that behave like a long
//! daisy-chained shift register rather than a random-access framebuffer.
//!
//! ### Signal names
//! - **R1 G1 B1 / R2 G2 B2** – Serial colour data for the upper and lower halves of the active scan line
//! - **CLK** – Shift-register clock; every rising edge pushes the six colour bits one pixel to the right
//! - **LAT / STB** – Latch; copies the shift-register contents to the LED drivers for the row currently selected by the address lines
//! - **OE** – Output-Enable (active LOW): LEDs are lit while OE is LOW and blanked when it is HIGH
//! - **A B C D (E)** – Row-address select lines (choose which pair of rows is lit)
//! - **VCC & GND** – 5 V power for panel logic and LED drivers
//!
//! ### Row-pair scanning workflow (e.g., 1/16-scan panel)
//! 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).
//! 2. After the last pixel is clocked in, the controller raises OE HIGH to blank the LEDs.
//! 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.
//! 4. OE is immediately driven LOW again, lighting row pair N.
//! 5. Steps 1–4 repeat for every row pair fast enough (hundreds of Hz) that the human eye sees a steady image.
//! - 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.
//!
//! ### Brightness and colour depth (Binary Code Modulation)
//! - Full colour is typically achieved using **Binary Code Modulation (BCM)**, also known as *Bit-Angle Modulation (BAM)*. Each bit-plane is displayed for a duration 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.
//! - 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.
//!
//! ### Implications for software / hardware drivers
//! - You don't simply "write a pixel" once; you must continuously stream the complete refresh data at MHz-range clock rates.
//! - Precise timing of CLK, OE, address lines, and LAT is critical—especially the order: blank (OE HIGH) → set address → latch → un-blank (OE LOW).
//! - Microcontrollers typically employ DMA, PIO, or parallel GPIO tricks, and FPGAs use dedicated logic, to sustain the data throughput while leaving processing resources free.
//!
//! 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.
//!
//! ## Framebuffer Implementations
//!
//! Four framebuffer layouts are provided, covering two hardware variants and
//! two BCM strategies:
//!
//! | Module | Word size | External latch? | BCM strategy |
//! |--------|-----------|-----------------|--------------|
//! | [`bitplane::plain`] | 16-bit | No | True bitplane |
//! | [`bitplane::latched`] | 8-bit | Yes | True bitplane |
//! | [`plain`] *(deprecated)* | 16-bit | No | Threshold frames |
//! | [`latched`] *(deprecated)* | 8-bit | Yes | Threshold frames |
//!
//! ### Plain vs. Latched
//! - **Plain** packs all HUB75 signals (address, latch, OE, colour) into each
//! 16-bit word. No extra hardware beyond a parallel output peripheral.
//! - **Latched** uses 8-bit words with a separate external latch circuit to
//! hold the row address and gate the pixel clock, halving per-entry memory.
//!
//! ### Threshold Frames vs. True Bitplane
//! The two BCM strategies differ in how they store colour data and how the
//! DMA stream must be driven to render it. **The bitplane layouts are
//! recommended for new designs**; the threshold layouts are deprecated.
//!
//! **True bitplane** (`bitplane::plain`, `bitplane::latched`) -- each of
//! `PLANES` planes (typically 8) stores one bit of every colour channel
//! directly. To render, stream each plane's data a number of times equal to
//! its bit-weight (the MSB plane 128 times, the LSB plane once), either with
//! a DMA descriptor chain or by reprogramming the DMA registers per segment.
//! Memory scales linearly with the number of planes. Each module offers a
//! plane-major (`frame`) and a row-major (`row`) layout — both LSB-first
//! with suffix-coalesced BCM segments; see their documentation for the exact
//! scan order.
//!
//! **Threshold frames** (`plain`, `latched`) -- **deprecated.** The driver
//! compares each channel's 8-bit value against per-frame thresholds and
//! stores the resulting on/off bits. For a colour depth of `BITS`, this
//! produces `2^BITS - 1` frames. Frame *n* is displayed for a duration
//! proportional to `2^n`. Memory grows exponentially with colour depth, but
//! the whole refresh is one contiguous buffer that even interrupt-less
//! circular DMA can stream.
//!
//! All four variants have configurable row and column dimensions, support
//! `embedded-graphics` via the `DrawTarget` trait, and expose their BCM
//! scan sequence through the [`FrameBuffer`] trait.
//!
//! ## Memory placement (⚠️ large buffers)
//!
//! Every framebuffer is a large inline array sized from its const generic
//! parameters. Rough sizes:
//!
//! - `bitplane::plain`: `PLANES × NROWS × (COLS + gap) × 2` bytes.
//! - `bitplane::latched`: `PLANES × NROWS × (COLS + gap)` bytes.
//! - `plain`: `(2^BITS - 1) × NROWS × COLS × 2` bytes.
//! - `latched`: `(2^BITS - 1) × NROWS × (COLS + 4)` bytes.
//!
//! For example, a 64×64 panel at 8-bit colour depth is already tens of
//! kilobytes. **Never bind a framebuffer to a task-local `let`** — the whole
//! buffer would be placed on that task's stack and overflow it.
//!
//! Framebuffers are **mutable** (drawing takes `&mut self`), so they need a
//! `'static` home that hands out `&'static mut` **without** `unsafe`.
//! `static mut` is *not* an option. Use `static_cell::StaticCell`, which
//! guarantees the value is taken at most once and lives in `.bss`:
//!
//! ```rust,no_run
//! use embedded_graphics::pixelcolor::RgbColor;
//! use embedded_graphics::prelude::Point;
//! use hub75_framebuffer::bitplane::plain::frame::DmaFrameBuffer;
//! use hub75_framebuffer::Color;
//! use static_cell::StaticCell;
//!
//! const COLS: usize = 64;
//! const NROWS: usize = 32;
//! const PLANES: usize = 8;
//! type Fb = DmaFrameBuffer<NROWS, COLS, PLANES>;
//!
//! // `StaticCell` hands out `&'static mut` without `unsafe`; the value is
//! // taken at most once and lives in .bss, not on the stack.
//! static FB: StaticCell<Fb> = StaticCell::new();
//! let fb = FB.uninit().write(Fb::new());
//!
//! fb.set_pixel(Point::new(0, 0), Color::RED);
//! ```
//!
//! ## Driving the Panel (DMA Integration)
//!
//! This crate is **buffer-only**: it builds the memory image and describes
//! exactly what to stream via the [`FrameBuffer`] trait — writing the
//! peripheral driver (the refresh loop) is up to you. A driver only needs
//! two things from a framebuffer:
//!
//! - [`FrameBuffer::Word`] — the stream element type: `u16` for the `plain`
//! variants, `u8` for the `latched` ones. The peripheral must output this
//! many bits in parallel and generates the pixel clock (`CLK`) itself.
//! - [`FrameBuffer::BCM_SEQUENCE`] and [`FrameBuffer::bcm_segment`] — the
//! ordered `(ptr, len, reps)` segments that make up one complete panel
//! refresh.
//!
//! The framebuffer must live in DMA-capable memory and outlive the transfer:
//! place it in a `static` (or a DMA RAM section on chips that require one)
//! and apply whatever alignment and cache maintenance your MCU needs.
//!
//! ### DMA with descriptor chains (least CPU)
//!
//! The bitplane stream is non-uniform: each segment must be output `reps`
//! times (the MSB plane up to `2^(PLANES-2)` times). This maps naturally
//! onto DMA descriptor chains (e.g. ESP32 GPDMA linked-list mode) — use
//! [`FrameBuffer::BCM_SEQUENCE`] / [`bcm_rep_count`] to size the descriptor
//! table at compile time and [`FrameBuffer::bcm_segment`] to populate it; a
//! segment whose `len` exceeds the DMA's maximum transfer size is simply
//! split across several descriptors. Link the chain into a loop and the
//! panel refreshes forever with zero CPU involvement. For free-running
//! loops, consider the `tail-closes-latch` feature so `LAT` is not left
//! asserted when the chain wraps.
//!
//! ### Simple DMA (registers only, no descriptors)
//!
//! If your DMA is just *source address + length* registers with a
//! transfer-complete interrupt, walk the segments in the ISR: on each
//! interrupt, program the address/length registers from
//! [`FrameBuffer::bcm_segment`], re-arm the transfer, and re-issue the same
//! segment until its `reps` count is exhausted before advancing. The cadence
//! is modest — the plane-major (`frame`) layouts raise only `PLANES`
//! interrupts per panel refresh (8 at full color depth); the row-major
//! (`row`) layouts raise one per segment of every row
//! ([`FrameBuffer::BCM_SEGMENT_COUNT`] per refresh).
//!
//! If the DMA cannot interrupt at all — truly circular-only hardware — the
//! deprecated threshold framebuffers ([`plain`], [`latched`]) remain an
//! option: their entire refresh is one contiguous buffer
//! ([`FrameBuffer::BCM_SEQUENCE_LEN`] is `1`, `reps == 1`) with all BCM
//! timing baked into the memory image, at an exponential memory cost.
//!
//! ## Multiple Panels / Scan-Pattern Remapping
//! Use [`tiling::RemappedFrameBuffer`] to drive several HUB75 panels as one
//! large virtual display, or to remap pixels for non-standard scan patterns
//! (e.g. 1/16-scan on 64×64 panels). It works with all four framebuffer types
//! and only requires two generic parameters (`F` and `M`).
//!
//! Combine it with a [`tiling::PixelRemapper`] implementation such as
//! [`tiling::ChainTopRightDown`] (tiling) or [`tiling::QuarterScan`] (1/16-scan).
//! The wrapper exposes a single `embedded-graphics` canvas, so for example a
//! 3 × 3 stack of 64 × 32 panels simply looks like a 192 × 96 screen while
//! all coordinate translation happens transparently.
//!
//! The older [`tiling::TiledFrameBuffer`] is still available but deprecated.
//!
//! ## Available Feature Flags
//!
//! ### `skip-black-pixels` Feature (disabled by default)
//! When enabled, calls to `set_pixel()` with `Color::BLACK` return early without
//! writing to the framebuffer. This provides a significant performance boost for
//! UI applications that frequently draw black pixels (backgrounds, clearing, etc.)
//! by assuming the framebuffer was already cleared.
//!
//! **Important**: This optimization assumes that black pixels represent "no change"
//! rather than "explicitly set to black". By default, black pixels are written
//! normally to ensure correct overwrite behavior. To enable the optimization:
//!
//! ```toml
//! [dependencies]
//! hub75-framebuffer = { version = "0.13.0", features = ["skip-black-pixels"] }
//! ```
//!
//! ### `esp32-ordering` Feature (required for original ESP32 only)
//! **Required** when targeting the original ESP32 chip (not ESP32-S3 or other variants).
//! This feature adjusts byte ordering to accommodate the quirky requirements of the
//! ESP32's I²S peripheral in 8-bit and 16-bit modes. The original ESP32 has different
//! byte ordering requirements compared to other ESP32 variants (S2, S3, C3, etc.),
//! which do **not** need this feature.
//!
//! ```toml
//! [dependencies]
//! hub75-framebuffer = { version = "0.13.0", features = ["esp32-ordering"] }
//! ```
//!
//! ### `interstate75` Feature (Pimoroni Interstate 75 / 75 W only)
//! Selects the 16-bit pin layout of the Pimoroni Interstate 75 and
//! Interstate 75 W (`RP2040` / `RP2350`). The DMA word is pre-aligned to the
//! board's contiguous GPIO mapping (`GPIO0..GPIO13`) so a PIO `out pins, 16`
//! stream can clock out the panel with no run-time bit shuffling:
//!
//! ```text
//! bit 13 12 11 10..6 5..3 2..0
//! OE LAT (spare) E D C B A B1 G1 R1 B0 G0 R0
//! ```
//!
//! Bit 11 is unused by this crate and always left at 0.
//!
//! Applies to the 16-bit [`plain`] and [`bitplane::plain`] framebuffers only;
//! the 8-bit `latched` framebuffers are unaffected. Mutually exclusive with
//! `esp32-ordering`.
//!
//! ```toml
//! [dependencies]
//! hub75-framebuffer = { version = "0.13.0", features = ["interstate75"] }
//! ```
//!
//! ### `tail-closes-latch` Feature (plain framebuffers only)
//! Appends a single extra "tail" word at the end of the DMA buffer that drives the
//! LATCH signal LOW (de-asserted) on the final clock edge. Without this feature the
//! last word in each row asserts LATCH HIGH to latch shifted data into the LED
//! drivers, and the GPIO pins remain in that state after the DMA transfer completes.
//! Some hardware configurations (e.g. free-running DMA loops or peripherals that
//! continue clocking after the descriptor chain ends) can re-latch stale data or
//! glitch if LATCH is left asserted.
//!
//! Enabling `tail-closes-latch` adds one 16-bit `Entry` (for `plain`) or one entry
//! per bit-plane (for `bitplane::plain`) that parks the bus with LATCH=0 and
//! OE=BLANK, cleanly terminating the transfer. The cost is a single extra word per
//! DMA chunk, which is negligible compared to the frame data.
//!
//! ```toml
//! [dependencies]
//! hub75-framebuffer = { version = "0.13.0", features = ["tail-closes-latch"] }
//! ```
//!
//! ### `reverse-row-order` Feature (disabled by default)
//! Stores the rows of every framebuffer layout in reverse scan order so that
//! the DMA stream renders the last panel row first and row 0 last. The rows
//! are physically reversed in the buffer (row addresses are written
//! back-to-front while keeping the deferred address-change timing intact) and
//! the pixel-setting paths map logical rows to the reversed slots, so logical
//! coordinates are unchanged — only the scan order changes.
//!
//! ```toml
//! [dependencies]
//! hub75-framebuffer = { version = "0.13.0", features = ["reverse-row-order"] }
//! ```
//!
//! ### Blanking delay features (`lead-blank-*` / `trail-blank-*`)
//!
//! Control the number of pixel-clock cycles of blanking (`OE` HIGH) inserted
//! around row-address changes. The lead blank controls how many cycles the
//! output is blanked *before* the row address is changed, and the trail blank
//! controls blanking *after* the row address is changed. Together they give
//! the address lines time to settle and prevent ghosting or "bleeding"
//! artifacts caused by the panel briefly displaying data on the wrong row
//! during the transition.
//!
//! | Feature | Blanking cycles | Position |
//! |------------------|-----------------|-----------------------|
//! | *(none)* | 1 (default) | before & after change |
//! | `lead-blank-1` | 1 | before address change |
//! | `lead-blank-2` | 2 | before address change |
//! | `lead-blank-4` | 4 | before address change |
//! | `lead-blank-8` | 8 | before address change |
//! | `lead-blank-16` | 16 | before address change |
//! | `trail-blank-1` | 1 | after address change |
//! | `trail-blank-2` | 2 | after address change |
//! | `trail-blank-4` | 4 | after address change |
//! | `trail-blank-8` | 8 | after address change |
//! | `trail-blank-16` | 16 | after address change |
//!
//! Higher values reduce ghosting at the cost of slightly less brightness (the
//! LEDs are on for less time per scan line). Start with the default and increase
//! only if you observe row-transition artifacts on your particular panel
//! hardware.
//!
//! ```toml
//! [dependencies]
//! hub75-framebuffer = { version = "0.13.0", features = ["lead-blank-4", "trail-blank-2"] }
//! ```
//!
//! **Note:** At most one `lead-blank-*` and one `trail-blank-*` feature may be
//! enabled at a time. If multiple are enabled for the same edge, compile-time cfg
//! conflicts will result.
//!
//! ### Inter-row blanking features (`inter-row-blank-*`)
//!
//! Insert additional dead clock cycles at the row transition, between the
//! latch and the address-line change. In plain framebuffers the gap entries
//! hold the previous row address with `OE` HIGH (blank), deferring the
//! address change to the first pixel after the gap and giving slow panels
//! more time to finish blanking before the address lines move. In latched
//! framebuffers the latch and address change are inseparable in hardware,
//! so the gap simply adds extra blanked cycles after the address change.
//! Row-major bitplane framebuffers stream the gap between plane 0 (shifted
//! out before the address change) and plane 1 (shifted out at/after it);
//! all other framebuffers place it at the end of each row, between that
//! row's latch and the next row's first pixel. The gap entries are
//! invisible to all drawing primitives — they only appear in the DMA
//! stream.
//!
//! | Feature | Gap cycles | RAM cost per row |
//! |----------------------|------------|------------------------|
//! | *(none)* | 0 | 0 bytes |
//! | `inter-row-blank-4` | 4 | 8 bytes (16-bit) / 4 bytes (8-bit) |
//! | `inter-row-blank-8` | 8 | 16 bytes / 8 bytes |
//! | `inter-row-blank-16` | 16 | 32 bytes / 16 bytes |
//! | `inter-row-blank-32` | 32 | 64 bytes / 32 bytes |
//!
//! ```toml
//! [dependencies]
//! hub75-framebuffer = { version = "0.13.0", features = ["inter-row-blank-8"] }
//! ```
//!
//! **Note:** At most one `inter-row-blank-*` feature may be enabled at a time.
//! The `inter-row-blank` feature (no number) is an internal umbrella that is
//! enabled automatically by any `inter-row-blank-*` feature — do not enable it
//! directly.
//! These are independent of the `lead-blank-*` / `trail-blank-*` features and
//! can be combined with them.
//!
//! ### `defmt` Feature
//! Implements `defmt::Format` for framebuffer types so they can be emitted with
//! the `defmt` logging framework. No functional changes; purely adds a trait impl.
//!
//! ### `doc-images` Feature
//! Embeds documentation images when building docs on docs.rs. Not needed for
//! normal usage.
use DrawTarget;
use Rgb888;
use Point;
/// Compile-time HUB75-signal → DMA-word bit mapping.
///
/// Exposes [`pinmap::PINMAP`] and [`pinmap::LATCHED_PINMAP`] so a driver crate
/// can validate at compile time that its own board wiring matches the bit
/// assignments this crate assumes.
/// Color type used in the framebuffer
pub type Color = Rgb888;
/// Word size configuration for the framebuffer
/// Computes the NROWS value from ROWS for `DmaFrameBuffer`
///
/// # Arguments
///
/// * `rows` - Total number of rows in the display
///
/// # Returns
///
/// Number of rows needed internally for `DmaFrameBuffer`
pub const
/// Computes the number of frames needed for a given bit depth
///
/// This is used to determine how many frames are needed to achieve
/// the desired color depth through Binary Code Modulation (BCM).
///
/// # Arguments
///
/// * `bits` - Number of bits per color channel
///
/// # Returns
///
/// Number of frames required for the given bit depth
pub const
/// Maps a logical row-pair index to its physical memory slot.
///
/// With the `reverse-row-order` feature the rows are stored back-to-front so
/// that the DMA stream renders the last panel row first and row 0 last; the
/// pixel-setting paths use this to compensate, keeping logical coordinates
/// unchanged. Without the feature this is the identity mapping.
pub const
/// Returns the `(prev_addr, addr)` row addresses for the row stored in
/// physical memory slot `slot` (slots are streamed in order `0..NROWS`).
///
/// `addr` is the panel row address rendered from that slot and `prev_addr` is
/// the address of the row rendered immediately before it (the row displayed
/// while this slot's data is shifted in). With the `reverse-row-order`
/// feature the scan order is reversed: slot 0 renders row `NROWS - 1` first
/// and the last slot renders row 0 last, so each slot's `prev_addr` is the
/// *next* higher address (wrapping to 0 for slot 0, which follows the
/// previous frame's final slot rendering row 0).
pub const
/// Static `(len, reps)` pair describing one BCM segment without a pointer.
///
/// [`FrameBuffer::BCM_SEQUENCE`] is a compile-time array of these, one per
/// segment in the repeating period. Drivers use it to size DMA descriptor
/// tables and compute timing without a framebuffer instance.
/// Capacity of the [`FrameBuffer::BCM_SEQUENCE`] array.
///
/// Sized for the worst case sequence: 8 bit-planes plus an inter-row gap
/// plus an end-of-row trailer.
pub const BCM_SEQUENCE_CAPACITY: usize = 10;
// ---------------------------------------------------------------------------
// Feature-gated blanking-delay constants (shared across all framebuffer types)
// ---------------------------------------------------------------------------
// Compile‑time assertion: at most one lead-blank-* feature enabled.
const _: = assert!;
pub const LEAD_BLANK_DELAY: usize = 1;
pub const LEAD_BLANK_DELAY: usize = 2;
pub const LEAD_BLANK_DELAY: usize = 4;
pub const LEAD_BLANK_DELAY: usize = 8;
pub const LEAD_BLANK_DELAY: usize = 16;
pub const LEAD_BLANK_DELAY: usize = 32;
pub const LEAD_BLANK_DELAY: usize = 0;
// Compile‑time assertion: at most one trail-blank-* feature enabled.
const _: = assert!;
pub const TRAIL_BLANK_DELAY: usize = 1;
pub const TRAIL_BLANK_DELAY: usize = 2;
pub const TRAIL_BLANK_DELAY: usize = 4;
pub const TRAIL_BLANK_DELAY: usize = 8;
pub const TRAIL_BLANK_DELAY: usize = 16;
pub const TRAIL_BLANK_DELAY: usize = 32;
pub const TRAIL_BLANK_DELAY: usize = 0;
// Compile‑time assertion: at most one inter-row-blank-* feature enabled.
const _: = assert!;
// The `inter-row-blank` feature is an internal umbrella enabled by any
// `inter-row-blank-*` feature; it must not be enabled on its own.
compile_error!;
// `interstate75` selects an RP2xxx/PIO pin layout; `esp32-ordering` compensates
// for the original ESP32's I²S byte order. The two target different boards and
// cannot both be correct.
compile_error!;
pub const INTER_ROW_BLANK: usize = 4;
pub const INTER_ROW_BLANK: usize = 8;
pub const INTER_ROW_BLANK: usize = 16;
pub const INTER_ROW_BLANK: usize = 32;
pub const INTER_ROW_BLANK: usize = 0;
/// A single segment of the BCM scan sequence.
///
/// The driver walks an ordered sequence of segments, sending each one `reps`
/// times, to produce correct BCM brightness weighting without needing to know
/// the framebuffer's internal memory layout. See the [`FrameBuffer`]
/// documentation for the segment/sequence terminology.
///
/// # Pointer validity
///
/// The [`ptr`](Self::ptr) field is a raw pointer borrowed from the
/// framebuffer it was obtained from. It carries no lifetime, so the borrow
/// checker cannot enforce the following requirements — the driver **must**:
///
/// - keep the source framebuffer borrowed (and **unmutated**) for the entire
/// duration `ptr` is used by the DMA/PIO/parallel peripheral;
/// - ensure the framebuffer is **not moved** while the transfer is live
/// (allocate it in `static` memory, or an embassy `StaticCell`/`Mutex`);
/// - treat `ptr` as aligned for the framebuffer's [`FrameBuffer::Word`], and
/// read at most `len` bytes from it.
/// Framebuffer that exposes its BCM scan sequence as an ordered series of
/// segments.
///
/// # Terminology
///
/// - **Segment** — the atomic unit, a [`BcmSegment`]: `len` bytes at
/// `ptr`, streamed `reps` times before the driver advances to the next
/// segment.
/// - **Sequence** — the repeating period of the scan:
/// [`BCM_SEQUENCE_LEN`](Self::BCM_SEQUENCE_LEN) consecutive segments
/// whose `len` and `reps` are given by
/// [`BCM_SEQUENCE`](Self::BCM_SEQUENCE). One complete panel refresh
/// consists of this sequence repeated
/// [`BCM_SEQUENCE_COUNT`](Self::BCM_SEQUENCE_COUNT) times.
/// - **Group** — an optional driver hint:
/// [`BCM_SEGMENTS_PER_GROUP`](Self::BCM_SEGMENTS_PER_GROUP) consecutive
/// segments that a driver *may* chain into a single DMA transfer.
/// Groups never straddle a sequence boundary.
///
/// ```text
/// one refresh = BCM_SEGMENT_COUNT segments
/// = BCM_SEQUENCE_COUNT repetitions of one sequence
/// one sequence = BCM_SEQUENCE_LEN segments (BCM_SEQUENCE)
/// one segment = len bytes, streamed reps times
/// ```
///
/// | Layout | One sequence is… | `BCM_SEQUENCE_LEN` | `BCM_SEQUENCE_COUNT` |
/// |--------|------------------|--------------------|----------------------|
/// | Frame-major bitplane | the whole frame | `PLANES` | `1` |
/// | Row-major bitplane | one row's BCM cycle | `PLANES + has_gap + has_tail` | `NROWS` |
/// | Threshold (`plain` / `latched`) | the whole frame | `1` | `1` |
///
/// Row-major framebuffers repeat the same `(len, reps)` pattern `NROWS`
/// times, so `BCM_SEQUENCE` holds one row's worth of entries instead of
/// the whole frame's.
///
/// # Segment Ordering
///
/// **Frame-major** (bitplane) framebuffers describe the whole frame in a
/// single sequence of `PLANES` segments (`BCM_SEQUENCE_LEN == PLANES`,
/// `BCM_SEQUENCE_COUNT == 1`). Planes are **LSB-first** and stored
/// contiguously, so each segment streams a whole *suffix* of planes: the
/// segment for plane `k` starts at plane `k`, covers the remaining planes,
/// and is repeated just enough times to bring plane `k`'s total coverage
/// to `2^k`:
///
/// ```text
/// segment 0: (plane0_ptr, PLANES*plane_bytes, 1) // LSB; all planes
/// segment 1: (plane1_ptr, (PLANES-1)*plane_bytes, 1)
/// segment 2: (plane2_ptr, (PLANES-2)*plane_bytes, 2)
/// …
/// segment N: (planeN_ptr, plane_bytes, 2^(PLANES-2)) // MSB
/// ```
///
/// **Row-major** framebuffers repeat one sequence per row
/// (`BCM_SEQUENCE_COUNT == NROWS`). Planes are **LSB-first** within each
/// row and stored contiguously. The inter-row gap segment sits between
/// plane 0 and plane 1 — the point where the row address changes; with a
/// gap enabled, plane 0 stands alone and plane 1's segment gets 2 reps:
///
/// ```text
/// sequence 0 (row 0):
/// (row0_plane0_ptr, PLANES*pixel_bytes, 1)
/// (row0_gap_ptr, gap_bytes, 1) // if enabled
/// (row0_plane1_ptr, (PLANES-1)*pixel_bytes, 1|2) // 2 reps if gap
/// …
/// (row0_planeN_ptr, pixel_bytes, 2^(PLANES-2))
/// (row0_trailer_ptr, trailer_bytes, 1) // if enabled
/// sequence 1 (row 1):
/// …
/// ```
///
/// **Threshold-based** framebuffers produce a single segment with
/// `reps = 1` covering the entire buffer.
/// Sum of `reps` across one complete panel refresh.
///
/// Useful for sizing DMA descriptor tables when the hardware uses one
/// descriptor per repetition (e.g. esp32 DMA and stm32 GPDMA linked-list mode).
pub const
/// Trait for mutable framebuffers that support `embedded_graphics` drawing.
/// Trait for all operations a user may want to call on a framebuffer.