Repository navigation
Expand file tree
/
Copy pathPanelDisplay.cpp
More file actions
1864 lines (1771 loc) · 63.7 KB
/
Copy pathPanelDisplay.cpp
File metadata and controls
1864 lines (1771 loc) · 63.7 KB
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
#include "PanelDisplay.h"
#include "DekiGPIO.h" // from deki-gpio
#include <deki/LogSystem.h>
#include <deki/Time.h>
#include <deki/providers/Memory.h>
#include <algorithm>
#include <cstring>
namespace DekiDisplay
{
namespace
{
const PanelDisplay::WorkerBackend* s_Worker = nullptr;
inline uint16_t SwapBytes16(uint16_t v)
{
return static_cast<uint16_t>((v >> 8) | (v << 8));
}
// Swaps the bytes of `pixels` RGB565 pixels in place, two at a time.
void SwapPixels(uint16_t* p, size_t pixels)
{
if (pixels == 0)
{
return;
}
if (reinterpret_cast<uintptr_t>(p) & 2)
{
*p = SwapBytes16(*p);
++p;
--pixels;
}
auto* words = reinterpret_cast<uint32_t*>(p);
for (size_t i = 0; i < pixels / 2; ++i)
{
const uint32_t v = words[i];
words[i] = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);
}
if (pixels & 1)
{
p[pixels - 1] = SwapBytes16(p[pixels - 1]);
}
}
// An overlay pixel (ARGB8888, alpha not 0) over an RGB565 one, both values in
// the CPU's byte order.
inline uint16_t BlendOverlayPixel(uint16_t bg, uint32_t argb)
{
if ((argb & 0xFF000000) == 0xFF000000)
{
return static_cast<uint16_t>(((argb >> 8) & 0xF800) | ((argb >> 5) & 0x07E0) | ((argb >> 3) & 0x001F));
}
const uint8_t alpha = argb >> 24;
const uint8_t r = (argb >> 16) & 0xFF;
const uint8_t g = (argb >> 8) & 0xFF;
const uint8_t b = argb & 0xFF;
const uint8_t bgR = (bg >> 8) & 0xF8;
const uint8_t bgG = (bg >> 3) & 0xFC;
const uint8_t bgB = (bg << 3) & 0xF8;
const uint8_t invAlpha = 255 - alpha;
const uint8_t outR = (r * alpha + bgR * invAlpha + 128) >> 8;
const uint8_t outG = (g * alpha + bgG * invAlpha + 128) >> 8;
const uint8_t outB = (b * alpha + bgB * invAlpha + 128) >> 8;
return static_cast<uint16_t>(((outR & 0xF8) << 8) | ((outG & 0xFC) << 3) | (outB >> 3));
}
// Finds where a row of the overlay is not fully transparent.
void MeasureOverlayRow(const uint32_t* row, int width, uint16_t& left, uint16_t& right)
{
int l = 0;
while (l < width && (row[l] & 0xFF000000) == 0)
{
++l;
}
int r = width;
while (r > l && (row[r - 1] & 0xFF000000) == 0)
{
--r;
}
left = static_cast<uint16_t>(l);
right = static_cast<uint16_t>(r);
}
} // namespace
PanelDisplay::PanelDisplay(PanelController& controller, IPanelIO& io)
: m_Controller(controller),
m_IO(io)
{
}
PanelDisplay::~PanelDisplay()
{
Shutdown();
}
bool PanelDisplay::Start(const Options& options)
{
if (m_Initialized)
{
return true;
}
m_Options = options;
m_Width = m_Controller.GetWidth();
m_Height = m_Controller.GetHeight();
if (m_Width <= 0 || m_Height <= 0)
{
DEKI_LOG_ERROR("PanelDisplay: the panel has no size (%dx%d)", (int)m_Width, (int)m_Height);
return false;
}
m_WireBigEndian = m_IO.PixelsBigEndian() != options.swapBytes;
m_SwapRGB565 = m_WireBigEndian != Deki::kRGB565BigEndian;
m_PanelWidth = m_Width;
m_PanelHeight = m_Height;
// May turn the controller to its own orientation, so before anything is
// sized by it or sent.
StartTearFree(options.tePin, options.scanlineSync);
// A band is at most one transfer, and a whole number of rows.
const size_t rowBytes = static_cast<size_t>(m_PanelWidth) * sizeof(uint16_t);
const size_t maxRows = std::max<size_t>(1, m_IO.GetMaxChunkBytes() / rowBytes);
m_BandRows = static_cast<int32_t>(std::clamp<size_t>(options.bandRows > 0 ? options.bandRows : 16, 1, maxRows));
if (!EnsureBands())
{
return false;
}
if (options.usePsram || options.doubleBuffer)
{
// The engine draws into these, and they are sent by DMA like the
// bands, so they must be DMA-capable wherever they live.
const size_t bytes = static_cast<size_t>(m_Width) * m_Height * sizeof(uint16_t);
const Deki::Memory::Region region = options.usePsram ? Deki::Memory::External : Deki::Memory::Internal;
for (int i = 0; i < (options.doubleBuffer ? 2 : 1); ++i)
{
m_RenderBuffers[i] = static_cast<uint16_t*>(Deki::Memory::AllocateDma(bytes, region));
if (!m_RenderBuffers[i])
{
DEKI_LOG_WARNING("PanelDisplay: no room for render buffer %d (%zu bytes, %s); %s", i, bytes,
options.usePsram ? "external" : "internal",
i == 0 ? "the engine draws into its own" : "one buffer only");
break;
}
memset(m_RenderBuffers[i], 0, bytes);
}
}
m_Initialized = true;
DekiGpio::IDekiGPIO* gpio = DekiGpio::DekiGPIO::GetCurrent();
if (gpio && options.backlightPin >= 0)
{
gpio->SetOutput(options.backlightPin, options.backlightInvert); // off while the panel is cleared
}
// The panel's memory holds noise at power-on: black before the light.
Clear();
SetBacklight(true);
// The bands come back on the first present that needs them. A frame
// drawn in strips never does: its strips are sent from their own copies,
// and 20 KB of internal RAM is the scene's.
FreeBands();
DEKI_LOG_INFO("PanelDisplay: %dx%d %s, bands of %d rows, %s on the wire", (int)m_Width, (int)m_Height,
m_Controller.GetInfo().name, (int)m_BandRows, m_SwapRGB565 ? "swapped" : "as drawn");
return true;
}
bool PanelDisplay::Initialize(int32_t, int32_t)
{
// The panel is started by DisplayPanelComponent, through Start().
DEKI_LOG_ERROR("PanelDisplay::Initialize() called directly - use the DisplayPanelComponent instead");
return false;
}
void PanelDisplay::Shutdown()
{
if (!m_Initialized)
{
return;
}
// The worker finishes what it was given and stops before anything it
// uses goes.
SetAsyncPresent(false);
m_IO.WaitPixels(0);
if (m_TePin >= 0 || m_Scanline)
{
DekiRendering::RegisterScanOrderedDisplay(this, nullptr);
DekiGpio::IDekiGPIO* gpio = DekiGpio::DekiGPIO::GetCurrent();
if (gpio && m_TePin >= 0)
{
gpio->StopCounting(m_TePin);
}
m_TePin = -1;
m_Scanline.reset();
}
FreeBands();
for (uint16_t*& buffer : m_RenderBuffers)
{
Deki::Memory::Free(buffer);
buffer = nullptr;
}
m_Initialized = false;
}
bool PanelDisplay::EnsureBands()
{
if (m_Band[0] && m_Band[1])
{
return true;
}
const size_t bytes = static_cast<size_t>(m_PanelWidth) * m_BandRows * sizeof(uint16_t);
for (uint16_t*& band : m_Band)
{
if (band)
{
continue;
}
// The panel reads the bands by DMA. Internal memory: some of the
// chip's RAM is out of a peripheral's reach, and DMA from it corrupts
// the display without an error.
band = static_cast<uint16_t*>(Deki::Memory::AllocateDma(bytes, Deki::Memory::Internal));
if (!band)
{
DEKI_LOG_ERROR("PanelDisplay: cannot allocate a %zu-byte band", bytes);
FreeBands();
return false;
}
}
return true;
}
void PanelDisplay::FreeBands()
{
for (uint16_t*& band : m_Band)
{
Deki::Memory::Free(band);
band = nullptr;
}
}
void PanelDisplay::Clear()
{
if (!EnsureBands())
{
return;
}
const size_t rowBytes = static_cast<size_t>(m_PanelWidth) * sizeof(uint16_t);
memset(m_Band[0], 0, rowBytes * m_BandRows);
m_Controller.BeginWrite();
m_Controller.SetWindow(0, 0, m_PanelWidth, m_PanelHeight);
// One band of black, sent as often as the screen needs; it never changes,
// so nothing waits for it to be free.
for (int32_t y = 0; y < m_PanelHeight; y += m_BandRows)
{
const int32_t rows = std::min(m_BandRows, m_PanelHeight - y);
m_IO.QueuePixels(m_Band[0], rowBytes * rows, y + rows < m_PanelHeight);
}
m_Controller.EndWrite();
}
void PanelDisplay::BlendOverlayRows(uint16_t* rows, size_t pitch, int width, int y0, int y1, bool swapped) const
{
if (!HasOverlay())
{
return;
}
// The overlay covers the screen from its top left corner.
const int w = std::min({ width, static_cast<int>(m_Width), static_cast<int>(m_ActiveOverlay->width) });
const int end = std::min({ y1, static_cast<int>(m_Height), static_cast<int>(m_ActiveOverlay->height) });
for (int y = y0 < 0 ? 0 : y0; y < end; ++y)
{
const int right = std::min(w, static_cast<int>(m_ActiveOverlay->spanRight[y]));
const uint32_t* overlayRow = m_ActiveOverlay->buffer + static_cast<size_t>(y) * m_ActiveOverlay->width;
uint16_t* dstRow = rows + static_cast<size_t>(y - y0) * pitch;
for (int x = m_ActiveOverlay->spanLeft[y]; x < right; ++x)
{
const uint32_t argb = overlayRow[x];
if ((argb & 0xFF000000) == 0)
{
continue;
}
const uint16_t bg = swapped ? SwapBytes16(dstRow[x]) : dstRow[x];
const uint16_t out = BlendOverlayPixel(bg, argb);
dstRow[x] = swapped ? SwapBytes16(out) : out;
}
}
}
void PanelDisplay::BeforeOverlayChange()
{
// Turned, the worker blends the overlay into what it sends; otherwise
// the drawing core blended it into its copy already.
if (m_Turned)
{
WaitForPresents();
}
}
void PanelDisplay::OverlayChanged()
{
// A frame that redraws only what changed sends only those parts: the rows
// the overlay covers, or covered, would keep what the panel shows now.
if (m_Initialized)
{
Deki::Engine::GetInstance().RequestFullRefresh();
}
}
void PanelDisplay::PushRows(const uint8_t* framebuffer, int width, int height, Deki::ColorFormat format, int y0, int y1,
bool blendOverlay)
{
m_Controller.BeginWrite();
PushRowsBody(framebuffer, width, height, format, y0, y1, blendOverlay);
m_Controller.EndWrite();
}
void PanelDisplay::PushRowsBody(const uint8_t* framebuffer, int width, int height, Deki::ColorFormat format, int y0,
int y1, bool blendOverlay)
{
if (!EnsureBands())
{
return;
}
const int w = std::min(width, static_cast<int>(m_Width));
y0 = std::max(y0, 0);
y1 = std::min({ y1, height, static_cast<int>(m_Height) });
if (y1 <= y0 || w <= 0)
{
return;
}
// One window for the whole run; the bands stream into it, each converted
// while the one before it is on the wire, from the other buffer.
m_Controller.SetWindow(0, y0, w, y1);
for (int y = y0; y < y1; y += m_BandRows)
{
const int rows = std::min(static_cast<int>(m_BandRows), y1 - y);
// The band about to be filled was queued two bands ago.
m_IO.WaitPixels(1);
uint16_t* band = m_Band[m_BandIndex];
for (int i = 0; i < rows; ++i)
{
uint16_t* dst = band + static_cast<size_t>(i) * w;
const int sy = y + i;
if (format == Deki::ColorFormat::RGB565)
{
const uint16_t* src = reinterpret_cast<const uint16_t*>(framebuffer) + static_cast<size_t>(sy) * width;
if (m_SwapRGB565)
{
for (int x = 0; x < w; ++x)
{
dst[x] = SwapBytes16(src[x]);
}
}
else
{
memcpy(dst, src, static_cast<size_t>(w) * sizeof(uint16_t));
}
}
else if (format == Deki::ColorFormat::ARGB8888)
{
const uint32_t* src = reinterpret_cast<const uint32_t*>(framebuffer) + static_cast<size_t>(sy) * width;
for (int x = 0; x < w; ++x)
{
const uint32_t p = src[x];
const uint16_t v =
static_cast<uint16_t>((((p >> 16) & 0xF8) << 8) | (((p >> 8) & 0xFC) << 3) | ((p & 0xFF) >> 3));
dst[x] = m_WireBigEndian ? SwapBytes16(v) : v;
}
}
else if (format == Deki::ColorFormat::RGB888)
{
const uint8_t* src = framebuffer + static_cast<size_t>(sy) * width * 3;
for (int x = 0; x < w; ++x)
{
const uint16_t v = static_cast<uint16_t>(((src[x * 3] & 0xF8) << 8) |
((src[x * 3 + 1] & 0xFC) << 3) | (src[x * 3 + 2] >> 3));
dst[x] = m_WireBigEndian ? SwapBytes16(v) : v;
}
}
else
{
memset(dst, 0, static_cast<size_t>(w) * sizeof(uint16_t));
}
}
if (blendOverlay)
{
// The band is in the wire's byte order.
BlendOverlayRows(band, w, w, y, y + rows, m_WireBigEndian);
}
m_IO.QueuePixels(band, static_cast<size_t>(rows) * w * sizeof(uint16_t), y + rows < y1);
m_BandIndex = 1 - m_BandIndex;
// The worker's last job finishes behind this band: its copy goes back
// to the drawing core now, not when this whole job is queued.
GiveBackPendingCopy();
}
}
void PanelDisplay::PushRowsDirect(const uint16_t* framebuffer, int y0, int y1)
{
m_Controller.BeginWrite();
PushRowsDirectBody(framebuffer, y0, y1);
// Ending the write waits for the last part: the frame is the engine's
// again when this returns.
m_Controller.EndWrite();
}
void PanelDisplay::PushRowsDirectBody(const uint16_t* frame, int y0, int y1)
{
// As long a part as the bus takes: the fewer parts, the less each one's
// start costs.
const size_t rowBytes = static_cast<size_t>(m_PanelWidth) * sizeof(uint16_t);
const int chunkRows = static_cast<int>(std::max<size_t>(1, m_IO.GetMaxChunkBytes() / rowBytes));
m_Controller.SetWindow(0, y0, m_PanelWidth, y1);
for (int y = y0; y < y1; y += chunkRows)
{
const int rows = std::min(chunkRows, y1 - y);
m_IO.QueuePixels(frame + static_cast<size_t>(y) * m_PanelWidth, rowBytes * rows, y + rows < y1);
// The worker's last job finishes behind this part.
GiveBackPendingCopy();
}
}
void PanelDisplay::CopyToWire(uint16_t* dst, const uint16_t* src, size_t pixels) const
{
if (!m_SwapRGB565)
{
memcpy(dst, src, pixels * sizeof(uint16_t));
return;
}
// Two pixels at a time, as SwapPixels does in place, when both ends are
// 4-byte aligned (a frame, a frame copy, and whole rows of an even width
// into them always are).
if ((reinterpret_cast<uintptr_t>(dst) | reinterpret_cast<uintptr_t>(src)) & 3)
{
for (size_t i = 0; i < pixels; ++i)
{
dst[i] = SwapBytes16(src[i]);
}
return;
}
auto* d = reinterpret_cast<uint32_t*>(dst);
const auto* s = reinterpret_cast<const uint32_t*>(src);
for (size_t i = 0; i < pixels / 2; ++i)
{
const uint32_t v = s[i];
d[i] = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);
}
if (pixels & 1)
{
dst[pixels - 1] = SwapBytes16(src[pixels - 1]);
}
}
void PanelDisplay::Present(const uint8_t* framebuffer, int width, int height, Deki::ColorFormat format)
{
const int lentFrame = TakeBackFrame(framebuffer);
if (!m_Initialized || !framebuffer)
{
return;
}
if (m_Turned)
{
if (format != Deki::ColorFormat::RGB565 || width != m_Width || height != m_Height)
{
if (lentFrame >= 0)
{
GiveBackCopy(lentFrame);
}
if (!m_TurnWarned)
{
DEKI_LOG_ERROR(
"PanelDisplay: a turned panel is sent RGB565 frames of its own size only (got format %d, "
"%dx%d)",
static_cast<int>(format), width, height);
m_TurnWarned = true;
}
return;
}
PresentTurned(reinterpret_cast<const uint16_t*>(framebuffer), width, 0, 0, width, height, 0, m_PanelHeight,
true, false, -1, lentFrame);
if (m_RenderBuffers[1])
{
m_RenderIndex = 1 - m_RenderIndex;
}
return;
}
// Async: the frame is copied for the worker, and the engine draws the
// next while it is sent. Waits only when both copies are in use.
// (The bands it is sent through are made here, on the drawing core: the
// worker never allocates.)
if (CanPresentAsync(framebuffer, width, height, format))
{
const int index = TakeCopy();
// Copied in the wire's byte order (swapped as it is copied, at about
// a copy's cost), so the worker sends the copy as it is, by DMA from
// external memory, in parts as long as the bus takes.
auto* copy = reinterpret_cast<uint16_t*>(m_Staging[index]);
CopyToWire(copy, reinterpret_cast<const uint16_t*>(framebuffer), static_cast<size_t>(width) * height);
BlendOverlayRows(copy, width, width, 0, height, m_WireBigEndian);
Post(Job{ index, 0, height, false, false, true });
return;
}
// Any other present goes after the worker's: it uses the bus and the
// bands.
WaitForPresents();
WaitForRefresh();
// Already in the wire's order, the panel's size and with nothing to blend
// over it: the frame goes out as it is, with no copy.
const bool direct =
format == Deki::ColorFormat::RGB565 && !m_SwapRGB565 && !HasOverlay() && width == m_Width && height == m_Height;
if (m_Presents++ == 0)
{
DEKI_LOG_INTERNAL("PanelDisplay: first present: fmt=%d %dx%d overlay=%d direct=%d", (int)format, width, height,
HasOverlay() ? 1 : 0, direct ? 1 : 0);
}
if (direct)
{
PushRowsDirect(reinterpret_cast<const uint16_t*>(framebuffer), 0, height);
}
else
{
PushRows(framebuffer, width, height, format, 0, height, true);
}
NotePartSent();
if (m_RenderBuffers[1])
{
m_RenderIndex = 1 - m_RenderIndex;
}
}
void PanelDisplay::PresentRegions(const uint8_t* framebuffer, int width, int height, Deki::ColorFormat format,
const Deki::Rect* rects, int32_t count)
{
PresentRegionsFrom(framebuffer, width, height, format, rects, count, true);
}
void PanelDisplay::PresentRegionsFrom(const uint8_t* framebuffer, int width, int height, Deki::ColorFormat format,
const Deki::Rect* rects, int32_t count, bool frameStart)
{
// A lent frame comes back here too, with something to send or nothing.
const int lentFrame = TakeBackFrame(framebuffer);
if (lentFrame >= 0 && (!m_Initialized || count == 0 || !m_Turned))
{
GiveBackCopy(lentFrame);
if (count == 0 || !m_Initialized)
{
return;
}
}
// Nothing changed on the panel, or (drawing in strips) every strip has
// been sent already: nothing to wait for either, so the strip the worker
// is still sending goes on while the next frame is drawn.
if (!m_Initialized || !framebuffer || count == 0)
{
return;
}
if (m_Turned)
{
if (format != Deki::ColorFormat::RGB565 || width != m_Width || height != m_Height)
{
if (!m_TurnWarned)
{
DEKI_LOG_ERROR(
"PanelDisplay: a turned panel is sent RGB565 frames of its own size only (got format %d, "
"%dx%d)",
static_cast<int>(format), width, height);
m_TurnWarned = true;
}
return;
}
// The panel rows the rectangles fall in: one run from the first to
// the last, which the whole frame has every pixel of.
int first = m_PanelHeight;
int last = 0;
for (int32_t i = 0; i < count; ++i)
{
if (rects[i].Empty())
{
continue;
}
int f = 0;
int l = 0;
PanelRowsOf(rects[i], &f, &l);
first = std::min(first, f);
last = std::max(last, l);
}
PresentTurned(reinterpret_cast<const uint16_t*>(framebuffer), width, 0, 0, width, height, first, last,
frameStart, false, -1, lentFrame);
if (m_RenderBuffers[1])
{
m_RenderIndex = 1 - m_RenderIndex;
}
return;
}
// One rectangle (a strip of a frame drawn in strips, or a frame where one
// thing moved) goes to the worker, and the engine draws on while it is
// sent.
if (count == 1 && !rects[0].Empty() &&
PresentRowsAsync(framebuffer, width, height, format, rects[0].top, rects[0].bottom, frameStart))
{
return;
}
// A window here spans whole rows, since the framebuffer's rows are only
// contiguous at full width, so rectangles become row bands.
MergeRowBands(rects, count, width, height);
if (m_BandScratch.empty())
{
return;
}
// Several rectangles (a frame where several things moved) go to the
// worker too: their rows into the same rows of a frame copy, in the
// wire's order, as one rectangle's do. Sending them here instead kept the
// drawing core busy for as long as the wire took.
if (count > 1 && CanPresentAsync(framebuffer, width, height, format))
{
const int index = TakeCopy();
m_CopyBands[index] = m_BandScratch;
const size_t pitch = static_cast<size_t>(width) * sizeof(uint16_t);
for (const Deki::Rect& band : m_BandScratch)
{
auto* copy = reinterpret_cast<uint16_t*>(m_Staging[index] + static_cast<size_t>(band.top) * pitch);
CopyToWire(copy, reinterpret_cast<const uint16_t*>(framebuffer + static_cast<size_t>(band.top) * pitch),
static_cast<size_t>(band.bottom - band.top) * width);
BlendOverlayRows(copy, width, width, band.top, band.bottom, m_WireBigEndian);
}
Job job{ index, m_BandScratch.front().top, m_BandScratch.back().bottom, false, false, frameStart };
job.bands = true;
Post(job);
return;
}
WaitForPresents();
if (frameStart)
{
WaitForRefresh();
}
const bool direct =
format == Deki::ColorFormat::RGB565 && !m_SwapRGB565 && !HasOverlay() && width == m_Width && height == m_Height;
for (const Deki::Rect& band : m_BandScratch)
{
if (direct)
{
PushRowsDirect(reinterpret_cast<const uint16_t*>(framebuffer), band.top, band.bottom);
}
else
{
PushRows(framebuffer, width, height, format, band.top, band.bottom, true);
}
}
NotePartSent();
if (m_RenderBuffers[1])
{
m_RenderIndex = 1 - m_RenderIndex;
}
}
void PanelDisplay::MergeRowBands(const Deki::Rect* rects, int32_t count, int width, int height)
{
const int32_t align = std::max<int32_t>(1, m_Controller.GetRowAlign());
m_BandScratch.clear();
for (int32_t i = 0; i < count; ++i)
{
const Deki::Rect& r = rects[i];
if (r.Empty())
{
continue;
}
const int32_t top = std::max<int32_t>(r.top - (r.top % align), 0);
const int32_t bottom = std::min<int32_t>(((r.bottom + align - 1) / align) * align, height);
if (bottom > top)
{
m_BandScratch.push_back(Deki::Rect{ 0, top, width, bottom });
}
}
std::sort(m_BandScratch.begin(), m_BandScratch.end(),
[](const Deki::Rect& a, const Deki::Rect& b) { return a.top < b.top; });
size_t out = 0;
for (size_t i = 0; i < m_BandScratch.size(); ++i)
{
if (out > 0 && m_BandScratch[i].top <= m_BandScratch[out - 1].bottom)
{
m_BandScratch[out - 1].bottom = std::max(m_BandScratch[out - 1].bottom, m_BandScratch[i].bottom);
}
else
{
m_BandScratch[out++] = m_BandScratch[i];
}
}
m_BandScratch.resize(out);
}
void PanelDisplay::GetDisplaySize(int32_t* width, int32_t* height) const
{
if (width)
{
*width = m_Width;
}
if (height)
{
*height = m_Height;
}
}
void* PanelDisplay::CreateUIOverlay(int32_t width, int32_t height)
{
if (!m_Initialized || width <= 0 || height <= 0)
{
DEKI_LOG_ERROR("PanelDisplay::CreateUIOverlay: display not started, or no size");
return nullptr;
}
auto* overlay = new UIOverlay();
overlay->width = width;
overlay->height = height;
const size_t bytes = static_cast<size_t>(width) * height * sizeof(uint32_t);
overlay->buffer = static_cast<uint32_t*>(Deki::Memory::Allocate(bytes, Deki::Memory::External));
if (!overlay->buffer)
{
DEKI_LOG_ERROR("PanelDisplay::CreateUIOverlay: no room for the overlay (%zu bytes)", bytes);
delete overlay;
return nullptr;
}
memset(overlay->buffer, 0, bytes);
overlay->spanLeft.assign(height, 0);
overlay->spanRight.assign(height, 0);
return overlay;
}
bool PanelDisplay::UpdateUIOverlay(void* overlay, int32_t x, int32_t y, int32_t width, int32_t height,
const uint32_t* pixels)
{
if (!overlay || !pixels)
{
return false;
}
auto* o = static_cast<UIOverlay*>(overlay);
BeforeOverlayChange();
if (x < 0 || y < 0 || width < 0 || height < 0 || x + width > o->width || y + height > o->height)
{
DEKI_LOG_WARNING("PanelDisplay::UpdateUIOverlay: bounds (%d,%d,%d,%d) outside the %dx%d overlay", x, y, width,
height, o->width, o->height);
return false;
}
for (int32_t row = 0; row < height; ++row)
{
uint32_t* dest = &o->buffer[static_cast<size_t>(y + row) * o->width + x];
memcpy(dest, &pixels[static_cast<size_t>(row) * width], static_cast<size_t>(width) * sizeof(uint32_t));
MeasureOverlayRow(&o->buffer[static_cast<size_t>(y + row) * o->width], o->width, o->spanLeft[y + row],
o->spanRight[y + row]);
}
if (o == m_ActiveOverlay)
{
OverlayChanged();
}
return true;
}
bool PanelDisplay::UpdateUIOverlayRGB565A8(void*, int32_t, int32_t, int32_t, int32_t, const uint8_t*)
{
return false;
}
void PanelDisplay::DestroyUIOverlay(void* overlay)
{
if (!overlay)
{
return;
}
auto* o = static_cast<UIOverlay*>(overlay);
BeforeOverlayChange();
if (o == m_ActiveOverlay)
{
// The rows it covered are sent again without it.
m_ActiveOverlay = nullptr;
OverlayChanged();
}
Deki::Memory::Free(o->buffer);
delete o;
}
void PanelDisplay::SetActiveUIOverlay(void* overlay)
{
if (m_ActiveOverlay == static_cast<UIOverlay*>(overlay))
{
return;
}
BeforeOverlayChange();
m_ActiveOverlay = static_cast<UIOverlay*>(overlay);
OverlayChanged();
}
void PanelDisplay::ClearActiveUIOverlay()
{
if (!HasOverlay())
{
return;
}
BeforeOverlayChange();
memset(m_ActiveOverlay->buffer, 0,
static_cast<size_t>(m_ActiveOverlay->width) * m_ActiveOverlay->height * sizeof(uint32_t));
std::fill(m_ActiveOverlay->spanRight.begin(), m_ActiveOverlay->spanRight.end(), 0);
OverlayChanged();
}
uint8_t* PanelDisplay::GetRenderBuffer(int32_t* width, int32_t* height)
{
// Offered wherever it lives. With usePsram the engine draws straight into
// PSRAM: slower to draw into than internal RAM, but a screen-sized buffer
// there leaves too little internal RAM for the scene.
if (!m_Initialized || !m_RenderBuffers[m_RenderIndex])
{
return nullptr;
}
if (width)
{
*width = m_Width;
}
if (height)
{
*height = m_Height;
}
return reinterpret_cast<uint8_t*>(m_RenderBuffers[m_RenderIndex]);
}
void PanelDisplay::SetBacklight(bool on)
{
DekiGpio::IDekiGPIO* gpio = DekiGpio::DekiGPIO::GetCurrent();
if (gpio && m_Options.backlightPin >= 0)
{
gpio->Write(m_Options.backlightPin, on != m_Options.backlightInvert);
return;
}
// No backlight (an AMOLED): the panel's own brightness, set between
// presents since it goes over the panel's bus.
if (m_Initialized && m_Controller.HasBrightness())
{
WaitForPresents();
m_Controller.SetBrightness(on ? m_Controller.GetInfo().onBrightness : 0);
}
}
bool PanelDisplay::SendCommand(uint8_t cmd, const uint8_t* params, size_t n)
{
if (!m_Initialized)
{
return false;
}
WaitForPresents();
return m_Controller.SendCommand(cmd, params, n);
}
// ---- Async present ----------------------------------------------------------
void PanelDisplay::SetWorkerBackend(const WorkerBackend* backend)
{
s_Worker = backend;
}
bool PanelDisplay::SetAsyncPresent(bool on)
{
if (!on)
{
if (m_Async)
{
WaitForPresents();
Post(Job{ 0, 0, 0, false, true });
std::unique_lock<std::mutex> lock(m_Lock);
m_CopyFree.wait(lock, [this] { return !m_WorkerRunning; });
}
for (uint8_t*& staging : m_Staging)
{
Deki::Memory::Free(staging);
staging = nullptr;
}
FreeStrips();
m_StagingBytes = 0;
m_NextCopy = 0;
m_Async = false;
return true;
}
if (m_Async)
{
return true;
}
if (!m_Initialized)
{
DEKI_LOG_ERROR("PanelDisplay: async present needs a started display");
return false;
}
if (!s_Worker || !s_Worker->start)
{
DEKI_LOG_INFO("PanelDisplay: this platform has no second core to send frames from; they are sent as they "
"are drawn");
return false;
}
// Two frames in external memory: the worker sends one while the engine
// copies the next frame into the other, then draws on into its own.
const size_t bytes = Deki::FrameBufferBytes(Deki::ColorFormat::RGB565, m_Width, m_Height);
for (uint8_t*& staging : m_Staging)
{
// DMA-capable: the worker sends straight from these.
staging = static_cast<uint8_t*>(Deki::Memory::AllocateDma(bytes, Deki::Memory::External));
}
if (!m_Staging[0] || !m_Staging[1])
{
DEKI_LOG_INFO("PanelDisplay: no external memory for two %zu-byte frame copies; frames are sent as they are "
"drawn",
bytes);
SetAsyncPresent(false);
return false;
}
m_StagingBytes = bytes;
{
std::lock_guard<std::mutex> lock(m_Lock);
m_JobHead = 0;
m_JobCount = 0;
m_FreeCopies = 2;
m_WorkerRunning = true;
}
if (!s_Worker->start(&PanelDisplay::WorkerMain, this))
{
{
std::lock_guard<std::mutex> lock(m_Lock);
m_WorkerRunning = false;
}
DEKI_LOG_INFO("PanelDisplay: the present worker did not start (one core?); frames are sent as they are "
"drawn");
SetAsyncPresent(false);
return false;
}
m_Async = true;
DEKI_LOG_INFO("PanelDisplay: frames are sent from the other core while the next is drawn");
return true;
}
void PanelDisplay::WorkerMain(void* self)
{
static_cast<PanelDisplay*>(self)->RunWorker();
}
void PanelDisplay::RunWorker()
{
// The worker holds the bus from one job to the next while jobs keep
// coming, so each job's window commands and first part are queued behind
// the one before while it is still on the wire, and the wire never waits
// between strips. A job's copy goes back to the drawing core once its
// parts are sent, which is found after the next job is queued, or when
// there is no next job: then everything is waited for, the copy given
// back and the bus let go, so the SD card and the radio get it between
// frames.
bool held = false;
uint32_t jobs = 0;
bool waitedForRefresh = false; // blocked since the last pause
for (;;)
{
Job job{};
{
std::unique_lock<std::mutex> lock(m_Lock);
if (m_JobCount == 0 && held)
{
lock.unlock();
m_Controller.EndWrite(); // waits for everything queued
held = false;
GiveBackPendingCopy();
continue;
}
m_JobReady.wait(lock, [this] { return m_JobCount > 0; });
job = m_Jobs[m_JobHead];
m_JobHead = (m_JobHead + 1) % 3;
--m_JobCount;
}
if (job.stop)
{
break; // posted after WaitForPresents: nothing is held or pending
}
// At full speed the next job is always waiting, so the worker never
// blocks and the core's idle task never runs, which a task watchdog
// reports. A pause every 30 jobs lets it; what is queued goes on.
// Waiting for the panel's refresh blocks every frame, and lets the
// idle task run then: a pause would only make a frame miss its
// refresh.
if (++jobs % 30 == 0)
{
if (!waitedForRefresh && s_Worker && s_Worker->yield)
{
s_Worker->yield();
}
waitedForRefresh = false;
}
// A frame waiting for the panel's refresh starts with the last one