-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathkmsgrab.cpp
More file actions
2186 lines (1861 loc) · 77.1 KB
/
Copy pathkmsgrab.cpp
File metadata and controls
2186 lines (1861 loc) · 77.1 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
/**
* @file src/platform/linux/kmsgrab.cpp
* @brief Definitions for KMS screen capture.
*/
// standard includes
#include <errno.h>
#include <fcntl.h>
#include <filesystem>
#include <ranges>
#include <thread>
#include <unistd.h>
// platform includes
#include <drm_fourcc.h>
#include <linux/dma-buf.h>
#include <sys/capability.h>
#include <sys/mman.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
// local includes
#include "cuda.h"
#include "graphics.h"
#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 "vaapi.h"
#include "vulkan_encode.h"
#include "wayland.h"
using namespace std::literals;
namespace fs = std::filesystem;
namespace platf {
namespace kms {
/**
* @brief Temporarily owns CAP_SYS_ADMIN while opening DRM capture resources.
*/
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; ///< Caps.
};
/**
* @brief RAII wrapper for DRM framebuffer metadata and GEM handles.
*/
class wrapper_fb {
public:
/**
* @brief Wrap legacy DRM framebuffer metadata.
*
* @param card_fd DRM card file descriptor used to close GEM handles.
* @param fb Legacy framebuffer metadata returned by drmModeGetFB.
*/
wrapper_fb(uint32_t card_fd, drmModeFB *fb):
card_fd {card_fd},
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;
}
/**
* @brief Wrap DRM framebuffer metadata with per-plane modifiers.
*
* @param card_fd DRM card file descriptor used to close GEM handles.
* @param fb2 Framebuffer metadata returned by drmModeGetFB2.
*/
wrapper_fb(uint32_t card_fd, drmModeFB2 *fb2):
card_fd {card_fd},
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() {
std::ranges::for_each(handles, [&](auto &handle) {
if (handle) {
struct drm_gem_close close_args = {};
close_args.handle = handle;
drmIoctl(card_fd, DRM_IOCTL_GEM_CLOSE, &close_args);
}
});
if (fb) {
drmModeFreeFB(fb);
} else if (fb2) {
drmModeFreeFB2(fb2);
}
}
uint32_t card_fd; ///< DRM card file descriptor that owns the framebuffer ID.
drmModeFB *fb = nullptr; ///< Legacy DRM framebuffer metadata when modifier data is unavailable.
drmModeFB2 *fb2 = nullptr; ///< DRM framebuffer metadata with modifier support.
uint32_t fb_id; ///< DRM framebuffer ID being captured.
uint32_t width; ///< Framebuffer width in pixels.
uint32_t height; ///< Framebuffer height in pixels.
uint32_t pixel_format; ///< DRM fourcc pixel format for the framebuffer.
uint64_t modifier; ///< DRM format modifier describing framebuffer memory layout.
uint32_t handles[4]; ///< GEM handles for each framebuffer plane.
uint32_t pitches[4]; ///< Row stride in bytes for each framebuffer plane.
uint32_t offsets[4]; ///< Byte offset to the first pixel for each framebuffer plane.
};
/**
* @brief DRM plane resource list released with `drmModeFreePlaneResources`.
*/
using plane_res_t = util::safe_ptr<drmModePlaneRes, drmModeFreePlaneResources>;
/**
* @brief DRM encoder pointer released with `drmModeFreeEncoder`.
*/
using encoder_t = util::safe_ptr<drmModeEncoder, drmModeFreeEncoder>;
/**
* @brief DRM resource list released with `drmModeFreeResources`.
*/
using res_t = util::safe_ptr<drmModeRes, drmModeFreeResources>;
/**
* @brief DRM plane pointer released with `drmModeFreePlane`.
*/
using plane_t = util::safe_ptr<drmModePlane, drmModeFreePlane>;
/**
* @brief DRM framebuffer pointer released with `drmModeFreeFB2`.
*/
using fb_t = std::unique_ptr<wrapper_fb>;
/**
* @brief DRM CRTC pointer released with `drmModeFreeCrtc`.
*/
using crtc_t = util::safe_ptr<drmModeCrtc, drmModeFreeCrtc>;
/**
* @brief DRM object-property list released with `drmModeFreeObjectProperties`.
*/
using obj_prop_t = util::safe_ptr<drmModeObjectProperties, drmModeFreeObjectProperties>;
/**
* @brief DRM property pointer released with `drmModeFreeProperty`.
*/
using prop_t = util::safe_ptr<drmModePropertyRes, drmModeFreeProperty>;
/**
* @brief DRM property-blob pointer released with `drmModeFreePropertyBlob`.
*/
using prop_blob_t = util::safe_ptr<drmModePropertyBlobRes, drmModeFreePropertyBlob>;
/**
* @brief DRM version pointer released with `drmFreeVersion`.
*/
using version_t = util::safe_ptr<drmVersion, drmFreeVersion>;
/**
* @brief Counter map keyed by DRM connector type.
*/
using conn_type_count_t = std::map<std::uint32_t, std::uint32_t>;
static int env_width;
static int env_height;
static int env_logical_width;
static int env_logical_height;
/**
* @brief Convert a DRM plane type value to a diagnostic string.
*
* @param val Value assigned to the synchronized object.
* @return Static text for the DRM plane type.
*/
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;
}
/**
* @brief DRM connector and mode information for one display.
*/
struct connector_t {
// For example: HDMI-A or HDMI
std::uint32_t type; ///< Type.
// Equals zero if not applicable
std::uint32_t crtc_id; ///< Crtc ID.
// For example HDMI-A-{index} or HDMI-{index}
std::uint32_t index; ///< Index.
// ID of the connector
std::uint32_t connector_id; ///< Connector ID.
bool connected; ///< Whether the DRM connector is connected.
};
/**
* @brief KMS monitor capture state and DRM resources.
*/
struct monitor_t {
// Connector attributes
std::uint32_t type; ///< Type.
std::uint32_t index; ///< Index.
// Monitor index in the global list
std::uint32_t monitor_index; ///< Monitor index.
platf::touch_port_t viewport; ///< Viewport.
};
/**
* @brief DRM card, device path, and render-node metadata.
*/
struct card_descriptor_t {
std::string path; ///< Path.
std::map<std::uint32_t, monitor_t> crtc_to_monitor; ///< Crtc to monitor.
};
static std::vector<card_descriptor_t> card_descriptors;
static std::uint32_t from_view(const std::string_view &string) {
#ifndef DOXYGEN
#define _CONVERT(x, y) \
if (string == x) \
return DRM_MODE_CONNECTOR_##y
#endif
// 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;
}
/**
* @brief Iterator over DRM planes and their associated properties.
*/
class plane_it_t: public round_robin_util::it_wrap_t<plane_t::element_type, plane_it_t> {
public:
/**
* @brief Create an iterator over DRM planes starting at a specific plane ID.
*
* @param fd DRM card file descriptor.
* @param plane_p Current plane ID pointer.
* @param end One-past-the-end plane ID pointer.
*/
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();
}
/**
* @brief Create the end iterator for a DRM plane range.
*
* @param fd DRM card file descriptor.
* @param end One-past-the-end plane ID pointer.
*/
plane_it_t(int fd, std::uint32_t *end):
fd {fd},
plane_p {end},
end {end} {
}
/**
* @brief Load next valid plane.
*/
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;
}
}
/**
* @brief Advance the iterator to the next element.
*/
void inc() {
++plane_p;
load_next_valid_plane();
}
/**
* @brief Compare two iterators for equality.
*
* @param other Plane iterator to compare against.
* @return True when both iterators reference the same plane position.
*/
bool eq(const plane_it_t &other) const {
return plane_p == other.plane_p;
}
/**
* @brief Return the currently wrapped value or handle.
*
* @return Underlying native handle or object pointer.
*/
plane_t::pointer get() {
return plane.get();
}
int fd; ///< DRM card file descriptor.
std::uint32_t *plane_p; ///< Current plane ID pointer.
std::uint32_t *end; ///< One-past-the-end plane ID pointer.
util::shared_t<plane_t> plane; ///< Plane.
};
/**
* @brief Cursor position and visibility for the current capture frame.
*/
struct cursor_t {
// Public properties used during blending
bool visible = false; ///< Whether the KMS cursor plane is visible.
std::int32_t x; ///< X.
std::int32_t y; ///< Y.
std::uint32_t dst_w; ///< Dst w.
std::uint32_t dst_h; ///< Dst h.
std::uint32_t src_w; ///< Src w.
std::uint32_t src_h; ///< Src h.
std::vector<std::uint8_t> pixels; ///< Pixels.
unsigned long serial; ///< Serial.
// Private properties used for tracking cursor changes
std::uint64_t prop_src_x; ///< Prop src x.
std::uint64_t prop_src_y; ///< Prop src y.
std::uint64_t prop_src_w; ///< Prop src w.
std::uint64_t prop_src_h; ///< Prop src h.
std::uint32_t fb_id; ///< Fb ID.
};
/**
* @brief DRM card, render node, and plane metadata used for KMS capture.
*/
class card_t {
public:
/**
* @brief Internal connector metadata tuple used while selecting a monitor.
*/
using connector_interal_t = util::safe_ptr<drmModeConnector, drmModeFreeConnector>;
/**
* @brief Open a DRM connector and cache its monitor metadata.
*
* @param path Filesystem path for the DRM device or resource.
* @return 0 on success; nonzero or negative platform status on failure.
*/
int init(const char *path) {
cap_sys_admin admin;
fd.el = open_drm_card_fd(path);
if (fd.el < 0) {
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;
}
/**
* @brief Return framebuffer metadata for the current CRTC.
*
* @param plane DRM or EGL plane index being described.
* @return Framebuffer metadata wrapper, or nullptr when the framebuffer cannot be read.
*/
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>(fd.el, fb2);
}
auto fb = drmModeGetFB(fd.el, plane->fb_id);
if (fb) {
return std::make_unique<wrapper_fb>(fd.el, fb);
}
return nullptr;
}
/**
* @brief Return the DRM CRTC object for the monitor.
*
* @param id DRM CRTC ID.
* @return Owning pointer to the DRM CRTC object.
*/
crtc_t crtc(std::uint32_t id) {
return drmModeGetCrtc(fd.el, id);
}
/**
* @brief Return the DRM encoder object for the connector.
*
* @param id DRM encoder ID.
* @return Owning pointer to the DRM encoder object.
*/
encoder_t encoder(std::uint32_t id) {
return drmModeGetEncoder(fd.el, id);
}
/**
* @brief Return the DRM resource list for the card.
*
* @return DRM card resource list.
*/
res_t res() {
return drmModeGetResources(fd.el);
}
/**
* @brief Check whether nvidia.
*
* @return True when the DRM device appears to be driven by NVIDIA.
*/
bool is_nvidia() {
version_t ver {drmGetVersion(fd.el)};
return ver && ver->name && strncmp(ver->name, "nvidia-drm", 10) == 0;
}
/**
* @brief Check whether cursor.
*
* @param plane_id Plane ID.
* @return True when the DRM plane is a cursor plane.
*/
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;
}
/**
* @brief Look up a DRM property value by property name.
*
* @param props DRM property collection to inspect.
* @param name DRM property name to search for.
* @return Property value when the property exists.
*/
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;
}
/**
* @brief Get panel orientation.
*
* @param plane_id Plane ID.
* @return DRM rotation bitmask for the panel orientation.
*/
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;
}
/**
* @brief Get crtc index by ID.
*
* @param crtc_id Crtc ID.
* @return Zero-based CRTC index, or -1 when the CRTC ID is unknown.
*/
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;
}
/**
* @brief Return the DRM connector object for the display.
*
* @param id DRM connector ID.
* @return Owning pointer to the DRM connector object.
*/
connector_interal_t connector(std::uint32_t id) {
return drmModeGetConnector(fd.el, id);
}
/**
* @brief Refresh the monitor list reported by the display server.
*
* @param conn_type_count Conn type count.
* @return Connector descriptors for monitors known to the DRM card.
*/
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;
}
}
++conn_type_count[conn->connector_type];
monitors.emplace_back(connector_t {
conn->connector_type,
crtc_id,
conn->connector_type_id,
conn->connector_id,
conn->connection == DRM_MODE_CONNECTED,
});
});
return monitors;
}
/**
* @brief Return the DRM file descriptor owned by the object.
*
* @param handle GEM handle exported by the DRM framebuffer.
* @return DMA-BUF file descriptor for the GEM handle.
*/
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;
}
/**
* @brief Return DRM object properties for the resource.
*
* @param id DRM object ID.
* @param type DRM object type.
* @return DRM properties and their current values.
*/
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;
}
/**
* @brief Return DRM plane properties.
*
* @param id DRM plane ID.
* @return Plane properties and their current values.
*/
std::vector<std::pair<prop_t, std::uint64_t>> plane_props(std::uint32_t id) {
return props(id, DRM_MODE_OBJECT_PLANE);
}
/**
* @brief Return DRM CRTC properties.
*
* @param id DRM CRTC ID.
* @return CRTC properties and their current values.
*/
std::vector<std::pair<prop_t, std::uint64_t>> crtc_props(std::uint32_t id) {
return props(id, DRM_MODE_OBJECT_CRTC);
}
/**
* @brief Return DRM connector properties.
*
* @param id DRM connector ID.
* @return Connector properties and their current values.
*/
std::vector<std::pair<prop_t, std::uint64_t>> connector_props(std::uint32_t id) {
return props(id, DRM_MODE_OBJECT_CONNECTOR);
}
/**
* @brief Fetch DRM plane metadata by plane-list index.
*
* @param index Zero-based index into the DRM plane resource list.
* @return Plane metadata for the requested DRM plane.
*/
plane_t operator[](std::uint32_t index) {
return drmModeGetPlane(fd.el, plane_res->planes[index]);
}
/**
* @brief Return the number of items in the wrapped DRM collection.
*
* @return Number of DRM planes reported by the card.
*/
std::uint32_t count() {
return plane_res->count_planes;
}
/**
* @brief Return an iterator to the first byte in the buffer view.
*
* @return Iterator to the first element.
*/
plane_it_t begin() const {
return plane_it_t {fd.el, plane_res->planes, plane_res->planes + plane_res->count_planes};
}
/**
* @brief Return an iterator one past the final byte in the buffer view.
*
* @return Iterator one past the last element.
*/
plane_it_t end() const {
return plane_it_t {fd.el, plane_res->planes + plane_res->count_planes};
}
file_t fd; ///< DRM card file descriptor.
file_t render_fd; ///< Render fd.
plane_res_t plane_res; ///< Plane res.
};
/**
* @brief Build a lookup from DRM CRTC IDs to monitor descriptors.
*
* @param connectors DRM connector list being mapped to monitors.
* @return Map keyed by CRTC ID.
*/
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;
}
/**
* @brief Multi-source KMS image assembled for encoding.
*/
struct kms_img_t: public img_t {
~kms_img_t() override {
delete[] data;
data = nullptr;
}
};
/**
* @brief Write a debug log representation of the input packet.
*
* @param plane DRM or EGL plane index being described.
* @param fb Framebuffer object to bind or update.
* @param crtc DRM CRTC identifier to map.
*/
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();
}
/**
* @brief Map display name to monitor index
*
* @param display_name Name of the display to determine monitor index for (or monitor index string value)
* @return monitor's display index
*/
static int64_t map_display_name_to_monitor_index(const std::string_view &display_name) {
// Handle (legacy) monitor index strings by converting them to integer
if (display_name.empty() || std::ranges::all_of(display_name, ::isdigit)) {
return util::from_view(display_name);
}
// display_name is a connector name (not empty and containing non-digits)
for (auto &card_descriptor : kms::card_descriptors) {
for (const auto &monitor_descriptor : card_descriptor.crtc_to_monitor | std::views::values) {
if (display_name == std::format("{}-{}", drmModeGetConnectorTypeName(monitor_descriptor.type), monitor_descriptor.index)) {
BOOST_LOG(info) << "Mapped '"sv << display_name << "' to kmsgrab monitor index " << monitor_descriptor.monitor_index;
return monitor_descriptor.monitor_index;
}
}
}
BOOST_LOG(warning) << "Couldn't map '"sv << display_name << "' to a monitor index. Falling back to first monitor in list (index=0).";
return 0; // Fallback to first index if nothing can be matched
}
/**
* @brief Base KMS display capture backend shared by RAM and VRAM paths.
*/
class display_t: public platf::display_t {
public:
/**
* @brief Initialize common KMS display state for the requested memory type.
*
* @param mem_type Mem type.
*/
display_t(mem_type_e mem_type):
platf::display_t(),
mem_type {mem_type} {
}
/**
* @brief Initialize the base KMS capture state for the selected monitor.
*
* @param display_name Display name.
* @param config Configuration values to apply.
* @return 0 on success; nonzero or negative platform status on failure.
*/
int init(const std::string &display_name, const ::video::config_t &config) {
delay = ::video::capture_frame_interval(config);
int monitor_index = map_display_name_to_monitor_index(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_string();
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;
}
}
// Skip Nvidia cards if we're looking for VAAPI devices
// This is important for hybrid GPU laptops where the display
// may be connected through NVIDIA but rendering happens on Intel
if (mem_type == mem_type_e::vaapi && card.is_nvidia()) {
BOOST_LOG(debug) << file << " is an NVIDIA card, skipping for VAAPI"sv;
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;