-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathkmsgrab.cpp
1740 lines (1428 loc) · 57.7 KB
/
kmsgrab.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
/**
* @file src/platform/linux/kmsgrab.cpp
* @brief todo
*/
#include <drm_fourcc.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/dma-buf.h>
#include <sys/capability.h>
#include <sys/mman.h>
#include <unistd.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <filesystem>
#include <thread>
#include "src/config.h"
#include "src/logging.h"
#include "src/platform/common.h"
#include "src/round_robin.h"
#include "src/utility.h"
#include "src/video.h"
#include "cuda.h"
#include "graphics.h"
#include "vaapi.h"
#include "wayland.h"
using namespace std::literals;
namespace fs = std::filesystem;
namespace platf {
namespace kms {
class cap_sys_admin {
public:
cap_sys_admin() {
caps = cap_get_proc();
cap_value_t sys_admin = CAP_SYS_ADMIN;
if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_admin, CAP_SET) || cap_set_proc(caps)) {
BOOST_LOG(error) << "Failed to gain CAP_SYS_ADMIN";
}
}
~cap_sys_admin() {
cap_value_t sys_admin = CAP_SYS_ADMIN;
if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_admin, CAP_CLEAR) || cap_set_proc(caps)) {
BOOST_LOG(error) << "Failed to drop CAP_SYS_ADMIN";
}
cap_free(caps);
}
cap_t caps;
};
class wrapper_fb {
public:
wrapper_fb(drmModeFB *fb):
fb { fb }, fb_id { fb->fb_id }, width { fb->width }, height { fb->height } {
pixel_format = DRM_FORMAT_XRGB8888;
modifier = DRM_FORMAT_MOD_INVALID;
std::fill_n(handles, 4, 0);
std::fill_n(pitches, 4, 0);
std::fill_n(offsets, 4, 0);
handles[0] = fb->handle;
pitches[0] = fb->pitch;
}
wrapper_fb(drmModeFB2 *fb2):
fb2 { fb2 }, fb_id { fb2->fb_id }, width { fb2->width }, height { fb2->height } {
pixel_format = fb2->pixel_format;
modifier = (fb2->flags & DRM_MODE_FB_MODIFIERS) ? fb2->modifier : DRM_FORMAT_MOD_INVALID;
memcpy(handles, fb2->handles, sizeof(handles));
memcpy(pitches, fb2->pitches, sizeof(pitches));
memcpy(offsets, fb2->offsets, sizeof(offsets));
}
~wrapper_fb() {
if (fb) {
drmModeFreeFB(fb);
}
else if (fb2) {
drmModeFreeFB2(fb2);
}
}
drmModeFB *fb = nullptr;
drmModeFB2 *fb2 = nullptr;
uint32_t fb_id;
uint32_t width;
uint32_t height;
uint32_t pixel_format;
uint64_t modifier;
uint32_t handles[4];
uint32_t pitches[4];
uint32_t offsets[4];
};
using plane_res_t = util::safe_ptr<drmModePlaneRes, drmModeFreePlaneResources>;
using encoder_t = util::safe_ptr<drmModeEncoder, drmModeFreeEncoder>;
using res_t = util::safe_ptr<drmModeRes, drmModeFreeResources>;
using plane_t = util::safe_ptr<drmModePlane, drmModeFreePlane>;
using fb_t = std::unique_ptr<wrapper_fb>;
using crtc_t = util::safe_ptr<drmModeCrtc, drmModeFreeCrtc>;
using obj_prop_t = util::safe_ptr<drmModeObjectProperties, drmModeFreeObjectProperties>;
using prop_t = util::safe_ptr<drmModePropertyRes, drmModeFreeProperty>;
using prop_blob_t = util::safe_ptr<drmModePropertyBlobRes, drmModeFreePropertyBlob>;
using version_t = util::safe_ptr<drmVersion, drmFreeVersion>;
using conn_type_count_t = std::map<std::uint32_t, std::uint32_t>;
static int env_width;
static int env_height;
std::string_view
plane_type(std::uint64_t val) {
switch (val) {
case DRM_PLANE_TYPE_OVERLAY:
return "DRM_PLANE_TYPE_OVERLAY"sv;
case DRM_PLANE_TYPE_PRIMARY:
return "DRM_PLANE_TYPE_PRIMARY"sv;
case DRM_PLANE_TYPE_CURSOR:
return "DRM_PLANE_TYPE_CURSOR"sv;
}
return "UNKNOWN"sv;
}
struct connector_t {
// For example: HDMI-A or HDMI
std::uint32_t type;
// Equals zero if not applicable
std::uint32_t crtc_id;
// For example HDMI-A-{index} or HDMI-{index}
std::uint32_t index;
// ID of the connector
std::uint32_t connector_id;
bool connected;
};
struct monitor_t {
// Connector attributes
std::uint32_t type;
std::uint32_t index;
// Monitor index in the global list
std::uint32_t monitor_index;
platf::touch_port_t viewport;
};
struct card_descriptor_t {
std::string path;
std::map<std::uint32_t, monitor_t> crtc_to_monitor;
};
static std::vector<card_descriptor_t> card_descriptors;
static std::uint32_t
from_view(const std::string_view &string) {
#define _CONVERT(x, y) \
if (string == x) return DRM_MODE_CONNECTOR_##y
// This list was created from the following sources:
// https://gitlab.freedesktop.org/mesa/drm/-/blob/main/xf86drmMode.c (drmModeGetConnectorTypeName)
// https://gitlab.freedesktop.org/wayland/weston/-/blob/e74f2897b9408b6356a555a0ce59146836307ff5/libweston/backend-drm/drm.c#L1458-1477
// https://github.com/GNOME/mutter/blob/65d481594227ea7188c0416e8e00b57caeea214f/src/backends/meta-monitor-manager.c#L1618-L1639
_CONVERT("VGA"sv, VGA);
_CONVERT("DVII"sv, DVII);
_CONVERT("DVI-I"sv, DVII);
_CONVERT("DVID"sv, DVID);
_CONVERT("DVI-D"sv, DVID);
_CONVERT("DVIA"sv, DVIA);
_CONVERT("DVI-A"sv, DVIA);
_CONVERT("Composite"sv, Composite);
_CONVERT("SVIDEO"sv, SVIDEO);
_CONVERT("S-Video"sv, SVIDEO);
_CONVERT("LVDS"sv, LVDS);
_CONVERT("Component"sv, Component);
_CONVERT("9PinDIN"sv, 9PinDIN);
_CONVERT("DIN"sv, 9PinDIN);
_CONVERT("DisplayPort"sv, DisplayPort);
_CONVERT("DP"sv, DisplayPort);
_CONVERT("HDMIA"sv, HDMIA);
_CONVERT("HDMI-A"sv, HDMIA);
_CONVERT("HDMI"sv, HDMIA);
_CONVERT("HDMIB"sv, HDMIB);
_CONVERT("HDMI-B"sv, HDMIB);
_CONVERT("TV"sv, TV);
_CONVERT("eDP"sv, eDP);
_CONVERT("VIRTUAL"sv, VIRTUAL);
_CONVERT("Virtual"sv, VIRTUAL);
_CONVERT("DSI"sv, DSI);
_CONVERT("DPI"sv, DPI);
_CONVERT("WRITEBACK"sv, WRITEBACK);
_CONVERT("Writeback"sv, WRITEBACK);
_CONVERT("SPI"sv, SPI);
#ifdef DRM_MODE_CONNECTOR_USB
_CONVERT("USB"sv, USB);
#endif
// If the string starts with "Unknown", it may have the raw type
// value appended to the string. Let's try to read it.
if (string.find("Unknown"sv) == 0) {
std::uint32_t type;
std::string null_terminated_string { string };
if (std::sscanf(null_terminated_string.c_str(), "Unknown%u", &type) == 1) {
return type;
}
}
BOOST_LOG(error) << "Unknown Monitor connector type ["sv << string << "]: Please report this to the GitHub issue tracker"sv;
return DRM_MODE_CONNECTOR_Unknown;
}
class plane_it_t: public round_robin_util::it_wrap_t<plane_t::element_type, plane_it_t> {
public:
plane_it_t(int fd, std::uint32_t *plane_p, std::uint32_t *end):
fd { fd }, plane_p { plane_p }, end { end } {
load_next_valid_plane();
}
plane_it_t(int fd, std::uint32_t *end):
fd { fd }, plane_p { end }, end { end } {}
void
load_next_valid_plane() {
this->plane.reset();
for (; plane_p != end; ++plane_p) {
plane_t plane = drmModeGetPlane(fd, *plane_p);
if (!plane) {
BOOST_LOG(error) << "Couldn't get drm plane ["sv << (end - plane_p) << "]: "sv << strerror(errno);
continue;
}
this->plane = util::make_shared<plane_t>(plane.release());
break;
}
}
void
inc() {
++plane_p;
load_next_valid_plane();
}
bool
eq(const plane_it_t &other) const {
return plane_p == other.plane_p;
}
plane_t::pointer
get() {
return plane.get();
}
int fd;
std::uint32_t *plane_p;
std::uint32_t *end;
util::shared_t<plane_t> plane;
};
struct cursor_t {
// Public properties used during blending
bool visible = false;
std::int32_t x, y;
std::uint32_t dst_w, dst_h;
std::uint32_t src_w, src_h;
std::vector<std::uint8_t> pixels;
unsigned long serial;
// Private properties used for tracking cursor changes
std::uint64_t prop_src_x, prop_src_y, prop_src_w, prop_src_h;
std::uint32_t fb_id;
};
class card_t {
public:
using connector_interal_t = util::safe_ptr<drmModeConnector, drmModeFreeConnector>;
int
init(const char *path) {
cap_sys_admin admin;
fd.el = open(path, O_RDWR);
if (fd.el < 0) {
BOOST_LOG(error) << "Couldn't open: "sv << path << ": "sv << strerror(errno);
return -1;
}
version_t ver { drmGetVersion(fd.el) };
BOOST_LOG(info) << path << " -> "sv << ((ver && ver->name) ? ver->name : "UNKNOWN");
// Open the render node for this card to share with libva.
// If it fails, we'll just share the primary node instead.
char *rendernode_path = drmGetRenderDeviceNameFromFd(fd.el);
if (rendernode_path) {
BOOST_LOG(debug) << "Opening render node: "sv << rendernode_path;
render_fd.el = open(rendernode_path, O_RDWR);
if (render_fd.el < 0) {
BOOST_LOG(warning) << "Couldn't open render node: "sv << rendernode_path << ": "sv << strerror(errno);
render_fd.el = dup(fd.el);
}
free(rendernode_path);
}
else {
BOOST_LOG(warning) << "No render device name for: "sv << path;
render_fd.el = dup(fd.el);
}
if (drmSetClientCap(fd.el, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1)) {
BOOST_LOG(error) << "GPU driver doesn't support universal planes: "sv << path;
return -1;
}
if (drmSetClientCap(fd.el, DRM_CLIENT_CAP_ATOMIC, 1)) {
BOOST_LOG(warning) << "GPU driver doesn't support atomic mode-setting: "sv << path;
#if defined(SUNSHINE_BUILD_X11)
// We won't be able to capture the mouse cursor with KMS on non-atomic drivers,
// so fall back to X11 if it's available and the user didn't explicitly force KMS.
if (window_system == window_system_e::X11 && config::video.capture != "kms") {
BOOST_LOG(info) << "Avoiding KMS capture under X11 due to lack of atomic mode-setting"sv;
return -1;
}
#endif
BOOST_LOG(warning) << "Cursor capture may fail without atomic mode-setting support!"sv;
}
plane_res.reset(drmModeGetPlaneResources(fd.el));
if (!plane_res) {
BOOST_LOG(error) << "Couldn't get drm plane resources"sv;
return -1;
}
return 0;
}
fb_t
fb(plane_t::pointer plane) {
cap_sys_admin admin;
auto fb2 = drmModeGetFB2(fd.el, plane->fb_id);
if (fb2) {
return std::make_unique<wrapper_fb>(fb2);
}
auto fb = drmModeGetFB(fd.el, plane->fb_id);
if (fb) {
return std::make_unique<wrapper_fb>(fb);
}
return nullptr;
}
crtc_t
crtc(std::uint32_t id) {
return drmModeGetCrtc(fd.el, id);
}
encoder_t
encoder(std::uint32_t id) {
return drmModeGetEncoder(fd.el, id);
}
res_t
res() {
return drmModeGetResources(fd.el);
}
bool
is_nvidia() {
version_t ver { drmGetVersion(fd.el) };
return ver && ver->name && strncmp(ver->name, "nvidia-drm", 10) == 0;
}
bool
is_cursor(std::uint32_t plane_id) {
auto props = plane_props(plane_id);
for (auto &[prop, val] : props) {
if (prop->name == "type"sv) {
if (val == DRM_PLANE_TYPE_CURSOR) {
return true;
}
else {
return false;
}
}
}
return false;
}
std::optional<std::uint64_t>
prop_value_by_name(const std::vector<std::pair<prop_t, std::uint64_t>> &props, std::string_view name) {
for (auto &[prop, val] : props) {
if (prop->name == name) {
return val;
}
}
return std::nullopt;
}
std::uint32_t
get_panel_orientation(std::uint32_t plane_id) {
auto props = plane_props(plane_id);
auto value = prop_value_by_name(props, "rotation"sv);
if (value) {
return *value;
}
BOOST_LOG(error) << "Failed to determine panel orientation, defaulting to landscape.";
return DRM_MODE_ROTATE_0;
}
int
get_crtc_index_by_id(std::uint32_t crtc_id) {
auto resources = res();
for (int i = 0; i < resources->count_crtcs; i++) {
if (resources->crtcs[i] == crtc_id) {
return i;
}
}
return -1;
}
connector_interal_t
connector(std::uint32_t id) {
return drmModeGetConnector(fd.el, id);
}
std::vector<connector_t>
monitors(conn_type_count_t &conn_type_count) {
auto resources = res();
if (!resources) {
BOOST_LOG(error) << "Couldn't get connector resources"sv;
return {};
}
std::vector<connector_t> monitors;
std::for_each_n(resources->connectors, resources->count_connectors, [this, &conn_type_count, &monitors](std::uint32_t id) {
auto conn = connector(id);
std::uint32_t crtc_id = 0;
if (conn->encoder_id) {
auto enc = encoder(conn->encoder_id);
if (enc) {
crtc_id = enc->crtc_id;
}
}
auto index = ++conn_type_count[conn->connector_type];
monitors.emplace_back(connector_t {
conn->connector_type,
crtc_id,
index,
conn->connector_id,
conn->connection == DRM_MODE_CONNECTED,
});
});
return monitors;
}
file_t
handleFD(std::uint32_t handle) {
file_t fb_fd;
auto status = drmPrimeHandleToFD(fd.el, handle, 0 /* flags */, &fb_fd.el);
if (status) {
return {};
}
return fb_fd;
}
std::vector<std::pair<prop_t, std::uint64_t>>
props(std::uint32_t id, std::uint32_t type) {
obj_prop_t obj_prop = drmModeObjectGetProperties(fd.el, id, type);
if (!obj_prop) {
return {};
}
std::vector<std::pair<prop_t, std::uint64_t>> props;
props.reserve(obj_prop->count_props);
for (auto x = 0; x < obj_prop->count_props; ++x) {
props.emplace_back(drmModeGetProperty(fd.el, obj_prop->props[x]), obj_prop->prop_values[x]);
}
return props;
}
std::vector<std::pair<prop_t, std::uint64_t>>
plane_props(std::uint32_t id) {
return props(id, DRM_MODE_OBJECT_PLANE);
}
std::vector<std::pair<prop_t, std::uint64_t>>
crtc_props(std::uint32_t id) {
return props(id, DRM_MODE_OBJECT_CRTC);
}
std::vector<std::pair<prop_t, std::uint64_t>>
connector_props(std::uint32_t id) {
return props(id, DRM_MODE_OBJECT_CONNECTOR);
}
plane_t
operator[](std::uint32_t index) {
return drmModeGetPlane(fd.el, plane_res->planes[index]);
}
std::uint32_t
count() {
return plane_res->count_planes;
}
plane_it_t
begin() const {
return plane_it_t { fd.el, plane_res->planes, plane_res->planes + plane_res->count_planes };
}
plane_it_t
end() const {
return plane_it_t { fd.el, plane_res->planes + plane_res->count_planes };
}
file_t fd;
file_t render_fd;
plane_res_t plane_res;
};
std::map<std::uint32_t, monitor_t>
map_crtc_to_monitor(const std::vector<connector_t> &connectors) {
std::map<std::uint32_t, monitor_t> result;
for (auto &connector : connectors) {
result.emplace(connector.crtc_id,
monitor_t {
connector.type,
connector.index,
});
}
return result;
}
struct kms_img_t: public img_t {
~kms_img_t() override {
delete[] data;
data = nullptr;
}
};
void
print(plane_t::pointer plane, fb_t::pointer fb, crtc_t::pointer crtc) {
if (crtc) {
BOOST_LOG(debug) << "crtc("sv << crtc->x << ", "sv << crtc->y << ')';
BOOST_LOG(debug) << "crtc("sv << crtc->width << ", "sv << crtc->height << ')';
BOOST_LOG(debug) << "plane->possible_crtcs == "sv << plane->possible_crtcs;
}
BOOST_LOG(debug)
<< "x("sv << plane->x
<< ") y("sv << plane->y
<< ") crtc_x("sv << plane->crtc_x
<< ") crtc_y("sv << plane->crtc_y
<< ") crtc_id("sv << plane->crtc_id
<< ')';
BOOST_LOG(debug)
<< "Resolution: "sv << fb->width << 'x' << fb->height
<< ": Pitch: "sv << fb->pitches[0]
<< ": Offset: "sv << fb->offsets[0];
std::stringstream ss;
ss << "Format ["sv;
std::for_each_n(plane->formats, plane->count_formats - 1, [&ss](auto format) {
ss << util::view(format) << ", "sv;
});
ss << util::view(plane->formats[plane->count_formats - 1]) << ']';
BOOST_LOG(debug) << ss.str();
}
class display_t: public platf::display_t {
public:
display_t(mem_type_e mem_type):
platf::display_t(), mem_type { mem_type } {}
int
init(const std::string &display_name, const ::video::config_t &config) {
delay = std::chrono::nanoseconds { 1s } / config.framerate;
int monitor_index = util::from_view(display_name);
int monitor = 0;
fs::path card_dir { "/dev/dri"sv };
for (auto &entry : fs::directory_iterator { card_dir }) {
auto file = entry.path().filename();
auto filestring = file.generic_u8string();
if (filestring.size() < 4 || std::string_view { filestring }.substr(0, 4) != "card"sv) {
continue;
}
kms::card_t card;
if (card.init(entry.path().c_str())) {
continue;
}
// Skip non-Nvidia cards if we're looking for CUDA devices
// unless NVENC is selected manually by the user
if (mem_type == mem_type_e::cuda && !card.is_nvidia()) {
BOOST_LOG(debug) << file << " is not a CUDA device"sv;
if (config::video.encoder != "nvenc") {
continue;
}
}
auto end = std::end(card);
for (auto plane = std::begin(card); plane != end; ++plane) {
// Skip unused planes
if (!plane->fb_id) {
continue;
}
if (card.is_cursor(plane->plane_id)) {
continue;
}
if (monitor != monitor_index) {
++monitor;
continue;
}
auto fb = card.fb(plane.get());
if (!fb) {
BOOST_LOG(error) << "Couldn't get drm fb for plane ["sv << plane->fb_id << "]: "sv << strerror(errno);
return -1;
}
if (!fb->handles[0]) {
BOOST_LOG(error) << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Probably not permitted"sv;
return -1;
}
for (int i = 0; i < 4; ++i) {
if (!fb->handles[i]) {
break;
}
auto fb_fd = card.handleFD(fb->handles[i]);
if (fb_fd.el < 0) {
BOOST_LOG(error) << "Couldn't get primary file descriptor for Framebuffer ["sv << fb->fb_id << "]: "sv << strerror(errno);
continue;
}
}
auto crtc = card.crtc(plane->crtc_id);
if (!crtc) {
BOOST_LOG(error) << "Couldn't get CRTC info: "sv << strerror(errno);
continue;
}
BOOST_LOG(info) << "Found monitor for DRM screencasting"sv;
// We need to find the correct /dev/dri/card{nr} to correlate the crtc_id with the monitor descriptor
auto pos = std::find_if(std::begin(card_descriptors), std::end(card_descriptors), [&](card_descriptor_t &cd) {
return cd.path == filestring;
});
if (pos == std::end(card_descriptors)) {
// This code path shouldn't happen, but it's there just in case.
// card_descriptors is part of the guesswork after all.
BOOST_LOG(error) << "Couldn't find ["sv << entry.path() << "]: This shouldn't have happened :/"sv;
return -1;
}
// TODO: surf_sd = fb->to_sd();
kms::print(plane.get(), fb.get(), crtc.get());
img_width = fb->width;
img_height = fb->height;
img_offset_x = crtc->x;
img_offset_y = crtc->y;
this->env_width = ::platf::kms::env_width;
this->env_height = ::platf::kms::env_height;
auto monitor = pos->crtc_to_monitor.find(plane->crtc_id);
if (monitor != std::end(pos->crtc_to_monitor)) {
auto &viewport = monitor->second.viewport;
width = viewport.width;
height = viewport.height;
switch (card.get_panel_orientation(plane->plane_id)) {
case DRM_MODE_ROTATE_270:
BOOST_LOG(debug) << "Detected panel orientation at 90, swapping width and height.";
width = viewport.height;
height = viewport.width;
break;
case DRM_MODE_ROTATE_90:
case DRM_MODE_ROTATE_180:
BOOST_LOG(warning) << "Panel orientation is unsupported, screen capture may not work correctly.";
break;
}
offset_x = viewport.offset_x;
offset_y = viewport.offset_y;
}
// This code path shouldn't happen, but it's there just in case.
// crtc_to_monitor is part of the guesswork after all.
else {
BOOST_LOG(warning) << "Couldn't find crtc_id, this shouldn't have happened :\\"sv;
width = crtc->width;
height = crtc->height;
offset_x = crtc->x;
offset_y = crtc->y;
}
plane_id = plane->plane_id;
crtc_id = plane->crtc_id;
crtc_index = card.get_crtc_index_by_id(plane->crtc_id);
// Find the connector for this CRTC
kms::conn_type_count_t conn_type_count;
for (auto &connector : card.monitors(conn_type_count)) {
if (connector.crtc_id == crtc_id) {
BOOST_LOG(info) << "Found connector ID ["sv << connector.connector_id << ']';
connector_id = connector.connector_id;
auto connector_props = card.connector_props(*connector_id);
hdr_metadata_blob_id = card.prop_value_by_name(connector_props, "HDR_OUTPUT_METADATA"sv);
}
}
this->card = std::move(card);
goto break_loop;
}
}
BOOST_LOG(error) << "Couldn't find monitor ["sv << monitor_index << ']';
return -1;
// Neatly break from nested for loop
break_loop:
// Look for the cursor plane for this CRTC
cursor_plane_id = -1;
auto end = std::end(card);
for (auto plane = std::begin(card); plane != end; ++plane) {
if (!card.is_cursor(plane->plane_id)) {
continue;
}
// NB: We do not skip unused planes here because cursor planes
// will look unused if the cursor is currently hidden.
if (!(plane->possible_crtcs & (1 << crtc_index))) {
// Skip cursor planes for other CRTCs
continue;
}
else if (plane->possible_crtcs != (1 << crtc_index)) {
// We assume a 1:1 mapping between cursor planes and CRTCs, which seems to
// match the behavior of drivers in the real world. If it's violated, we'll
// proceed anyway but print a warning in the log.
BOOST_LOG(warning) << "Cursor plane spans multiple CRTCs!"sv;
}
BOOST_LOG(info) << "Found cursor plane ["sv << plane->plane_id << ']';
cursor_plane_id = plane->plane_id;
break;
}
if (cursor_plane_id < 0) {
BOOST_LOG(warning) << "No KMS cursor plane found. Cursor may not be displayed while streaming!"sv;
}
return 0;
}
bool
is_hdr() {
if (!hdr_metadata_blob_id || *hdr_metadata_blob_id == 0) {
return false;
}
prop_blob_t hdr_metadata_blob = drmModeGetPropertyBlob(card.fd.el, *hdr_metadata_blob_id);
if (hdr_metadata_blob == nullptr) {
BOOST_LOG(error) << "Unable to get HDR metadata blob: "sv << strerror(errno);
return false;
}
if (hdr_metadata_blob->length < sizeof(uint32_t) + sizeof(hdr_metadata_infoframe)) {
BOOST_LOG(error) << "HDR metadata blob is too small: "sv << hdr_metadata_blob->length;
return false;
}
auto raw_metadata = (hdr_output_metadata *) hdr_metadata_blob->data;
if (raw_metadata->metadata_type != 0) { // HDMI_STATIC_METADATA_TYPE1
BOOST_LOG(error) << "Unknown HDMI_STATIC_METADATA_TYPE value: "sv << raw_metadata->metadata_type;
return false;
}
if (raw_metadata->hdmi_metadata_type1.metadata_type != 0) { // Static Metadata Type 1
BOOST_LOG(error) << "Unknown secondary metadata type value: "sv << raw_metadata->hdmi_metadata_type1.metadata_type;
return false;
}
// We only support Traditional Gamma SDR or SMPTE 2084 PQ HDR EOTFs.
// Print a warning if we encounter any others.
switch (raw_metadata->hdmi_metadata_type1.eotf) {
case 0: // HDMI_EOTF_TRADITIONAL_GAMMA_SDR
return false;
case 1: // HDMI_EOTF_TRADITIONAL_GAMMA_HDR
BOOST_LOG(warning) << "Unsupported HDR EOTF: Traditional Gamma"sv;
return true;
case 2: // HDMI_EOTF_SMPTE_ST2084
return true;
case 3: // HDMI_EOTF_BT_2100_HLG
BOOST_LOG(warning) << "Unsupported HDR EOTF: HLG"sv;
return true;
default:
BOOST_LOG(warning) << "Unsupported HDR EOTF: "sv << raw_metadata->hdmi_metadata_type1.eotf;
return true;
}
}
bool
get_hdr_metadata(SS_HDR_METADATA &metadata) {
// This performs all the metadata validation
if (!is_hdr()) {
return false;
}
prop_blob_t hdr_metadata_blob = drmModeGetPropertyBlob(card.fd.el, *hdr_metadata_blob_id);
if (hdr_metadata_blob == nullptr) {
BOOST_LOG(error) << "Unable to get HDR metadata blob: "sv << strerror(errno);
return false;
}
auto raw_metadata = (hdr_output_metadata *) hdr_metadata_blob->data;
for (int i = 0; i < 3; i++) {
metadata.displayPrimaries[i].x = raw_metadata->hdmi_metadata_type1.display_primaries[i].x;
metadata.displayPrimaries[i].y = raw_metadata->hdmi_metadata_type1.display_primaries[i].y;
}
metadata.whitePoint.x = raw_metadata->hdmi_metadata_type1.white_point.x;
metadata.whitePoint.y = raw_metadata->hdmi_metadata_type1.white_point.y;
metadata.maxDisplayLuminance = raw_metadata->hdmi_metadata_type1.max_display_mastering_luminance;
metadata.minDisplayLuminance = raw_metadata->hdmi_metadata_type1.min_display_mastering_luminance;
metadata.maxContentLightLevel = raw_metadata->hdmi_metadata_type1.max_cll;
metadata.maxFrameAverageLightLevel = raw_metadata->hdmi_metadata_type1.max_fall;
return true;
}
void
update_cursor() {
if (cursor_plane_id < 0) {
return;
}
plane_t plane = drmModeGetPlane(card.fd.el, cursor_plane_id);
std::optional<std::int32_t> prop_crtc_x;
std::optional<std::int32_t> prop_crtc_y;
std::optional<std::uint32_t> prop_crtc_w;
std::optional<std::uint32_t> prop_crtc_h;
std::optional<std::uint64_t> prop_src_x;
std::optional<std::uint64_t> prop_src_y;
std::optional<std::uint64_t> prop_src_w;
std::optional<std::uint64_t> prop_src_h;
auto props = card.plane_props(cursor_plane_id);
for (auto &[prop, val] : props) {
if (prop->name == "CRTC_X"sv) {
prop_crtc_x = val;
}
else if (prop->name == "CRTC_Y"sv) {
prop_crtc_y = val;
}
else if (prop->name == "CRTC_W"sv) {
prop_crtc_w = val;
}
else if (prop->name == "CRTC_H"sv) {
prop_crtc_h = val;
}
else if (prop->name == "SRC_X"sv) {
prop_src_x = val;
}
else if (prop->name == "SRC_Y"sv) {
prop_src_y = val;
}
else if (prop->name == "SRC_W"sv) {
prop_src_w = val;
}
else if (prop->name == "SRC_H"sv) {
prop_src_h = val;
}
}
if (!prop_crtc_w || !prop_crtc_h || !prop_crtc_x || !prop_crtc_y) {
BOOST_LOG(error) << "Cursor plane is missing required plane CRTC properties!"sv;
BOOST_LOG(error) << "Atomic mode-setting must be enabled to capture the cursor!"sv;
cursor_plane_id = -1;
captured_cursor.visible = false;
return;
}
if (!prop_src_x || !prop_src_y || !prop_src_w || !prop_src_h) {
BOOST_LOG(error) << "Cursor plane is missing required plane SRC properties!"sv;
BOOST_LOG(error) << "Atomic mode-setting must be enabled to capture the cursor!"sv;
cursor_plane_id = -1;
captured_cursor.visible = false;
return;
}
// Update the cursor position and size unconditionally
captured_cursor.x = *prop_crtc_x;
captured_cursor.y = *prop_crtc_y;
captured_cursor.dst_w = *prop_crtc_w;
captured_cursor.dst_h = *prop_crtc_h;
// We're technically cheating a bit here by assuming that we can detect
// changes to the cursor plane via property adjustments. If this isn't
// true, we'll really have to mmap() the dmabuf and draw that every time.
bool cursor_dirty = false;
if (!plane->fb_id) {
captured_cursor.visible = false;
captured_cursor.fb_id = 0;
}
else if (plane->fb_id != captured_cursor.fb_id) {
BOOST_LOG(debug) << "Refreshing cursor image after FB changed"sv;
cursor_dirty = true;
}
else if (*prop_src_x != captured_cursor.prop_src_x ||
*prop_src_y != captured_cursor.prop_src_y ||
*prop_src_w != captured_cursor.prop_src_w ||
*prop_src_h != captured_cursor.prop_src_h) {
BOOST_LOG(debug) << "Refreshing cursor image after source dimensions changed"sv;
cursor_dirty = true;
}
// If the cursor is dirty, map it so we can download the new image
if (cursor_dirty) {
auto fb = card.fb(plane.get());
if (!fb || !fb->handles[0]) {
// This means the cursor is not currently visible
captured_cursor.visible = false;
return;
}
// All known cursor planes in the wild are ARGB8888
if (fb->pixel_format != DRM_FORMAT_ARGB8888) {
BOOST_LOG(error) << "Unsupported non-ARGB8888 cursor format: "sv << fb->pixel_format;
captured_cursor.visible = false;
cursor_plane_id = -1;
return;
}
// All known cursor planes in the wild require linear buffers
if (fb->modifier != DRM_FORMAT_MOD_LINEAR && fb->modifier != DRM_FORMAT_MOD_INVALID) {
BOOST_LOG(error) << "Unsupported non-linear cursor modifier: "sv << fb->modifier;
captured_cursor.visible = false;
cursor_plane_id = -1;
return;
}
// The SRC_* properties are in Q16.16 fixed point, so convert to integers
auto src_x = *prop_src_x >> 16;
auto src_y = *prop_src_y >> 16;
auto src_w = *prop_src_w >> 16;
auto src_h = *prop_src_h >> 16;
// Check for a legal source rectangle
if (src_x + src_w > fb->width || src_y + src_h > fb->height) {
BOOST_LOG(error) << "Illegal source size: ["sv << src_x + src_w << ',' << src_y + src_h << "] > ["sv << fb->width << ',' << fb->height << ']';