-
Notifications
You must be signed in to change notification settings - Fork 4
/
display_output.cpp
1350 lines (1173 loc) · 51.3 KB
/
display_output.cpp
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 "display_output.h"
#include <drm/drm.h>
#include <drm_fourcc.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <unistd.h>
#include <cctype>
#include <cmath>
#include <map>
#include <mutex>
#include <optional>
#include <set>
#include <system_error>
#include <type_traits>
#include <fmt/core.h>
#include "logging_policy.h"
#include "unix_system.h"
namespace pivid {
namespace {
auto const& display_logger() {
static const auto logger = make_logger("display");
return logger;
}
//
// Helpers for KMS/DRM interface
//
// Support KMS/DRM ioctl conventions for variable size arrays;
// returns true if the ioctl needs to be re-submitted with a resized array.
template <typename Pointer, typename Count, typename Item>
bool size_vec(Pointer* ptr, Count* count, std::vector<Item>* v) {
if (*count == v->size() && *ptr == (Pointer) v->data()) return false;
v->resize(*count);
*ptr = (Pointer) v->data();
return true;
}
DisplayMode mode_from_drm(drm_mode_modeinfo const& drm) {
auto const sign = [&drm](uint32_t nflag, uint32_t pflag) -> int8_t {
return (drm.flags & nflag) ? -1 : (drm.flags & pflag) ? +1 : 0;
};
// Note, drm.name is just WxH[i], not worth capturing.
return {
.size = {drm.hdisplay, drm.vdisplay},
.scan_size = {drm.htotal, drm.vtotal},
.sync_start = {drm.hsync_start, drm.vsync_start},
.sync_end = {drm.hsync_end, drm.vsync_end},
.sync_polarity = {
sign(DRM_MODE_FLAG_NHSYNC, DRM_MODE_FLAG_PHSYNC),
sign(DRM_MODE_FLAG_NVSYNC, DRM_MODE_FLAG_PVSYNC),
},
.doubling = {
sign(DRM_MODE_FLAG_CLKDIV2, DRM_MODE_FLAG_DBLCLK),
sign(DRM_MODE_FLAG_INTERLACE, DRM_MODE_FLAG_DBLSCAN),
},
.aspect =
(drm.flags & DRM_MODE_FLAG_PIC_AR_4_3) ? XY<int>{4, 3} :
(drm.flags & DRM_MODE_FLAG_PIC_AR_16_9) ? XY<int>{16, 9} :
(drm.flags & DRM_MODE_FLAG_PIC_AR_64_27) ? XY<int>{64, 27} :
(drm.flags & DRM_MODE_FLAG_PIC_AR_256_135) ? XY<int>{256, 135} :
XY<int>{},
.pixel_khz = int(drm.clock),
.nominal_hz = int(drm.vrefresh),
};
}
drm_mode_modeinfo mode_to_drm(DisplayMode const& mode) {
return {
.clock = uint32_t(mode.pixel_khz),
.hdisplay = uint16_t(mode.size.x),
.hsync_start = uint16_t(mode.sync_start.x),
.hsync_end = uint16_t(mode.sync_end.x),
.htotal = uint16_t(mode.scan_size.x),
.hskew = 0,
.vdisplay = uint16_t(mode.size.y),
.vsync_start = uint16_t(mode.sync_start.y),
.vsync_end = uint16_t(mode.sync_end.y),
.vtotal = uint16_t(mode.scan_size.y),
.vscan = uint16_t(mode.doubling.y ? 2 : 1),
.vrefresh = uint32_t(mode.nominal_hz),
.flags = uint32_t(
(mode.sync_polarity.x > 0 ? DRM_MODE_FLAG_PHSYNC : 0) |
(mode.sync_polarity.x < 0 ? DRM_MODE_FLAG_NHSYNC : 0) |
(mode.sync_polarity.y > 0 ? DRM_MODE_FLAG_PVSYNC : 0) |
(mode.sync_polarity.y < 0 ? DRM_MODE_FLAG_NVSYNC : 0) |
(mode.doubling.y < 0 ? DRM_MODE_FLAG_INTERLACE : 0) |
(mode.doubling.y > 0 ? DRM_MODE_FLAG_DBLSCAN : 0) |
(mode.doubling.x > 0 ? DRM_MODE_FLAG_DBLCLK : 0) |
(mode.doubling.x < 0 ? DRM_MODE_FLAG_CLKDIV2 : 0) |
(mode.aspect == XY<int>{4, 3} ? DRM_MODE_FLAG_PIC_AR_4_3 : 0) |
(mode.aspect == XY<int>{16, 9} ? DRM_MODE_FLAG_PIC_AR_16_9 : 0) |
(mode.aspect == XY<int>{64, 27} ? DRM_MODE_FLAG_PIC_AR_64_27 : 0) |
(mode.aspect == XY<int>{256, 135} ? DRM_MODE_FLAG_PIC_AR_256_135 : 0)
),
.type = uint32_t(DRM_MODE_TYPE_USERDEF),
.name = {},
};
}
uint32_t format_to_drm(uint32_t format) {
// Note, ffmpeg/AVI/"standard" fourcc is big endian, DRM is little endian
// We use "rgb" for premultiplied-alpha components, which DRM expects.
switch (format) {
case fourcc("0BGR"): return DRM_FORMAT_RGBX8888;
case fourcc("0RGB"): return DRM_FORMAT_BGRX8888;
case fourcc("Abgr"): return DRM_FORMAT_RGBA8888;
case fourcc("Argb"): return DRM_FORMAT_BGRA8888;
case fourcc("BGR0"): return DRM_FORMAT_XRGB8888;
case fourcc("bgrA"): return DRM_FORMAT_ARGB8888;
case fourcc("BGR\x10"): return DRM_FORMAT_BGR565;
case fourcc("BGR\x18"): return DRM_FORMAT_RGB888;
case fourcc("I420"): return DRM_FORMAT_YUV420;
case fourcc("NV12"): return DRM_FORMAT_NV12;
case fourcc("NV21"): return DRM_FORMAT_NV21;
case fourcc("PAL\x08"): return DRM_FORMAT_C8;
case fourcc("RGB0"): return DRM_FORMAT_XBGR8888;
case fourcc("rgbA"): return DRM_FORMAT_ABGR8888;
case fourcc("RGB\x10"): return DRM_FORMAT_RGB565;
case fourcc("RGB\x18"): return DRM_FORMAT_BGR888;
case fourcc("Y42B"): return DRM_FORMAT_YUV422;
default: return format; // Might match!
}
}
void to_premultiplied_rgba(
uint32_t format, int width, uint8_t const* from, uint8_t* to
) {
switch (format) {
case fourcc("ABGR"):
for (int x = 0; x < width; ++x) {
uint8_t const alpha = to[3 + 4 * x] = from[4 * x];
to[0 + 4 * x] = from[3 + 4 * x] * alpha / 255;
to[1 + 4 * x] = from[2 + 4 * x] * alpha / 255;
to[2 + 4 * x] = from[1 + 4 * x] * alpha / 255;
}
break;
case fourcc("ARGB"):
for (int x = 0; x < width; ++x) {
uint8_t const alpha = to[3 + 4 * x] = from[4 * x];
to[0 + 4 * x] = from[1 + 4 * x] * alpha / 255;
to[1 + 4 * x] = from[2 + 4 * x] * alpha / 255;
to[2 + 4 * x] = from[3 + 4 * x] * alpha / 255;
}
break;
case fourcc("RGBA"):
for (int x = 0; x < width; ++x) {
uint8_t const alpha = to[3 + 4 * x] = from[3 + 4 * x];
to[0 + 4 * x] = from[0 + 4 * x] * alpha / 255;
to[1 + 4 * x] = from[1 + 4 * x] * alpha / 255;
to[2 + 4 * x] = from[2 + 4 * x] * alpha / 255;
}
break;
case fourcc("BGRA"):
for (int x = 0; x < width; ++x) {
uint8_t const alpha = to[3 + 4 * x] = from[3 + 4 * x];
to[0 + 4 * x] = from[2 + 4 * x] * alpha / 255;
to[1 + 4 * x] = from[1 + 4 * x] * alpha / 255;
to[2 + 4 * x] = from[0 + 4 * x] * alpha / 255;
}
break;
}
}
class DumbBuffer : public MemoryBuffer {
public:
DumbBuffer(std::shared_ptr<FileDescriptor> fd, XY<int> size, int bpp) {
ddat.height = size.y;
ddat.width = size.x;
ddat.bpp = bpp;
fd->ioc<DRM_IOCTL_MODE_CREATE_DUMB>(&ddat).ex("DRM buffer");
this->fd = std::move(fd);
}
virtual ~DumbBuffer() final {
if (!ddat.handle) return;
drm_mode_destroy_dumb dddat = {.handle = ddat.handle};
(void) fd->ioc<DRM_IOCTL_MODE_DESTROY_DUMB>(&dddat);
}
virtual int size() const final { return ddat.size; }
virtual uint8_t const* read() final {
std::scoped_lock const lock{mem_mutex};
if (!mem) {
drm_mode_map_dumb mdat = {};
mdat.handle = ddat.handle;
fd->ioc<DRM_IOCTL_MODE_MAP_DUMB>(&mdat).ex("Map DRM buffer");
mem = fd->mmap(
ddat.size, PROT_READ | PROT_WRITE, MAP_SHARED, mdat.offset
).ex("Memory map DRM buffer");
}
return (uint8_t const*) mem.get();
}
virtual uint32_t drm_handle() const final { return ddat.handle; }
uint8_t* write() { read(); return (uint8_t*) mem.get(); }
ptrdiff_t stride() const { return ddat.pitch; }
DumbBuffer(DumbBuffer const&) = delete;
DumbBuffer& operator=(DumbBuffer const&) = delete;
private:
std::shared_ptr<FileDescriptor> fd;
drm_mode_create_dumb ddat = {};
std::mutex mem_mutex;
std::shared_ptr<void> mem;
};
class ImportedBuffer {
public:
ImportedBuffer(std::shared_ptr<FileDescriptor> drm_fd, int dma_fd) {
hdat.fd = dma_fd;
drm_fd->ioc<DRM_IOCTL_PRIME_FD_TO_HANDLE>(&hdat).ex("Import DMA");
fd = std::move(drm_fd);
}
~ImportedBuffer() {
if (!hdat.handle) return;
drm_gem_close cdat = {.handle = hdat.handle, .pad = 0};
(void) fd->ioc<DRM_IOCTL_GEM_CLOSE>(cdat);
}
uint32_t drm_handle() const { return hdat.handle; }
ImportedBuffer(ImportedBuffer const&) = delete;
ImportedBuffer& operator=(ImportedBuffer const&) = delete;
private:
std::shared_ptr<FileDescriptor> fd;
drm_prime_handle hdat = {};
};
class LoadedImageDef : public LoadedImage {
public:
LoadedImageDef(std::shared_ptr<FileDescriptor> fd, ImageBuffer image) {
im = std::move(image);
CHECK_ARG(
im.channels.size() <= 4,
"Too many image channels ({}) for DRM", im.channels.size()
);
static_assert(std::extent_v<decltype(fdat.handles)> >= 4);
fdat.width = im.size.x;
fdat.height = im.size.y;
fdat.pixel_format = format_to_drm(im.fourcc);
fdat.flags = DRM_MODE_FB_MODIFIERS;
// Keep DMA-to-DRM imports until the ADDFB2 call which will ref them.
std::vector<std::unique_ptr<ImportedBuffer>> imports;
for (size_t ci = 0; ci < im.channels.size(); ++ci) {
auto const& ch = im.channels[ci];
auto const dma_fd = ch.memory->dma_fd();
auto const drm_handle = ch.memory->drm_handle();
CHECK_ARG(dma_fd >= 0 || drm_handle, "No DMA handle (ch{})", ci);
fdat.pitches[ci] = ch.stride;
fdat.offsets[ci] = ch.offset;
fdat.modifier[ci] = im.modifier;
// For the same memory buffer, reuse the handle & references.
for (size_t pci = 0; pci < ci; ++pci) {
if (ch.memory == im.channels[pci].memory) {
ASSERT(fdat.handles[pci]);
fdat.handles[ci] = fdat.handles[pci];
break;
}
}
if (fdat.handles[ci]) continue;
if (drm_handle) {
fdat.handles[ci] = drm_handle;
} else {
auto imp = std::make_unique<ImportedBuffer>(fd, dma_fd);
fdat.handles[ci] = imp->drm_handle();
imports.push_back(std::move(imp));
}
}
auto const logger = display_logger();
this->fd = std::move(fd);
TRACE(logger, "Loading framebuffer...", debug(im));
this->fd->ioc<DRM_IOCTL_MODE_ADDFB2>(&fdat).ex("DRM framebuffer");
DEBUG(logger, "LOADED fb{} {}", fdat.fb_id, debug(im));
}
~LoadedImageDef() {
if (!fdat.fb_id) return;
auto const logger = display_logger();
(void) fd->ioc<DRM_IOCTL_MODE_RMFB>(&fdat.fb_id);
TRACE(logger, "Unload fb{} {}x{}", fdat.fb_id, fdat.width, fdat.height);
}
virtual uint32_t drm_id() const final { return fdat.fb_id; }
virtual uint32_t drm_format() const final { return fdat.pixel_format; }
virtual ImageBuffer const& content() const { return im; }
LoadedImageDef(LoadedImageDef const&) = delete;
LoadedImageDef& operator=(LoadedImageDef const&) = delete;
private:
std::shared_ptr<FileDescriptor> fd;
drm_mode_fb_cmd2 fdat = {};
ImageBuffer im;
};
//
// DisplayDriver implementation
//
class DisplayDriverDef : public DisplayDriver {
public:
DisplayDriverDef() {}
virtual std::vector<DisplayScreen> scan_screens() final {
TRACE(logger, "Scanning screens...");
std::vector<DisplayScreen> out;
for (auto const& id_conn : connectors) {
drm_mode_get_connector cdat = {};
cdat.connector_id = id_conn.first;
std::vector<drm_mode_modeinfo> modes;
do {
TRACE(
logger, " (get connector {}, {} modes)",
cdat.connector_id, cdat.count_modes
);
cdat.count_props = cdat.count_encoders = 0;
fd->ioc<DRM_IOCTL_MODE_GETCONNECTOR>(&cdat).ex("DRM connector");
} while (size_vec(&cdat.modes_ptr, &cdat.count_modes, &modes));
DisplayScreen screen = {};
screen.id = id_conn.first;
screen.connector = id_conn.second.name;
screen.display_detected = (cdat.connection == 1);
for (auto const& mode : modes) {
if (!(mode.flags & DRM_MODE_FLAG_3D_MASK))
screen.modes.push_back(mode_from_drm(mode));
}
if (cdat.encoder_id) {
drm_mode_get_encoder edat = {};
edat.encoder_id = cdat.encoder_id;
TRACE(logger, " (get encoder {})", edat.encoder_id);
fd->ioc<DRM_IOCTL_MODE_GETENCODER>(&edat).ex("DRM encoder");
if (edat.crtc_id) {
// We are DRM master, assume no sneaky mode changes.
auto const& drm_mode = crtcs.at(edat.crtc_id).active.mode;
screen.active_mode = mode_from_drm(drm_mode);
}
}
out.push_back(std::move(screen));
}
logger->debug("Found {} display screens", out.size());
return out;
}
virtual std::unique_ptr<LoadedImage> load_image(ImageBuffer im) final {
TRACE(logger, "Loading start {}", debug(im));
CHECK_ARG(im.size.x > 0 && im.size.y > 0, "Bad size: {}", debug(im));
switch (im.fourcc) {
case fourcc("ABGR"):
case fourcc("ARGB"):
case fourcc("BGRA"):
case fourcc("RGBA"): {
TRACE(logger, " (premultiplying alpha...)");
CHECK_ARG(
im.channels.size() == 1,
"Bad channel count ({}) for {} image",
im.channels.size(), debug_fourcc(im.fourcc)
);
auto* chan = &im.channels[0];
auto const& [w, h] = im.size;
int const min_size = chan->offset + chan->stride * h;
CHECK_ARG(
chan->memory->size() >= min_size && chan->stride >= 4 * w,
"Bad buffer size ({}/{}) for {}x{} {} @{}",
debug_size(chan->memory->size()),
debug_size(chan->stride), w, h, debug_fourcc(im.fourcc),
debug_size(chan->offset)
);
auto buf = std::make_shared<DumbBuffer>(fd, im.size, 32);
uint8_t const* read_from = chan->memory->read() + chan->offset;
uint8_t* write_to = buf->write();
for (int y = 0; y < h; ++y) {
to_premultiplied_rgba(
im.fourcc, w,
read_from + y * chan->stride,
write_to + y * buf->stride()
);
}
chan->offset = 0;
chan->stride = buf->stride();
chan->memory = std::move(buf);
im.fourcc = fourcc("rgbA");
break;
}
case fourcc("PAL\x08"): {
TRACE(logger, " (expanding PAL8 to premultiplied rgbA...)");
CHECK_ARG(
im.channels.size() == 2,
"Bad channel count ({}) for PAL8 image", im.channels.size()
);
auto* chan = &im.channels[0];
auto const& [w, h] = im.size;
int const min_size = chan->offset + chan->stride * h;
CHECK_ARG(
chan->memory->size() >= min_size && chan->stride >= w,
"Bad buffer size ({}/{}) for {}x{} PAL8 @{}",
debug_size(chan->memory->size()),
debug_size(chan->stride), w, h, debug_size(chan->offset)
);
auto const& pchan = im.channels[1];
int const min_pchan_size = pchan.offset + 256 * 4;
CHECK_ARG(
pchan.memory->size() >= min_pchan_size,
"Bad palette size ({}) for PAL8 image @{}",
debug_size(pchan.memory->size()), debug_size(pchan.offset)
);
// TODO: On big-endian, this would be ARGB.
// https://ffmpeg.org/doxygen/3.3/pixfmt_8h.html
uint8_t pal[256 * 4];
to_premultiplied_rgba(
fourcc("BGRA"), 256,
pchan.memory->read() + pchan.offset, pal
);
auto buf = std::make_shared<DumbBuffer>(fd, im.size, 32);
uint8_t const* read_from = chan->memory->read() + chan->offset;
uint8_t* write_to = buf->write();
for (int y = 0; y < h; ++y) {
auto* line_from = read_from + y * chan->stride;
auto* line_to = write_to + y * buf->stride();
for (int x = 0; x < w; ++x)
std::memcpy(line_to + 4 * x, pal + 4 * line_from[x], 4);
}
chan->offset = 0;
chan->stride = buf->stride();
chan->memory = std::move(buf);
im.channels.resize(1);
im.fourcc = fourcc("rgbA");
break;
}
default: {
CHECK_ARG(
im.channels.size() <= 4,
"Too many image channels ({}) to copy", im.channels.size()
);
int total_space = 0, chan_space[4] = {};
for (size_t ci = 0; ci < im.channels.size(); ++ci) {
auto* const chan = &im.channels[ci];
auto const m = chan->memory;
if ((m->dma_fd() >= 0 || m->drm_handle()) && !m->pool_low())
continue; // No copy needed.
chan_space[ci] = (chan->size + 1023) / 1024 * 1024;
total_space += chan_space[ci];
}
if (!total_space) break; // No copying needed.
auto const start_mt = sys->clock(CLOCK_MONOTONIC);
auto const pixels = im.size.x * im.size.y;
auto copy = std::make_shared<DumbBuffer>(
fd, im.size, (8 * total_space + pixels - 1) / pixels
);
CHECK_RUNTIME(
copy->size() >= total_space,
"Buffer size={} < requested size={}",
copy->size(), total_space
);
int offset = 0, total_copy = 0;
auto* const out = copy->write();
for (size_t ci = 0; ci < im.channels.size(); ++ci) {
if (!chan_space[ci]) continue;
auto* const chan = &im.channels[ci];
auto const m = chan->memory;
memcpy(out + offset, m->read() + chan->offset, chan->size);
chan->memory = copy;
chan->offset = offset;
offset += chan_space[ci];
total_copy += chan->size;
}
TRACE(
logger, " copied {} {} {:.1f}ms",
debug_fourcc(im.fourcc), debug_size(total_copy),
(sys->clock(CLOCK_MONOTONIC) - start_mt) * 1e3
);
break;
}
}
return std::make_unique<LoadedImageDef>(fd, std::move(im));
}
virtual DisplayUpdated update(
uint32_t screen_id, DisplayFrame const& frame
) final {
auto* const conn = &connectors.at(screen_id);
auto cost = predict_cost(frame);
if (
cost.memory_bandwidth >= 1.0 ||
cost.compositor_bandwidth >= 1.0 ||
cost.line_buffer_memory >= 1.0
) {
logger->warn(
"Predicted overload {} {}l mbw={:.0f}% cbw={:.0f}% lbm={:.0f}%",
conn->name, frame.layers.size(), cost.memory_bandwidth * 100,
cost.compositor_bandwidth * 100, cost.line_buffer_memory * 100
);
for (auto const& layer : frame.layers) {
auto const layer_cost = predict_cost({frame.mode, {layer}});
logger->warn(
" {:4.1f}%m {:4.1f}%c {:4.1f}%l {}",
layer_cost.memory_bandwidth * 100,
layer_cost.compositor_bandwidth * 100,
layer_cost.line_buffer_memory * 100,
debug(layer)
);
}
} else {
DEBUG(
logger, "UPDATE {} {}l mbw={:.0f}% cbw={:.0f}% lbm={:.0f}%",
conn->name, frame.layers.size(), cost.memory_bandwidth * 100,
cost.compositor_bandwidth * 100, cost.line_buffer_memory * 100
);
}
for (auto const& warning : frame.warnings)
logger->warn("{} {}", conn->name, warning);
std::unique_lock lock{mutex};
auto* crtc = conn->using_crtc;
CHECK_ARG(
!crtc || !crtc->pending_flip,
"Update requested before prev done"
);
if (!crtc) {
if (!frame.mode.nominal_hz) {
DEBUG(logger, " ({} was off, staying off)", conn->name);
return {};
}
for (auto* const c : conn->usable_crtcs) {
if (c->used_by_conn) continue;
ASSERT(!c->pending_flip);
crtc = c;
break;
}
CHECK_RUNTIME(crtc, "No DRM CRTC: {}", conn->name);
}
// Build the atomic update and the state that will result.
std::map<uint32_t, std::map<PropId const*, uint64_t>> props;
std::shared_ptr<uint32_t const> mode_blob;
Crtc::State next = {};
int32_t writeback_fd = -1;
ASSERT(crtc);
if (!frame.mode.nominal_hz) {
DEBUG(logger, " ({} turning off)", conn->name);
props[conn->id][&conn->CRTC_ID] = 0;
props[crtc->id][&crtc->ACTIVE] = 0;
props[crtc->id][&crtc->MODE_ID] = 0;
// Leave next state zeroed (disassociate CRTC).
} else {
next.mode = mode_to_drm(frame.mode);
static_assert(sizeof(crtc->active.mode) == sizeof(next.mode));
if (memcmp(&crtc->active.mode, &next.mode, sizeof(next.mode))) {
DEBUG(logger, " {}: {}", conn->name, debug(frame.mode));
if (frame.mode.nominal_hz) mode_blob = create_blob(next.mode);
props[crtc->id][&crtc->ACTIVE] = frame.mode.nominal_hz ? 1 : 0;
props[crtc->id][&crtc->MODE_ID] = mode_blob ? *mode_blob : 0;
}
if (conn->WRITEBACK_FB_ID.prop_id) {
XY<int> const size = {next.mode.hdisplay, next.mode.vdisplay};
auto buf = std::make_shared<DumbBuffer>(fd, size, 32);
Writeback wb = {};
wb.image.fourcc = fourcc("RGBA");
wb.image.size = size;
wb.image.channels.resize(1);
wb.image.channels[0].stride = buf->stride();
wb.image.channels[0].memory = std::move(buf);
wb.fb_id = load_image(wb.image);
int const id = wb.fb_id->drm_id();
DEBUG(logger, " writeback: fb{} {}", id, debug(wb.image));
next.writeback = std::move(wb);
props[conn->id][&conn->WRITEBACK_FB_ID] = id;
props[conn->id][&conn->WRITEBACK_OUT_FENCE_PTR] =
(uint64_t) &writeback_fd;
}
if (!conn->using_crtc || next.writeback) {
props[conn->id][&conn->CRTC_ID] = crtc->id;
props[crtc->id][&crtc->ACTIVE] = 1;
}
int first_plane = true;
auto plane_iter = crtc->usable_planes.begin();
for (auto const& layer : frame.layers) {
// Don't send invisible layers to the compositor
// TODO: Also detect layers positioned fully off-screen?
if (!layer.to_size || layer.opacity <= 0) continue;
// Find an appropriate plane (Primary=1, Overlay=0)
uint64_t const wanted_type = first_plane ? 1 : 0;
for (;; ++plane_iter) {
CHECK_RUNTIME(
plane_iter != crtc->usable_planes.end(),
"No DRM plane: {}", conn->name
);
auto const* plane = (*plane_iter);
auto const type = plane->type.init_value;
auto const* used_by = plane->used_by_crtc;
if (type == wanted_type && (used_by == crtc || !used_by))
break;
// Disable any plane no longer used by this CRTC
if (used_by == crtc) {
DEBUG(logger, " pl{}: disable (skipped)", plane->id);
auto* plane_props = &props[plane->id];
(*plane_props)[&plane->CRTC_ID] = 0;
(*plane_props)[&plane->FB_ID] = 0;
}
}
first_plane = false;
auto* plane = *plane_iter++;
int const fb_id = layer.image->drm_id();
next.using_planes.push_back(plane);
next.images.push_back(layer.image);
DEBUG(logger, " pl{}: {}", plane->id, debug(layer));
auto* plane_props = &props[plane->id];
(*plane_props)[&plane->CRTC_ID] = crtc->id;
(*plane_props)[&plane->FB_ID] = fb_id;
(*plane_props)[&plane->SRC_X] = 65536.0 * layer.from_xy.x;
(*plane_props)[&plane->SRC_Y] = 65536.0 * layer.from_xy.y;
(*plane_props)[&plane->SRC_W] = 65536.0 * layer.from_size.x;
(*plane_props)[&plane->SRC_H] = 65536.0 * layer.from_size.y;
(*plane_props)[&plane->CRTC_X] = layer.to_xy.x;
(*plane_props)[&plane->CRTC_Y] = layer.to_xy.y;
(*plane_props)[&plane->CRTC_W] = layer.to_size.x;
(*plane_props)[&plane->CRTC_H] = layer.to_size.y;
if (plane->alpha.prop_id) {
(*plane_props)[&plane->alpha] = layer.opacity * 65535.0;
} else {
CHECK_RUNTIME(layer.opacity >= 1.0, "Alpha unsupported");
}
if (plane->rotation.prop_id) {
int rotation = 0;
if (layer.reflect) rotation |= DRM_MODE_REFLECT_X;
switch (layer.rotate) {
case 0: rotation |= DRM_MODE_ROTATE_0; break;
case 90: rotation |= DRM_MODE_ROTATE_270; break;
case 180: rotation |= DRM_MODE_ROTATE_180; break;
case 270: rotation |= DRM_MODE_ROTATE_90; break;
default:
CHECK_RUNTIME(0, "Bad rotation {}", layer.rotate);
break;
}
(*plane_props)[&plane->rotation] = rotation;
} else {
CHECK_RUNTIME(layer.rotate == 0, "Rotation unsupported");
CHECK_RUNTIME(!layer.reflect, "Reflection unsupported");
}
}
// Disable any other planes no longer used by this CRTC
for (; plane_iter != crtc->usable_planes.end(); ++plane_iter) {
auto const* plane = (*plane_iter);
if (plane->used_by_crtc == crtc) {
DEBUG(logger, " pl{}: disable (leftover)", plane->id);
auto* plane_props = &props[plane->id];
(*plane_props)[&plane->CRTC_ID] = 0;
(*plane_props)[&plane->FB_ID] = 0;
}
}
}
if (props.empty()) {
TRACE(logger, " {} unchanged!", conn->name);
ASSERT(conn->using_crtc == crtc);
ASSERT(crtc->used_by_conn == conn);
ASSERT(!crtc->pending_flip);
crtc->active = std::move(next);
return {};
}
conn->using_crtc = crtc;
crtc->used_by_conn = conn;
crtc->pending_flip.emplace(std::move(next));
crtc->vblank_event.reset();
for (auto* plane : crtc->pending_flip->using_planes) {
ASSERT(plane->used_by_crtc == crtc || !plane->used_by_crtc);
plane->used_by_crtc = crtc;
}
//
// UNLOCK for blocking commit
//
lock.unlock();
std::vector<uint32_t> obj_ids;
std::vector<uint32_t> obj_prop_counts;
std::vector<uint32_t> prop_ids;
std::vector<uint64_t> prop_values;
for (auto const& obj_props : props) {
obj_ids.push_back(obj_props.first);
obj_prop_counts.push_back(obj_props.second.size());
for (auto const& prop_value : obj_props.second) {
TRACE(
logger, " #{} {} = {}", obj_props.first,
prop_value.first->name, prop_value.second
);
prop_ids.push_back(prop_value.first->prop_id);
prop_values.push_back(prop_value.second);
}
}
drm_mode_atomic atomic = {
.flags =
DRM_MODE_PAGE_FLIP_EVENT |
DRM_MODE_ATOMIC_ALLOW_MODESET,
.count_objs = (uint32_t) obj_ids.size(),
.objs_ptr = (uint64_t) obj_ids.data(),
.count_props_ptr = (uint64_t) obj_prop_counts.data(),
.props_ptr = (uint64_t) prop_ids.data(),
.prop_values_ptr = (uint64_t) prop_values.data(),
.reserved = 0,
.user_data = update_sequence++,
};
DEBUG(logger, " {} u{} committing...", conn->name, atomic.user_data);
auto const result = fd->ioc<DRM_IOCTL_MODE_ATOMIC>(&atomic);
TRACE(
logger, " {} u{} commit done (err={})",
conn->name, atomic.user_data, result.err
);
std::unique_ptr<FileDescriptor> writeback_fence;
if (writeback_fd >= 0) writeback_fence = sys->adopt(writeback_fd);
//
// RE-LOCK after blocking commit
//
lock.lock();
ASSERT(conn->using_crtc == crtc);
ASSERT(crtc->used_by_conn == conn);
// If update failed, clear the pending flip value.
if (result.err) {
crtc->pending_flip.reset();
result.check("DRM atomic update"); // Throws an exception
}
// Read and store events until we've seen one for this CRTC
while (!crtc->vblank_event) {
drm_event_vblank ev = {};
do {
auto const len = fd->read(&ev, sizeof(ev)).ex("Read DRM event");
CHECK_RUNTIME(len == sizeof(ev), "Bad DRM event size");
} while (ev.base.type != DRM_EVENT_FLIP_COMPLETE);
auto* const crtc = &crtcs.at(ev.crtc_id);
CHECK_RUNTIME(
crtc->pending_flip && crtc->used_by_conn && !crtc->vblank_event,
"Unexpected DRM CRTC pageflip ({})", crtc->id
);
crtc->vblank_event = std::move(ev);
}
auto const& ev = *crtc->vblank_event;
DisplayUpdated done = {};
do {
double const flip_mt = ev.tv_sec + 1e-6 * ev.tv_usec;
double const mt0 = sys->clock(CLOCK_MONOTONIC);
double const rt1 = sys->clock();
double const mt2 = sys->clock(CLOCK_MONOTONIC);
ASSERT(mt2 >= mt0);
if (mt2 - mt0 > 0.001) {
TRACE(logger, "Clock jump: m{:.6f} => m{:.6f}", mt0, mt2);
} else {
done.flip_time = flip_mt - 0.5 * (mt0 + mt2) + rt1;
}
DEBUG(
logger, "{} u{} done! {} (m{:.3f})",
conn->name, ev.user_data,
abbrev_realtime(done.flip_time), flip_mt
);
} while (done.flip_time == 0.0);
if (!crtc->pending_flip->mode.vrefresh) {
TRACE(logger, " (display is off)", conn->name);
ASSERT(conn->using_crtc == crtc);
ASSERT(crtc->pending_flip->using_planes.empty());
conn->using_crtc = nullptr;
crtc->used_by_conn = nullptr;
}
for (auto* plane : crtc->pending_flip->using_planes)
ASSERT(plane->used_by_crtc == crtc);
for (auto* plane : crtc->active.using_planes) {
ASSERT(plane->used_by_crtc == crtc);
plane->used_by_crtc = nullptr;
}
for (auto* plane : crtc->pending_flip->using_planes)
plane->used_by_crtc = crtc;
crtc->active = std::move(*crtc->pending_flip);
crtc->pending_flip.reset();
ASSERT(!crtc->used_by_conn || crtc->used_by_conn == conn);
ASSERT(!conn->using_crtc || conn->using_crtc == crtc);
if (writeback_fence) {
TRACE(logger, " (writeback fd={})", writeback_fence->raw_fd());
// TODO: Read from writeback fence
// (see https://forums.raspberrypi.com/viewtopic.php?t=328068)
}
return done;
}
virtual DisplayCost predict_cost(DisplayFrame const& frame) const final {
// These calculations are all RPi 4B specific. TODO: Generalize?
DisplayCost out = {};
for (auto const& layer : frame.layers) {
// Skip invisible frames (matching logic to skip them in update())
if (!layer.to_size || layer.opacity <= 0) continue;
auto const& image = layer.image->content();
auto const image_pix = image.size.x * image.size.y;
if (image_pix <= 0) continue;
int image_bytes = 0;
for (auto const& chan : image.channels) image_bytes += chan.size;
auto const pix_bytes = (image_bytes + image_pix - 1) / image_pix;
// https://github.com/raspberrypi/linux/blob/rpi-5.15.y/drivers/gpu/drm/vc4/vc4_plane.c#:~:text=vc4_plane_calc_load
if (layer.to_size.y <= 0) continue;
out.memory_bandwidth +=
std::ceil(layer.from_size.x) * std::ceil(layer.from_size.y)
* std::ceil(layer.from_size.y / layer.to_size.y) * pix_bytes;
bool scaled_uv = false;
switch (image.fourcc) {
case fourcc("I420"):
case fourcc("NV12"):
case fourcc("NV21"):
case fourcc("Y42B"):
scaled_uv = true;
}
bool const scaled = scaled_uv || layer.from_size != layer.to_size;
out.compositor_bandwidth +=
layer.to_size.x * layer.to_size.y * (scaled ? 0.5 : 0.25);
// https://github.com/raspberrypi/linux/blob/rpi-5.15.y/drivers/gpu/drm/vc4/vc4_plane.c#:~:text=vc4_lbm_size
// https://github.com/raspberrypi/linux/blob/rpi-5.15.y/drivers/gpu/drm/vc4/vc4_plane.c#:~:text=vc4_get_scaling_mode
if (scaled_uv || layer.from_size.y != layer.to_size.y) {
int const line_pix = // Dest if TPZ, source otherwise
3 * layer.to_size.x < 2 * layer.from_size.x
? layer.to_size.x : std::ceil(layer.from_size.x);
int const lbm_pix = // 2x if TPZ, 4x otherwise
(!scaled_uv && 3 * layer.to_size.y < 2 * layer.from_size.y)
? line_pix * 2 : line_pix * 4;
// Align to 128 bytes (32 pixels, 8 "words")
out.line_buffer_memory += (lbm_pix + 31) / 32 * 32;
}
}
// https://github.com/raspberrypi/linux/blob/rpi-5.15.y/drivers/gpu/drm/vc4/vc4_kms.c#:~:text=vc4_load_tracker_atomic_check
// Empirically, the Pi4 can do ~150% the Pi3, despite 2x clock??
out.compositor_bandwidth *= frame.mode.actual_hz() / (340 * 1000000.0);
// https://forums.raspberrypi.com/viewtopic.php?t=271121
// Empirically, Pi4 has ~2x Pi3's bandwidth, and indeed 2x1.5GB=3.0GB
// seems to be around where HVS underruns start creeping in.
out.memory_bandwidth *= frame.mode.actual_hz() / (3072 * 1048576.0);
// https://github.com/raspberrypi/linux/blob/rpi-5.15.y/drivers/gpu/drm/vc4/vc4_hvs.c#:~:text=60k%20words
// The *2 is because both the old & new config must be allocated.
out.line_buffer_memory *= 2.0 / (60 * 1024);
return out;
}
void open(std::shared_ptr<UnixSystem> sys, std::string const& dev) {
logger->info("Opening display \"{}\"...", dev);
this->sys = std::move(sys);
fd = this->sys->open(dev.c_str(), O_RDWR).ex(dev);
try {
fd->ioc<DRM_IOCTL_SET_MASTER>().ex("DRM master mode");
} catch (std::system_error const& e) {
logger->error("{}", e.what());
// Continue, though something will probably fail later
}
fd->ioc<DRM_IOCTL_SET_CLIENT_CAP>(
drm_set_client_cap{DRM_CLIENT_CAP_ATOMIC, 1}
).ex("Enable DRM atomic modesetting");
fd->ioc<DRM_IOCTL_SET_CLIENT_CAP>(
drm_set_client_cap{DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1}
).ex("Enable DRM universal planes");
fd->ioc<DRM_IOCTL_SET_CLIENT_CAP>(
drm_set_client_cap{DRM_CLIENT_CAP_WRITEBACK_CONNECTORS, 1}
).ex("Enable DRM universal planes");
drm_mode_card_res res = {};
std::vector<uint32_t> crtc_ids, conn_ids;
do {
res.count_fbs = res.count_encoders = 0; // Don't use these.
fd->ioc<DRM_IOCTL_MODE_GETRESOURCES>(&res).ex("DRM resources");
} while (
size_vec(&res.crtc_id_ptr, &res.count_crtcs, &crtc_ids) +
size_vec(&res.connector_id_ptr, &res.count_connectors, &conn_ids)
);
for (auto const crtc_id : crtc_ids) {
drm_mode_crtc ccdat = {};
ccdat.crtc_id = crtc_id;
fd->ioc<DRM_IOCTL_MODE_GETCRTC>(&ccdat).ex("DRM CRTC");
auto* crtc = &crtcs[crtc_id];
crtc->id = crtc_id;
lookup_required_prop_ids(crtc_id, &crtc->prop_ids);
if (ccdat.mode_valid) // Round-trip to ensure struct memcmp().
crtc->active.mode = mode_to_drm(mode_from_drm(ccdat.mode));
}
for (auto const conn_id : conn_ids) {
drm_mode_get_connector cdat = {};
cdat.connector_id = conn_id;
std::vector<uint32_t> enc_ids;
do {
cdat.count_props = cdat.count_modes = 0;
fd->ioc<DRM_IOCTL_MODE_GETCONNECTOR>(&cdat).ex("DRM conn");
} while (
size_vec(&cdat.encoders_ptr, &cdat.count_encoders, &enc_ids)
);
auto* conn = &connectors[conn_id];
conn->id = conn_id;
lookup_required_prop_ids(conn_id, &conn->prop_ids);
lookup_prop_ids(conn_id, &conn->opt_ids);
switch (cdat.connector_type) {
case DRM_MODE_CONNECTOR_HDMIA: conn->name = "HDMI"; break;
#define T(x) case DRM_MODE_CONNECTOR_##x: conn->name = #x; break
T(Unknown);
T(VGA);
T(DVII);
T(DVID);