Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
kmsgrab.cpp
Go to the documentation of this file.
1
5// standard includes
6#include <array>
7#include <cstdio>
8#include <cstdlib>
9#include <cstring>
10#include <errno.h>
11#include <fcntl.h>
12#include <filesystem>
13#include <limits>
14#include <string>
15#include <thread>
16#include <unistd.h>
17
18// platform includes
19#include <drm_fourcc.h>
20#include <linux/dma-buf.h>
21#include <linux/sync_file.h>
22#include <poll.h>
23#include <sys/capability.h>
24#include <sys/mman.h>
25#include <sys/stat.h>
26#include <xf86drm.h>
27#include <xf86drmMode.h>
28
29// local includes
30#include "cuda.h"
31#include "dmabuf_mapping.h"
32#include "graphics.h"
33#include "misc.h"
34#include "pyrowave.h"
35#include "src/config.h"
36#include "src/logging.h"
37#include "src/platform/common.h"
38#include "src/round_robin.h"
39#include "src/utility.h"
40#include "src/video.h"
41#include "vaapi.h"
42#include "virtual_display.h"
43#include "wayland.h"
44
45using namespace std::literals;
46namespace fs = std::filesystem;
47
48namespace platf {
49
50 namespace kms {
51
52 // Rolling average of the per-frame capture cost, logged every 120 frames.
53 // Used to compare the Hermes zero-copy ACQUIRE_FRAME against EVDI's CPU
54 // copy_to() under identical conditions. @label distinguishes the backend.
55 inline void accumulate_capture_metric(const char *label, long long ns) {
56 static thread_local long long sum = 0;
57 static thread_local long long peak = 0;
58 static thread_local int count = 0;
59 sum += ns;
60 peak = std::max(peak, ns);
61 if (++count >= 120) {
62 BOOST_LOG(info) << "[capture-metric/" << label << "] avg="
63 << (sum / count) / 1000.0 << "us peak=" << peak / 1000.0
64 << "us over " << count << " frames";
65 sum = 0;
66 peak = 0;
67 count = 0;
68 }
69 }
70
71 enum class hermes_fence_wait_e {
72 ready,
73 timeout,
74 failed,
75 error,
76 };
77
78 // WAIT_FRAME takes an unsigned timeout while poll() takes a signed one.
79 // Clamp once so acquisition and explicit-fence waiting share one bounded
80 // deadline and a very large caller duration cannot wrap either API.
81 inline std::uint32_t hermes_timeout_ms(std::chrono::milliseconds timeout) {
82 if (timeout <= 0ms) {
83 return 1;
84 }
85
86 constexpr auto max_poll_timeout = std::chrono::milliseconds {
87 std::numeric_limits<int>::max()
88 };
89 if (timeout >= max_poll_timeout) {
90 return static_cast<std::uint32_t>(std::numeric_limits<int>::max());
91 }
92 return static_cast<std::uint32_t>(timeout.count());
93 }
94
95 // A sync_file becomes pollable for both successful and failed fences.
96 // Query its status after poll() so a producer error is never mistaken for
97 // a frame that is safe to import or read.
98 inline hermes_fence_wait_e wait_hermes_frame_fence(
99 int fd,
100 std::chrono::steady_clock::time_point deadline
101 ) {
102 while (true) {
103 const auto now = std::chrono::steady_clock::now();
104 int wait_ms = 0;
105 if (now < deadline) {
106 const auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now);
107 wait_ms = static_cast<int>(std::max<std::int64_t>(1, remaining.count()));
108 }
109
110 pollfd fence_poll {fd, POLLIN, 0};
111 const int poll_result = ::poll(&fence_poll, 1, wait_ms);
112 if (poll_result < 0) {
113 if (errno == EINTR) {
114 continue;
115 }
116 return hermes_fence_wait_e::error;
117 }
118 if (poll_result == 0) {
119 errno = ETIMEDOUT;
120 return hermes_fence_wait_e::timeout;
121 }
122 if (fence_poll.revents & POLLNVAL) {
123 errno = EBADF;
124 return hermes_fence_wait_e::error;
125 }
126
127 sync_file_info info {};
128 int info_result;
129 do {
130 info_result = ::ioctl(fd, SYNC_IOC_FILE_INFO, &info);
131 } while (info_result < 0 && errno == EINTR);
132 if (info_result < 0) {
133 return hermes_fence_wait_e::error;
134 }
135 if (info.status < 0) {
136 errno = info.status >= -4095 ? -info.status : EIO;
137 return hermes_fence_wait_e::failed;
138 }
139 if (info.status > 0) {
140 return hermes_fence_wait_e::ready;
141 }
142
143 // poll() should not report an active fence as readable. Treat any
144 // other terminal event as a malformed sync_file instead of spinning.
145 errno = EIO;
146 return hermes_fence_wait_e::error;
147 }
148 }
149
150 inline capture_e hermes_acquire_failure(const char *path, int acquire_errno) {
151 if (acquire_errno == ETIMEDOUT || acquire_errno == EAGAIN) {
152 return capture_e::timeout;
153 }
154 if (acquire_errno == EINTR) {
155 return capture_e::interrupted;
156 }
157
158 if (!acquire_errno) {
159 acquire_errno = EPROTO;
160 }
161 BOOST_LOG(error) << "Hermes-KMS "sv << path
162 << " capture failed; reinitializing: "sv
163 << strerror(acquire_errno);
164 return capture_e::reinit;
165 }
166
167 inline int hermes_dma_buf_sync(int fd, std::uint64_t flags) {
168 dma_buf_sync sync {};
169 sync.flags = flags;
170
171 int result;
172 do {
173 result = ::ioctl(fd, DMA_BUF_IOCTL_SYNC, &sync);
174 } while (result < 0 && errno == EINTR);
175 return result;
176 }
177
178 class cap_sys_admin {
179 public:
180 cap_sys_admin() {
181 caps = cap_get_proc();
182
183 cap_value_t sys_admin = CAP_SYS_ADMIN;
184 if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_admin, CAP_SET) || cap_set_proc(caps)) {
185 BOOST_LOG(error) << "Failed to gain CAP_SYS_ADMIN";
186 }
187 }
188
189 ~cap_sys_admin() {
190 cap_value_t sys_admin = CAP_SYS_ADMIN;
191 if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_admin, CAP_CLEAR) || cap_set_proc(caps)) {
192 BOOST_LOG(error) << "Failed to drop CAP_SYS_ADMIN";
193 }
194 cap_free(caps);
195 }
196
197 cap_t caps;
198 };
199
200 class wrapper_fb {
201 public:
202 wrapper_fb(drmModeFB *fb):
203 fb {fb},
204 fb_id {fb->fb_id},
205 width {fb->width},
206 height {fb->height} {
207 pixel_format = DRM_FORMAT_XRGB8888;
208 modifier = DRM_FORMAT_MOD_INVALID;
209 std::fill_n(handles, 4, 0);
210 std::fill_n(pitches, 4, 0);
211 std::fill_n(offsets, 4, 0);
212 handles[0] = fb->handle;
213 pitches[0] = fb->pitch;
214 }
215
216 wrapper_fb(drmModeFB2 *fb2):
217 fb2 {fb2},
218 fb_id {fb2->fb_id},
219 width {fb2->width},
220 height {fb2->height} {
221 pixel_format = fb2->pixel_format;
222 modifier = (fb2->flags & DRM_MODE_FB_MODIFIERS) ? fb2->modifier : DRM_FORMAT_MOD_INVALID;
223
224 memcpy(handles, fb2->handles, sizeof(handles));
225 memcpy(pitches, fb2->pitches, sizeof(pitches));
226 memcpy(offsets, fb2->offsets, sizeof(offsets));
227 }
228
229 ~wrapper_fb() {
230 if (fb) {
231 drmModeFreeFB(fb);
232 } else if (fb2) {
233 drmModeFreeFB2(fb2);
234 }
235 }
236
237 drmModeFB *fb = nullptr;
238 drmModeFB2 *fb2 = nullptr;
239 uint32_t fb_id;
240 uint32_t width;
241 uint32_t height;
242 uint32_t pixel_format;
243 uint64_t modifier;
244 uint32_t handles[4];
245 uint32_t pitches[4];
246 uint32_t offsets[4];
247 };
248
249 using plane_res_t = util::safe_ptr<drmModePlaneRes, drmModeFreePlaneResources>;
250 using encoder_t = util::safe_ptr<drmModeEncoder, drmModeFreeEncoder>;
251 using res_t = util::safe_ptr<drmModeRes, drmModeFreeResources>;
252 using plane_t = util::safe_ptr<drmModePlane, drmModeFreePlane>;
253 using fb_t = std::unique_ptr<wrapper_fb>;
254 using crtc_t = util::safe_ptr<drmModeCrtc, drmModeFreeCrtc>;
255 using obj_prop_t = util::safe_ptr<drmModeObjectProperties, drmModeFreeObjectProperties>;
256 using prop_t = util::safe_ptr<drmModePropertyRes, drmModeFreeProperty>;
257 using prop_blob_t = util::safe_ptr<drmModePropertyBlobRes, drmModeFreePropertyBlob>;
258 using version_t = util::safe_ptr<drmVersion, drmFreeVersion>;
259
260 using conn_type_count_t = std::map<std::uint32_t, std::uint32_t>;
261
262 static int env_width;
263 static int env_height;
264
265 std::string_view plane_type(std::uint64_t val) {
266 switch (val) {
267 case DRM_PLANE_TYPE_OVERLAY:
268 return "DRM_PLANE_TYPE_OVERLAY"sv;
269 case DRM_PLANE_TYPE_PRIMARY:
270 return "DRM_PLANE_TYPE_PRIMARY"sv;
271 case DRM_PLANE_TYPE_CURSOR:
272 return "DRM_PLANE_TYPE_CURSOR"sv;
273 }
274
275 return "UNKNOWN"sv;
276 }
277
278 struct connector_t {
279 // For example: HDMI-A or HDMI
280 std::uint32_t type;
281
282 // Equals zero if not applicable
283 std::uint32_t crtc_id;
284
285 // For example HDMI-A-{index} or HDMI-{index}
286 std::uint32_t index;
287
288 // ID of the connector
289 std::uint32_t connector_id;
290
291 bool connected;
292 };
293
294 struct monitor_t {
295 // Connector attributes
296 std::uint32_t type;
297 std::uint32_t index;
298
299 // Monitor index in the global list
300 std::uint32_t monitor_index;
301
302 platf::touch_port_t viewport;
303 };
304
306 std::string path;
307
308 std::map<std::uint32_t, monitor_t> crtc_to_monitor;
309 };
310
311 static std::vector<card_descriptor_t> card_descriptors;
312
318 static std::string kernel_connector_name(std::uint32_t type, std::uint32_t type_id) {
319 static constexpr std::array<const char *, 21> names {
320 "Unknown", "VGA", "DVI-I", "DVI-D", "DVI-A", "Composite", "SVIDEO", "LVDS", "Component", "DIN",
321 "DP", "HDMI-A", "HDMI-B", "TV", "eDP", "Virtual", "DSI", "DPI", "Writeback", "SPI", "USB",
322 };
323 if (type >= names.size() || type_id == 0) {
324 return {};
325 }
326 return std::string {names[type]} + '-' + std::to_string(type_id);
327 }
328
329 static std::uint32_t from_view(const std::string_view &string) {
330#define _CONVERT(x, y) \
331 if (string == x) \
332 return DRM_MODE_CONNECTOR_##y
333
334 // This list was created from the following sources:
335 // https://gitlab.freedesktop.org/mesa/drm/-/blob/main/xf86drmMode.c (drmModeGetConnectorTypeName)
336 // https://gitlab.freedesktop.org/wayland/weston/-/blob/e74f2897b9408b6356a555a0ce59146836307ff5/libweston/backend-drm/drm.c#L1458-1477
337 // https://github.com/GNOME/mutter/blob/65d481594227ea7188c0416e8e00b57caeea214f/src/backends/meta-monitor-manager.c#L1618-L1639
338 _CONVERT("VGA"sv, VGA);
339 _CONVERT("DVII"sv, DVII);
340 _CONVERT("DVI-I"sv, DVII);
341 _CONVERT("DVID"sv, DVID);
342 _CONVERT("DVI-D"sv, DVID);
343 _CONVERT("DVIA"sv, DVIA);
344 _CONVERT("DVI-A"sv, DVIA);
345 _CONVERT("Composite"sv, Composite);
346 _CONVERT("SVIDEO"sv, SVIDEO);
347 _CONVERT("S-Video"sv, SVIDEO);
348 _CONVERT("LVDS"sv, LVDS);
349 _CONVERT("Component"sv, Component);
350 _CONVERT("9PinDIN"sv, 9PinDIN);
351 _CONVERT("DIN"sv, 9PinDIN);
352 _CONVERT("DisplayPort"sv, DisplayPort);
353 _CONVERT("DP"sv, DisplayPort);
354 _CONVERT("HDMIA"sv, HDMIA);
355 _CONVERT("HDMI-A"sv, HDMIA);
356 _CONVERT("HDMI"sv, HDMIA);
357 _CONVERT("HDMIB"sv, HDMIB);
358 _CONVERT("HDMI-B"sv, HDMIB);
359 _CONVERT("TV"sv, TV);
360 _CONVERT("eDP"sv, eDP);
361 _CONVERT("VIRTUAL"sv, VIRTUAL);
362 _CONVERT("Virtual"sv, VIRTUAL);
363 _CONVERT("DSI"sv, DSI);
364 _CONVERT("DPI"sv, DPI);
365 _CONVERT("WRITEBACK"sv, WRITEBACK);
366 _CONVERT("Writeback"sv, WRITEBACK);
367 _CONVERT("SPI"sv, SPI);
368#ifdef DRM_MODE_CONNECTOR_USB
369 _CONVERT("USB"sv, USB);
370#endif
371
372 // If the string starts with "Unknown", it may have the raw type
373 // value appended to the string. Let's try to read it.
374 if (string.find("Unknown"sv) == 0) {
375 std::uint32_t type;
376 std::string null_terminated_string {string};
377 if (std::sscanf(null_terminated_string.c_str(), "Unknown%u", &type) == 1) {
378 return type;
379 }
380 }
381
382 BOOST_LOG(error) << "Unknown Monitor connector type ["sv << string << "]: Please report this to the GitHub issue tracker"sv;
383 return DRM_MODE_CONNECTOR_Unknown;
384 }
385
386 class plane_it_t: public round_robin_util::it_wrap_t<plane_t::element_type, plane_it_t> {
387 public:
388 plane_it_t(int fd, std::uint32_t *plane_p, std::uint32_t *end):
389 fd {fd},
390 plane_p {plane_p},
391 end {end} {
392 load_next_valid_plane();
393 }
394
395 plane_it_t(int fd, std::uint32_t *end):
396 fd {fd},
397 plane_p {end},
398 end {end} {
399 }
400
401 void load_next_valid_plane() {
402 this->plane.reset();
403
404 for (; plane_p != end; ++plane_p) {
405 plane_t plane = drmModeGetPlane(fd, *plane_p);
406 if (!plane) {
407 BOOST_LOG(error) << "Couldn't get drm plane ["sv << (end - plane_p) << "]: "sv << strerror(errno);
408 continue;
409 }
410
411 this->plane = util::make_shared<plane_t>(plane.release());
412 break;
413 }
414 }
415
416 void inc() {
417 ++plane_p;
418 load_next_valid_plane();
419 }
420
421 bool eq(const plane_it_t &other) const {
422 return plane_p == other.plane_p;
423 }
424
425 plane_t::pointer get() {
426 return plane.get();
427 }
428
429 int fd;
430 std::uint32_t *plane_p;
431 std::uint32_t *end;
432
433 util::shared_t<plane_t> plane;
434 };
435
436 struct cursor_t {
437 // Public properties used during blending
438 bool visible = false;
439 std::int32_t x, y;
440 std::uint32_t dst_w, dst_h;
441 std::uint32_t src_w, src_h;
442 std::vector<std::uint8_t> pixels;
443 unsigned long serial;
444
445 // Private properties used for tracking cursor changes
446 std::uint64_t prop_src_x, prop_src_y, prop_src_w, prop_src_h;
447 std::uint32_t fb_id;
448 };
449
450 inline capture_e refresh_hermes_cursor(
451 int render_fd,
452 std::chrono::steady_clock::time_point deadline,
453 cursor_t &captured_cursor,
454 std::uint64_t &last_cursor_sequence
455 ) {
457 errno = 0;
458 if (!VDISPLAY::hermesKmsAcquireCursor(render_fd, true, cursor)) {
459 if (errno == ESTALE || errno == EAGAIN) {
460 return capture_e::timeout;
461 }
462 return hermes_acquire_failure("cursor", errno);
463 }
464 auto cursor_guard = util::fail_guard([&cursor]() { cursor.close(); });
465
466 if (!cursor.visible) {
467 captured_cursor.visible = false;
468 last_cursor_sequence = cursor.sequence;
469 return capture_e::ok;
470 }
471
472 constexpr std::uint32_t fixed_fraction_mask = (1U << 16) - 1U;
473 const bool integral_source =
474 ((cursor.src_x | cursor.src_y | cursor.src_w | cursor.src_h) & fixed_fraction_mask) == 0;
475 const std::uint32_t src_x = cursor.src_x >> 16;
476 const std::uint32_t src_y = cursor.src_y >> 16;
477 const std::uint32_t src_w = cursor.src_w >> 16;
478 const std::uint32_t src_h = cursor.src_h >> 16;
479 const bool supported_layout =
480 cursor.position_valid && cursor.geometry_valid && cursor.buffer_valid &&
481 cursor.plane_count == 1 && cursor.dma_buf_fd[0] >= 0 && cursor.sync_file_fd >= 0 &&
482 cursor.fourcc == DRM_FORMAT_ARGB8888 &&
483 (cursor.modifier == DRM_FORMAT_MOD_LINEAR || cursor.modifier == DRM_FORMAT_MOD_INVALID) &&
484 integral_source && src_w && src_h && cursor.crtc_w == src_w && cursor.crtc_h == src_h &&
485 src_x <= cursor.width && src_w <= cursor.width - src_x &&
486 src_y <= cursor.height && src_h <= cursor.height - src_y;
487 if (!supported_layout) {
488 BOOST_LOG(error) << "Hermes-KMS cursor capture: unsupported or malformed cursor layout."sv;
489 return capture_e::reinit;
490 }
491
492 const auto fence_status = wait_hermes_frame_fence(cursor.sync_file_fd, deadline);
493 if (fence_status == hermes_fence_wait_e::timeout) {
494 BOOST_LOG(warning) << "Hermes-KMS cursor capture: producer fence timed out."sv;
495 return capture_e::timeout;
496 }
497 if (fence_status == hermes_fence_wait_e::failed) {
498 const int fence_errno = errno;
499 BOOST_LOG(warning) << "Hermes-KMS cursor capture: dropping update "sv
500 << cursor.sequence << " after producer fence failure: "sv
501 << strerror(fence_errno);
502 captured_cursor.visible = false;
503 last_cursor_sequence = cursor.sequence;
504 return capture_e::ok;
505 }
506 if (fence_status == hermes_fence_wait_e::error) {
507 BOOST_LOG(error) << "Hermes-KMS cursor capture: invalid sync file: "sv << strerror(errno);
508 return capture_e::reinit;
509 }
510
511 const std::size_t pitch = cursor.pitch[0];
512 const std::size_t offset = cursor.offset[0];
513 const std::size_t source_x_bytes = static_cast<std::size_t>(src_x) * 4U;
514 const std::size_t row_bytes = static_cast<std::size_t>(src_w) * 4U;
515 const std::size_t last_source_row = static_cast<std::size_t>(src_y) + src_h - 1U;
516 if (pitch < source_x_bytes || row_bytes > pitch - source_x_bytes ||
517 last_source_row > (std::numeric_limits<std::size_t>::max() - offset) / pitch) {
518 BOOST_LOG(error) << "Hermes-KMS cursor capture: cursor row layout overflows size_t."sv;
519 return capture_e::reinit;
520 }
521 const std::size_t last_row_offset = offset + last_source_row * pitch;
522 if (source_x_bytes > std::numeric_limits<std::size_t>::max() - last_row_offset ||
523 row_bytes > std::numeric_limits<std::size_t>::max() - last_row_offset - source_x_bytes) {
524 BOOST_LOG(error) << "Hermes-KMS cursor capture: cursor mapping length overflows size_t."sv;
525 return capture_e::reinit;
526 }
527 const std::size_t map_len = last_row_offset + source_x_bytes + row_bytes;
528 if (static_cast<std::size_t>(src_h) >
529 std::numeric_limits<std::size_t>::max() / row_bytes) {
530 BOOST_LOG(error) << "Hermes-KMS cursor capture: cursor image size overflows size_t."sv;
531 return capture_e::reinit;
532 }
533
534 struct stat dmabuf_stat {};
535 if (::fstat(cursor.dma_buf_fd[0], &dmabuf_stat) < 0 || dmabuf_stat.st_size <= 0 ||
536 static_cast<std::uintmax_t>(map_len) > static_cast<std::uintmax_t>(dmabuf_stat.st_size)) {
537 BOOST_LOG(error) << "Hermes-KMS cursor capture: cursor metadata exceeds its DMA-BUF."sv;
538 return capture_e::reinit;
539 }
540
541 cursor_t next_cursor {};
542 next_cursor.pixels.resize(static_cast<std::size_t>(src_h) * row_bytes);
543 void *map = ::mmap(nullptr, map_len, PROT_READ, MAP_SHARED, cursor.dma_buf_fd[0], 0);
544 if (map == MAP_FAILED) {
545 BOOST_LOG(error) << "Hermes-KMS cursor capture: mmap failed: "sv << strerror(errno);
546 return capture_e::reinit;
547 }
548 if (hermes_dma_buf_sync(cursor.dma_buf_fd[0], DMA_BUF_SYNC_START | DMA_BUF_SYNC_READ) < 0) {
549 const int sync_errno = errno;
550 ::munmap(map, map_len);
551 BOOST_LOG(error) << "Hermes-KMS cursor capture: DMA_BUF_SYNC_START failed: "sv
552 << strerror(sync_errno);
553 return capture_e::reinit;
554 }
555
556 const auto *source = static_cast<const std::uint8_t *>(map) + offset +
557 static_cast<std::size_t>(src_y) * pitch + source_x_bytes;
558 for (std::size_t y = 0; y < src_h; ++y) {
559 std::memcpy(next_cursor.pixels.data() + y * row_bytes, source + y * pitch, row_bytes);
560 }
561
562 const int sync_end_result = hermes_dma_buf_sync(
563 cursor.dma_buf_fd[0],
564 DMA_BUF_SYNC_END | DMA_BUF_SYNC_READ
565 );
566 const int sync_end_errno = errno;
567 const int unmap_result = ::munmap(map, map_len);
568 const int unmap_errno = errno;
569 if (sync_end_result < 0 || unmap_result < 0) {
570 BOOST_LOG(error) << "Hermes-KMS cursor capture: cleanup failed: "sv
571 << strerror(sync_end_result < 0 ? sync_end_errno : unmap_errno);
572 return capture_e::reinit;
573 }
574
575 next_cursor.visible = true;
576 next_cursor.x = cursor.crtc_x;
577 next_cursor.y = cursor.crtc_y;
578 next_cursor.dst_w = cursor.crtc_w;
579 next_cursor.dst_h = cursor.crtc_h;
580 next_cursor.src_w = src_w;
581 next_cursor.src_h = src_h;
582 next_cursor.serial = captured_cursor.serial + 1;
583 next_cursor.prop_src_x = cursor.src_x;
584 next_cursor.prop_src_y = cursor.src_y;
585 next_cursor.prop_src_w = cursor.src_w;
586 next_cursor.prop_src_h = cursor.src_h;
587 captured_cursor = std::move(next_cursor);
588 last_cursor_sequence = cursor.sequence;
589 return capture_e::ok;
590 }
591
592 inline void attach_hermes_cursor(
593 egl::img_descriptor_t &img,
594 bool requested,
595 const cursor_t &captured_cursor
596 ) {
597 if (!requested || !captured_cursor.visible) {
598 img.data = nullptr;
599 return;
600 }
601
602 if (img.serial != captured_cursor.serial) {
603 img.buffer = captured_cursor.pixels;
604 img.serial = captured_cursor.serial;
605 }
606 img.cursor_premultiplied = true;
607 img.x = captured_cursor.x;
608 img.y = captured_cursor.y;
609 img.src_w = captured_cursor.src_w;
610 img.src_h = captured_cursor.src_h;
611 img.width = captured_cursor.dst_w;
612 img.height = captured_cursor.dst_h;
613 img.pixel_pitch = 4;
614 img.row_pitch = img.pixel_pitch * img.src_w;
615 img.data = img.buffer.data();
616 }
617
619 std::string hermes_fourcc_name(uint32_t fourcc) {
620 std::string name;
621 for (unsigned int i = 0; i < 4; ++i) {
622 const auto c = static_cast<char>((fourcc >> (8 * i)) & 0xff);
623 if (c < 0x20 || c > 0x7e) {
624 char hex[16];
625 std::snprintf(hex, sizeof(hex), "0x%08x", fourcc);
626 return hex;
627 }
628 name += c;
629 }
630 return name;
631 }
632
634 constexpr bool hermes_ten_bit_format(uint32_t fourcc) {
635 return fourcc == DRM_FORMAT_XRGB2101010 || fourcc == DRM_FORMAT_ARGB2101010 ||
636 fourcc == DRM_FORMAT_XBGR2101010 || fourcc == DRM_FORMAT_ABGR2101010;
637 }
638
641 constexpr bool hermes_cpu_copy_format(uint32_t fourcc) {
642 return fourcc == DRM_FORMAT_XRGB8888 || fourcc == DRM_FORMAT_ARGB8888 || hermes_ten_bit_format(fourcc);
643 }
644
651 inline void blend_hermes_cursor(img_t &img, const cursor_t &cursor, uint32_t fourcc = DRM_FORMAT_ARGB8888) {
652 if (!cursor.visible || !img.data || img.pixel_pitch != 4 || img.row_pitch <= 0 ||
653 img.width <= 0 || img.height <= 0 || !cursor.src_w || !cursor.src_h ||
654 cursor.src_w > std::numeric_limits<std::size_t>::max() / 4U) {
655 return;
656 }
657
658 const std::int32_t left = std::max<std::int32_t>(0, cursor.x);
659 const std::int32_t top = std::max<std::int32_t>(0, cursor.y);
660 const std::int64_t cursor_right = static_cast<std::int64_t>(cursor.x) + cursor.src_w;
661 const std::int64_t cursor_bottom = static_cast<std::int64_t>(cursor.y) + cursor.src_h;
662 const std::int32_t right = static_cast<std::int32_t>(
663 std::min<std::int64_t>(img.width, cursor_right)
664 );
665 const std::int32_t bottom = static_cast<std::int32_t>(
666 std::min<std::int64_t>(img.height, cursor_bottom)
667 );
668 if (left >= right || top >= bottom) {
669 return;
670 }
671
672 const std::size_t cursor_pitch = static_cast<std::size_t>(cursor.src_w) * 4U;
673 if (cursor.src_h > std::numeric_limits<std::size_t>::max() / cursor_pitch) {
674 return;
675 }
676 const std::size_t required_cursor_bytes = static_cast<std::size_t>(cursor.src_h) * cursor_pitch;
677 if (cursor.pixels.size() < required_cursor_bytes ||
678 static_cast<std::size_t>(img.row_pitch) < static_cast<std::size_t>(img.width) * 4U) {
679 return;
680 }
681
682 const std::size_t source_x = static_cast<std::size_t>(left - cursor.x);
683 const std::size_t source_y = static_cast<std::size_t>(top - cursor.y);
684 const bool ten_bit = hermes_ten_bit_format(fourcc);
685 // Bit offsets of the cursor's B, G and R bytes inside a 10-bit word.
686 const bool red_high = fourcc == DRM_FORMAT_XRGB2101010 || fourcc == DRM_FORMAT_ARGB2101010;
687 const unsigned int shifts[3] {red_high ? 0U : 20U, 10U, red_high ? 20U : 0U};
688 for (std::int32_t y = top; y < bottom; ++y) {
689 const auto *source = cursor.pixels.data() +
690 (source_y + static_cast<std::size_t>(y - top)) * cursor_pitch +
691 source_x * 4U;
692 auto *destination = img.data + static_cast<std::size_t>(y) * img.row_pitch +
693 static_cast<std::size_t>(left) * 4U;
694 for (std::int32_t x = left; x < right; ++x, source += 4, destination += 4) {
695 const unsigned int alpha = source[3];
696 if (ten_bit) {
697 if (!alpha) {
698 continue;
699 }
700 std::uint32_t word;
701 std::memcpy(&word, destination, sizeof(word));
702 std::uint32_t blended = word & 0xc0000000U;
703 for (unsigned int channel = 0; channel < 3; ++channel) {
704 const unsigned int below = (word >> shifts[channel]) & 1023U;
705 const unsigned int value = (source[channel] * 1023U + below * (255U - alpha) + 127U) / 255U;
706 blended |= std::min(value, 1023U) << shifts[channel];
707 }
708 std::memcpy(destination, &blended, sizeof(blended));
709 } else if (alpha == 255U) {
710 std::memcpy(destination, source, 4);
711 } else if (alpha) {
712 // DRM cursor pixels use premultiplied alpha.
713 destination[0] = static_cast<std::uint8_t>(
714 source[0] + (destination[0] * (255U - alpha) + 127U) / 255U
715 );
716 destination[1] = static_cast<std::uint8_t>(
717 source[1] + (destination[1] * (255U - alpha) + 127U) / 255U
718 );
719 destination[2] = static_cast<std::uint8_t>(
720 source[2] + (destination[2] * (255U - alpha) + 127U) / 255U
721 );
722 }
723 }
724 }
725 }
726
727#ifdef HERMES_TESTS
728 void blend_hermes_cursor_for_test(
729 img_t &img,
730 bool visible,
731 std::int32_t x,
732 std::int32_t y,
733 std::uint32_t width,
734 std::uint32_t height,
735 const std::vector<std::uint8_t> &pixels,
736 uint32_t fourcc
737 ) {
738 cursor_t cursor {};
739 cursor.visible = visible;
740 cursor.x = x;
741 cursor.y = y;
742 cursor.src_w = width;
743 cursor.src_h = height;
744 cursor.pixels = pixels;
745 blend_hermes_cursor(img, cursor, fourcc);
746 }
747#endif
748
749 class card_t {
750 public:
751 using connector_interal_t = util::safe_ptr<drmModeConnector, drmModeFreeConnector>;
752
753 int init(const char *path) {
754 cap_sys_admin admin;
755 fd.el = platf::open_drm_node(path, O_RDWR);
756
757 if (fd.el < 0) {
758 BOOST_LOG(error) << "Couldn't open: "sv << path << ": "sv << strerror(errno);
759 return -1;
760 }
761
762 version_t ver {drmGetVersion(fd.el)};
763 BOOST_LOG(info) << path << " -> "sv << ((ver && ver->name) ? ver->name : "UNKNOWN");
764
765 // Open the render node for this card to share with libva.
766 // If it fails, we'll just share the primary node instead.
767 char *rendernode_path = drmGetRenderDeviceNameFromFd(fd.el);
768 if (rendernode_path) {
769 BOOST_LOG(debug) << "Opening render node: "sv << rendernode_path;
770 render_fd.el = open(rendernode_path, O_RDWR);
771 if (render_fd.el < 0) {
772 // Hermes-KMS grants read-write on its render node to root only, so
773 // generic GPU probes skip it; Hermes reaches it read-only through
774 // its own path. Failing here is expected for it, not worth a warning.
775 const bool hermes_kms = errno == EACCES && ver && ver->name && ver->name == "hermes-kms"sv;
776 BOOST_LOG(hermes_kms ? debug : warning) << "Couldn't open render node: "sv << rendernode_path << ": "sv << strerror(errno);
777 render_fd.el = dup(fd.el);
778 }
779 free(rendernode_path);
780 } else {
781 BOOST_LOG(warning) << "No render device name for: "sv << path;
782 render_fd.el = dup(fd.el);
783 }
784
785 if (drmSetClientCap(fd.el, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1)) {
786 BOOST_LOG(error) << "GPU driver doesn't support universal planes: "sv << path;
787 return -1;
788 }
789
790 if (drmSetClientCap(fd.el, DRM_CLIENT_CAP_ATOMIC, 1)) {
791 BOOST_LOG(warning) << "GPU driver doesn't support atomic mode-setting: "sv << path;
792#if defined(HERMES_BUILD_X11)
793 // We won't be able to capture the mouse cursor with KMS on non-atomic drivers,
794 // so fall back to X11 if it's available and the user didn't explicitly force KMS.
795 if (window_system == window_system_e::X11 && config::video.capture != "kms") {
796 BOOST_LOG(info) << "Avoiding KMS capture under X11 due to lack of atomic mode-setting"sv;
797 return -1;
798 }
799#endif
800 BOOST_LOG(warning) << "Cursor capture may fail without atomic mode-setting support!"sv;
801 }
802
803 plane_res.reset(drmModeGetPlaneResources(fd.el));
804 if (!plane_res) {
805 BOOST_LOG(error) << "Couldn't get drm plane resources"sv;
806 return -1;
807 }
808
809 return 0;
810 }
811
812 fb_t fb(plane_t::pointer plane) {
813 cap_sys_admin admin;
814
815 auto fb2 = drmModeGetFB2(fd.el, plane->fb_id);
816 if (fb2) {
817 return std::make_unique<wrapper_fb>(fb2);
818 }
819
820 auto fb = drmModeGetFB(fd.el, plane->fb_id);
821 if (fb) {
822 return std::make_unique<wrapper_fb>(fb);
823 }
824
825 return nullptr;
826 }
827
828 crtc_t crtc(std::uint32_t id) {
829 return drmModeGetCrtc(fd.el, id);
830 }
831
832 encoder_t encoder(std::uint32_t id) {
833 return drmModeGetEncoder(fd.el, id);
834 }
835
836 res_t res() {
837 return drmModeGetResources(fd.el);
838 }
839
840 bool is_nvidia() {
841 version_t ver {drmGetVersion(fd.el)};
842 return ver && ver->name && strncmp(ver->name, "nvidia-drm", 10) == 0;
843 }
844
845 bool is_cursor(std::uint32_t plane_id) {
846 auto props = plane_props(plane_id);
847 for (auto &[prop, val] : props) {
848 if (prop->name == "type"sv) {
849 if (val == DRM_PLANE_TYPE_CURSOR) {
850 return true;
851 } else {
852 return false;
853 }
854 }
855 }
856
857 return false;
858 }
859
860 std::optional<std::uint64_t> prop_value_by_name(const std::vector<std::pair<prop_t, std::uint64_t>> &props, std::string_view name) {
861 for (auto &[prop, val] : props) {
862 if (prop->name == name) {
863 return val;
864 }
865 }
866 return std::nullopt;
867 }
868
869 std::uint32_t get_panel_orientation(std::uint32_t plane_id) {
870 auto props = plane_props(plane_id);
871 auto value = prop_value_by_name(props, "rotation"sv);
872 if (value) {
873 return *value;
874 }
875
876 BOOST_LOG(error) << "Failed to determine panel orientation, defaulting to landscape.";
877 return DRM_MODE_ROTATE_0;
878 }
879
880 int get_crtc_index_by_id(std::uint32_t crtc_id) {
881 auto resources = res();
882 for (int i = 0; i < resources->count_crtcs; i++) {
883 if (resources->crtcs[i] == crtc_id) {
884 return i;
885 }
886 }
887 return -1;
888 }
889
890 connector_interal_t connector(std::uint32_t id) {
891 return drmModeGetConnector(fd.el, id);
892 }
893
894 std::vector<connector_t> monitors(conn_type_count_t &conn_type_count) {
895 auto resources = res();
896 if (!resources) {
897 BOOST_LOG(error) << "Couldn't get connector resources"sv;
898 return {};
899 }
900
901 std::vector<connector_t> monitors;
902 std::for_each_n(resources->connectors, resources->count_connectors, [this, &conn_type_count, &monitors](std::uint32_t id) {
903 auto conn = connector(id);
904
905 std::uint32_t crtc_id = 0;
906
907 if (conn->encoder_id) {
908 auto enc = encoder(conn->encoder_id);
909 if (enc) {
910 crtc_id = enc->crtc_id;
911 }
912 }
913
914 auto index = ++conn_type_count[conn->connector_type];
915
916 monitors.emplace_back(connector_t {
917 conn->connector_type,
918 crtc_id,
919 index,
920 conn->connector_id,
921 conn->connection == DRM_MODE_CONNECTED,
922 });
923 });
924
925 return monitors;
926 }
927
928 file_t handleFD(std::uint32_t handle) {
929 file_t fb_fd;
930
931 auto status = drmPrimeHandleToFD(fd.el, handle, 0 /* flags */, &fb_fd.el);
932 if (status) {
933 return {};
934 }
935
936 return fb_fd;
937 }
938
939 std::vector<std::pair<prop_t, std::uint64_t>> props(std::uint32_t id, std::uint32_t type) {
940 obj_prop_t obj_prop = drmModeObjectGetProperties(fd.el, id, type);
941 if (!obj_prop) {
942 return {};
943 }
944
945 std::vector<std::pair<prop_t, std::uint64_t>> props;
946 props.reserve(obj_prop->count_props);
947
948 for (auto x = 0; x < obj_prop->count_props; ++x) {
949 props.emplace_back(drmModeGetProperty(fd.el, obj_prop->props[x]), obj_prop->prop_values[x]);
950 }
951
952 return props;
953 }
954
955 std::vector<std::pair<prop_t, std::uint64_t>> plane_props(std::uint32_t id) {
956 return props(id, DRM_MODE_OBJECT_PLANE);
957 }
958
959 std::vector<std::pair<prop_t, std::uint64_t>> crtc_props(std::uint32_t id) {
960 return props(id, DRM_MODE_OBJECT_CRTC);
961 }
962
963 std::vector<std::pair<prop_t, std::uint64_t>> connector_props(std::uint32_t id) {
964 return props(id, DRM_MODE_OBJECT_CONNECTOR);
965 }
966
967 plane_t operator[](std::uint32_t index) {
968 return drmModeGetPlane(fd.el, plane_res->planes[index]);
969 }
970
971 std::uint32_t count() {
972 return plane_res->count_planes;
973 }
974
975 plane_it_t begin() const {
976 return plane_it_t {fd.el, plane_res->planes, plane_res->planes + plane_res->count_planes};
977 }
978
979 plane_it_t end() const {
980 return plane_it_t {fd.el, plane_res->planes + plane_res->count_planes};
981 }
982
983 file_t fd;
984 file_t render_fd;
985 plane_res_t plane_res;
986 };
987
988 std::map<std::uint32_t, monitor_t> map_crtc_to_monitor(const std::vector<connector_t> &connectors) {
989 std::map<std::uint32_t, monitor_t> result;
990
991 for (auto &connector : connectors) {
992 result.emplace(connector.crtc_id, monitor_t {
993 connector.type,
994 connector.index,
995 });
996 }
997
998 return result;
999 }
1000
1001 struct kms_img_t: public img_t {
1002 ~kms_img_t() override {
1003 delete[] data;
1004 data = nullptr;
1005 }
1006 };
1007
1008#ifdef HERMES_BUILD_CUDA
1010 struct cuda_host_img_t: public img_t {
1011 ~cuda_host_img_t() override {
1012 cuda::free_host(data);
1013 data = nullptr;
1014 }
1015 };
1016
1018 cuda::pixel::layout_e hermes_cuda_layout(uint32_t fourcc) {
1019 switch (fourcc) {
1020 case DRM_FORMAT_XRGB2101010:
1021 case DRM_FORMAT_ARGB2101010:
1023 case DRM_FORMAT_XBGR2101010:
1024 case DRM_FORMAT_ABGR2101010:
1026 default:
1028 }
1029 }
1030#endif
1031
1032 void print(plane_t::pointer plane, fb_t::pointer fb, crtc_t::pointer crtc) {
1033 if (crtc) {
1034 BOOST_LOG(debug) << "crtc("sv << crtc->x << ", "sv << crtc->y << ')';
1035 BOOST_LOG(debug) << "crtc("sv << crtc->width << ", "sv << crtc->height << ')';
1036 BOOST_LOG(debug) << "plane->possible_crtcs == "sv << plane->possible_crtcs;
1037 }
1038
1039 BOOST_LOG(debug)
1040 << "x("sv << plane->x
1041 << ") y("sv << plane->y
1042 << ") crtc_x("sv << plane->crtc_x
1043 << ") crtc_y("sv << plane->crtc_y
1044 << ") crtc_id("sv << plane->crtc_id
1045 << ')';
1046
1047 BOOST_LOG(debug)
1048 << "Resolution: "sv << fb->width << 'x' << fb->height
1049 << ": Pitch: "sv << fb->pitches[0]
1050 << ": Offset: "sv << fb->offsets[0];
1051
1052 std::stringstream ss;
1053
1054 ss << "Format ["sv;
1055 std::for_each_n(plane->formats, plane->count_formats - 1, [&ss](auto format) {
1056 ss << util::view(format) << ", "sv;
1057 });
1058
1059 ss << util::view(plane->formats[plane->count_formats - 1]) << ']';
1060
1061 BOOST_LOG(debug) << ss.str();
1062 }
1063
1064 class display_t: public platf::display_t {
1065 public:
1066 display_t(mem_type_e mem_type):
1068 mem_type {mem_type} {
1069 }
1070
1071 int init(const std::string &display_name, const ::video::config_t &config) {
1072 delay = std::chrono::nanoseconds {1s} / config.framerate;
1073
1074 // EVDI exposes a real DRM card. Virtual display names identify that
1075 // card so we never silently capture the user's primary monitor.
1076 int monitor_index = 0;
1077 std::string virtual_card;
1078 constexpr std::string_view virtual_card_prefix {"VIRTUAL-card"};
1079 const auto hermes_card_index = VDISPLAY::getHermesKmsCardIndex(display_name);
1080 const auto evdi_card_index = VDISPLAY::getEvdiCardIndex(display_name);
1081 if (hermes_card_index >= 0) {
1082 virtual_card = "card" + std::to_string(hermes_card_index);
1083 } else if (evdi_card_index >= 0) {
1084 virtual_card = "card" + std::to_string(evdi_card_index);
1085 } else if (display_name.rfind(virtual_card_prefix, 0) == 0) {
1086 const auto card_index = display_name.substr(virtual_card_prefix.size());
1087 if (card_index.empty() || card_index.find_first_not_of("0123456789") != std::string::npos) {
1088 BOOST_LOG(error) << "Invalid virtual display name ["sv << display_name << ']';
1089 return -1;
1090 }
1091 virtual_card = "card" + card_index;
1092 } else if (display_name.rfind("VIRTUAL-", 0) != 0) {
1093 // Not a virtual display, parse as numeric index
1094 monitor_index = util::from_view(display_name);
1095 } else {
1096 BOOST_LOG(error) << "Virtual display ["sv << display_name << "] has no DRM card mapping"sv;
1097 return -1;
1098 }
1099 int monitor = 0;
1100
1101 fs::path card_dir {"/dev/dri"sv};
1102 for (auto &entry : fs::directory_iterator {card_dir}) {
1103 auto file = entry.path().filename();
1104
1105 auto filestring = file.generic_string();
1106 if (filestring.size() < 4 || std::string_view {filestring}.substr(0, 4) != "card"sv) {
1107 continue;
1108 }
1109 if (!virtual_card.empty() && filestring != virtual_card) {
1110 continue;
1111 }
1112
1113 kms::card_t card;
1114 if (card.init(entry.path().c_str())) {
1115 continue;
1116 }
1117
1118 // Skip non-Nvidia cards if we're looking for CUDA devices
1119 // unless NVENC is selected manually by the user
1120 if (virtual_card.empty() && mem_type == mem_type_e::cuda && !card.is_nvidia()) {
1121 BOOST_LOG(debug) << file << " is not a CUDA device"sv;
1122 if (config::video.encoder != "nvenc") {
1123 continue;
1124 }
1125 }
1126
1127 auto end = std::end(card);
1128 for (auto plane = std::begin(card); plane != end; ++plane) {
1129 // Skip unused planes
1130 if (!plane->fb_id) {
1131 continue;
1132 }
1133
1134 if (card.is_cursor(plane->plane_id)) {
1135 continue;
1136 }
1137
1138 if (monitor != monitor_index) {
1139 ++monitor;
1140 continue;
1141 }
1142
1143 auto fb = card.fb(plane.get());
1144 if (!fb) {
1145 BOOST_LOG(error) << "Couldn't get drm fb for plane ["sv << plane->fb_id << "]: "sv << strerror(errno);
1146 return -1;
1147 }
1148
1149 if (!fb->handles[0]) {
1150 BOOST_LOG(error) << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Probably not permitted"sv;
1151 return -1;
1152 }
1153
1154 for (int i = 0; i < 4; ++i) {
1155 if (!fb->handles[i]) {
1156 break;
1157 }
1158
1159 auto fb_fd = card.handleFD(fb->handles[i]);
1160 if (fb_fd.el < 0) {
1161 BOOST_LOG(error) << "Couldn't get primary file descriptor for Framebuffer ["sv << fb->fb_id << "]: "sv << strerror(errno);
1162 continue;
1163 }
1164 }
1165
1166 auto crtc = card.crtc(plane->crtc_id);
1167 if (!crtc) {
1168 BOOST_LOG(error) << "Couldn't get CRTC info: "sv << strerror(errno);
1169 continue;
1170 }
1171
1172 BOOST_LOG(info) << "Found monitor for DRM screencasting"sv;
1173
1174 // We need to find the correct /dev/dri/card{nr} to correlate the crtc_id with the monitor descriptor
1175 auto pos = std::find_if(std::begin(card_descriptors), std::end(card_descriptors), [&](card_descriptor_t &cd) {
1176 return cd.path == filestring;
1177 });
1178
1179 if (pos == std::end(card_descriptors) && virtual_card.empty()) {
1180 // card_descriptors is populated by display enumeration. Physical
1181 // displays need it for desktop-coordinate correlation.
1182 BOOST_LOG(error) << "Couldn't find ["sv << entry.path() << "]: This shouldn't have happened :/"sv;
1183 return -1;
1184 }
1185
1186 // TODO: surf_sd = fb->to_sd();
1187
1188 kms::print(plane.get(), fb.get(), crtc.get());
1189
1190 img_width = fb->width;
1191 img_height = fb->height;
1192 img_offset_x = crtc->x;
1193 img_offset_y = crtc->y;
1194
1195 this->env_width = ::platf::kms::env_width;
1196 this->env_height = ::platf::kms::env_height;
1197
1198 if (pos != std::end(card_descriptors) &&
1199 pos->crtc_to_monitor.find(plane->crtc_id) != std::end(pos->crtc_to_monitor)) {
1200 auto monitor = pos->crtc_to_monitor.find(plane->crtc_id);
1201 auto &viewport = monitor->second.viewport;
1202
1203 width = viewport.width;
1204 height = viewport.height;
1205
1206 switch (card.get_panel_orientation(plane->plane_id)) {
1207 case DRM_MODE_ROTATE_270:
1208 BOOST_LOG(debug) << "Detected panel orientation at 90, swapping width and height.";
1209 width = viewport.height;
1210 height = viewport.width;
1211 break;
1212 case DRM_MODE_ROTATE_90:
1213 case DRM_MODE_ROTATE_180:
1214 BOOST_LOG(warning) << "Panel orientation is unsupported, screen capture may not work correctly.";
1215 break;
1216 }
1217
1218 offset_x = viewport.offset_x;
1219 offset_y = viewport.offset_y;
1220 }
1221
1222 // The virtual EVDI card can be ready before the asynchronous
1223 // global display enumeration has populated card_descriptors. Its
1224 // CRTC dimensions are sufficient for capture, so avoid a delayed
1225 // retry just to obtain desktop-coordinate metadata.
1226 else {
1227 BOOST_LOG(virtual_card.empty() ? warning : debug)
1228 << "Using CRTC geometry because no monitor descriptor is available."sv;
1229 width = crtc->width;
1230 height = crtc->height;
1231 offset_x = crtc->x;
1232 offset_y = crtc->y;
1233 if (!virtual_card.empty()) {
1234 // An isolated EVDI display is its own desktop from the
1235 // stream's perspective. Keep absolute input coordinates in
1236 // that space even before Wayland/KMS correlation completes.
1237 this->env_width = width;
1238 this->env_height = height;
1239 }
1240 }
1241
1242 plane_id = plane->plane_id;
1243 crtc_id = plane->crtc_id;
1244 crtc_index = card.get_crtc_index_by_id(plane->crtc_id);
1245
1246 // Find the connector for this CRTC
1247 kms::conn_type_count_t conn_type_count;
1248 for (auto &connector : card.monitors(conn_type_count)) {
1249 if (connector.crtc_id == crtc_id) {
1250 BOOST_LOG(info) << "Found connector ID ["sv << connector.connector_id << ']';
1251
1252 connector_id = connector.connector_id;
1253
1254 // A physical monitor: report its connector so touch and pen can be
1255 // bound to the output this session streams.
1256 if (virtual_card.empty()) {
1257 auto conn = card.connector(connector.connector_id);
1258 if (conn) {
1259 const auto name = kernel_connector_name(conn->connector_type, conn->connector_type_id);
1260 if (!name.empty()) {
1261 VDISPLAY::notePhysicalCaptureOutput(name);
1262 }
1263 }
1264 }
1265
1266 auto connector_props = card.connector_props(*connector_id);
1267 hdr_metadata_blob_id = card.prop_value_by_name(connector_props, "HDR_OUTPUT_METADATA"sv);
1268 }
1269 }
1270
1271 this->card = std::move(card);
1272 goto break_loop;
1273 }
1274 }
1275
1276 BOOST_LOG(error) << "Couldn't find monitor ["sv << monitor_index << ']';
1277 return -1;
1278
1279 // Neatly break from nested for loop
1280 break_loop:
1281
1282 // Look for the cursor plane for this CRTC
1283 cursor_plane_id = -1;
1284 auto end = std::end(card);
1285 for (auto plane = std::begin(card); plane != end; ++plane) {
1286 if (!card.is_cursor(plane->plane_id)) {
1287 continue;
1288 }
1289
1290 // NB: We do not skip unused planes here because cursor planes
1291 // will look unused if the cursor is currently hidden.
1292
1293 if (!(plane->possible_crtcs & (1 << crtc_index))) {
1294 // Skip cursor planes for other CRTCs
1295 continue;
1296 } else if (plane->possible_crtcs != (1 << crtc_index)) {
1297 // We assume a 1:1 mapping between cursor planes and CRTCs, which seems to
1298 // match the behavior of drivers in the real world. If it's violated, we'll
1299 // proceed anyway but print a warning in the log.
1300 BOOST_LOG(warning) << "Cursor plane spans multiple CRTCs!"sv;
1301 }
1302
1303 BOOST_LOG(info) << "Found cursor plane ["sv << plane->plane_id << ']';
1304 cursor_plane_id = plane->plane_id;
1305 break;
1306 }
1307
1308 if (cursor_plane_id < 0) {
1309 BOOST_LOG(warning) << "No KMS cursor plane found. Cursor may not be displayed while streaming!"sv;
1310 }
1311
1312 return 0;
1313 }
1314
1315 bool is_hdr() {
1316 if (!hdr_metadata_blob_id || *hdr_metadata_blob_id == 0) {
1317 return false;
1318 }
1319
1320 prop_blob_t hdr_metadata_blob = drmModeGetPropertyBlob(card.fd.el, *hdr_metadata_blob_id);
1321 if (hdr_metadata_blob == nullptr) {
1322 BOOST_LOG(error) << "Unable to get HDR metadata blob: "sv << strerror(errno);
1323 return false;
1324 }
1325
1326 if (hdr_metadata_blob->length < sizeof(uint32_t) + sizeof(hdr_metadata_infoframe)) {
1327 BOOST_LOG(error) << "HDR metadata blob is too small: "sv << hdr_metadata_blob->length;
1328 return false;
1329 }
1330
1331 auto raw_metadata = (hdr_output_metadata *) hdr_metadata_blob->data;
1332 if (raw_metadata->metadata_type != 0) { // HDMI_STATIC_METADATA_TYPE1
1333 BOOST_LOG(error) << "Unknown HDMI_STATIC_METADATA_TYPE value: "sv << raw_metadata->metadata_type;
1334 return false;
1335 }
1336
1337 if (raw_metadata->hdmi_metadata_type1.metadata_type != 0) { // Static Metadata Type 1
1338 BOOST_LOG(error) << "Unknown secondary metadata type value: "sv << raw_metadata->hdmi_metadata_type1.metadata_type;
1339 return false;
1340 }
1341
1342 // We only support Traditional Gamma SDR or SMPTE 2084 PQ HDR EOTFs.
1343 // Print a warning if we encounter any others.
1344 switch (raw_metadata->hdmi_metadata_type1.eotf) {
1345 case 0: // HDMI_EOTF_TRADITIONAL_GAMMA_SDR
1346 return false;
1347 case 1: // HDMI_EOTF_TRADITIONAL_GAMMA_HDR
1348 BOOST_LOG(warning) << "Unsupported HDR EOTF: Traditional Gamma"sv;
1349 return true;
1350 case 2: // HDMI_EOTF_SMPTE_ST2084
1351 return true;
1352 case 3: // HDMI_EOTF_BT_2100_HLG
1353 BOOST_LOG(warning) << "Unsupported HDR EOTF: HLG"sv;
1354 return true;
1355 default:
1356 BOOST_LOG(warning) << "Unsupported HDR EOTF: "sv << raw_metadata->hdmi_metadata_type1.eotf;
1357 return true;
1358 }
1359 }
1360
1361 bool requires_hdr_for_hdr_output() const override {
1362 return true;
1363 }
1364
1365 bool get_hdr_metadata(SS_HDR_METADATA &metadata) {
1366 // This performs all the metadata validation
1367 if (!is_hdr()) {
1368 return false;
1369 }
1370
1371 prop_blob_t hdr_metadata_blob = drmModeGetPropertyBlob(card.fd.el, *hdr_metadata_blob_id);
1372 if (hdr_metadata_blob == nullptr) {
1373 BOOST_LOG(error) << "Unable to get HDR metadata blob: "sv << strerror(errno);
1374 return false;
1375 }
1376
1377 auto raw_metadata = (hdr_output_metadata *) hdr_metadata_blob->data;
1378
1379 for (int i = 0; i < 3; i++) {
1380 metadata.displayPrimaries[i].x = raw_metadata->hdmi_metadata_type1.display_primaries[i].x;
1381 metadata.displayPrimaries[i].y = raw_metadata->hdmi_metadata_type1.display_primaries[i].y;
1382 }
1383
1384 metadata.whitePoint.x = raw_metadata->hdmi_metadata_type1.white_point.x;
1385 metadata.whitePoint.y = raw_metadata->hdmi_metadata_type1.white_point.y;
1386 metadata.maxDisplayLuminance = raw_metadata->hdmi_metadata_type1.max_display_mastering_luminance;
1387 metadata.minDisplayLuminance = raw_metadata->hdmi_metadata_type1.min_display_mastering_luminance;
1388 metadata.maxContentLightLevel = raw_metadata->hdmi_metadata_type1.max_cll;
1389 metadata.maxFrameAverageLightLevel = raw_metadata->hdmi_metadata_type1.max_fall;
1390
1391 return true;
1392 }
1393
1394 void update_cursor() {
1395 if (cursor_plane_id < 0) {
1396 return;
1397 }
1398
1399 plane_t plane = drmModeGetPlane(card.fd.el, cursor_plane_id);
1400 if (!plane) {
1401 // Same reasoning as the primary plane in refresh(), except that losing
1402 // the cursor plane costs a cursor rather than the stream. Give it up
1403 // the way the unusable-format cases below do, instead of asking again
1404 // at frame rate for something that is not coming back.
1405 BOOST_LOG(error) << "Couldn't get drm cursor plane ["sv << cursor_plane_id << "]: "sv << strerror(errno);
1406 cursor_plane_id = -1;
1407 captured_cursor.visible = false;
1408 return;
1409 }
1410
1411 std::optional<std::int32_t> prop_crtc_x;
1412 std::optional<std::int32_t> prop_crtc_y;
1413 std::optional<std::uint32_t> prop_crtc_w;
1414 std::optional<std::uint32_t> prop_crtc_h;
1415
1416 std::optional<std::uint64_t> prop_src_x;
1417 std::optional<std::uint64_t> prop_src_y;
1418 std::optional<std::uint64_t> prop_src_w;
1419 std::optional<std::uint64_t> prop_src_h;
1420
1421 auto props = card.plane_props(cursor_plane_id);
1422 for (auto &[prop, val] : props) {
1423 if (prop->name == "CRTC_X"sv) {
1424 prop_crtc_x = val;
1425 } else if (prop->name == "CRTC_Y"sv) {
1426 prop_crtc_y = val;
1427 } else if (prop->name == "CRTC_W"sv) {
1428 prop_crtc_w = val;
1429 } else if (prop->name == "CRTC_H"sv) {
1430 prop_crtc_h = val;
1431 } else if (prop->name == "SRC_X"sv) {
1432 prop_src_x = val;
1433 } else if (prop->name == "SRC_Y"sv) {
1434 prop_src_y = val;
1435 } else if (prop->name == "SRC_W"sv) {
1436 prop_src_w = val;
1437 } else if (prop->name == "SRC_H"sv) {
1438 prop_src_h = val;
1439 }
1440 }
1441
1442 if (!prop_crtc_w || !prop_crtc_h || !prop_crtc_x || !prop_crtc_y) {
1443 BOOST_LOG(error) << "Cursor plane is missing required plane CRTC properties!"sv;
1444 BOOST_LOG(error) << "Atomic mode-setting must be enabled to capture the cursor!"sv;
1445 cursor_plane_id = -1;
1446 captured_cursor.visible = false;
1447 return;
1448 }
1449 if (!prop_src_x || !prop_src_y || !prop_src_w || !prop_src_h) {
1450 BOOST_LOG(error) << "Cursor plane is missing required plane SRC properties!"sv;
1451 BOOST_LOG(error) << "Atomic mode-setting must be enabled to capture the cursor!"sv;
1452 cursor_plane_id = -1;
1453 captured_cursor.visible = false;
1454 return;
1455 }
1456
1457 // Update the cursor position and size unconditionally
1458 captured_cursor.x = *prop_crtc_x;
1459 captured_cursor.y = *prop_crtc_y;
1460 captured_cursor.dst_w = *prop_crtc_w;
1461 captured_cursor.dst_h = *prop_crtc_h;
1462
1463 // We're technically cheating a bit here by assuming that we can detect
1464 // changes to the cursor plane via property adjustments. If this isn't
1465 // true, we'll really have to mmap() the dmabuf and draw that every time.
1466 bool cursor_dirty = false;
1467
1468 if (!plane->fb_id) {
1469 captured_cursor.visible = false;
1470 captured_cursor.fb_id = 0;
1471 } else if (plane->fb_id != captured_cursor.fb_id) {
1472 BOOST_LOG(debug) << "Refreshing cursor image after FB changed"sv;
1473 cursor_dirty = true;
1474 } else if (*prop_src_x != captured_cursor.prop_src_x ||
1475 *prop_src_y != captured_cursor.prop_src_y ||
1476 *prop_src_w != captured_cursor.prop_src_w ||
1477 *prop_src_h != captured_cursor.prop_src_h) {
1478 BOOST_LOG(debug) << "Refreshing cursor image after source dimensions changed"sv;
1479 cursor_dirty = true;
1480 }
1481
1482 // If the cursor is dirty, map it so we can download the new image
1483 if (cursor_dirty) {
1484 auto fb = card.fb(plane.get());
1485 if (!fb || !fb->handles[0]) {
1486 // This means the cursor is not currently visible
1487 captured_cursor.visible = false;
1488 return;
1489 }
1490
1491 // All known cursor planes in the wild are ARGB8888
1492 if (fb->pixel_format != DRM_FORMAT_ARGB8888) {
1493 BOOST_LOG(error) << "Unsupported non-ARGB8888 cursor format: "sv << fb->pixel_format;
1494 captured_cursor.visible = false;
1495 cursor_plane_id = -1;
1496 return;
1497 }
1498
1499 // All known cursor planes in the wild require linear buffers
1500 if (fb->modifier != DRM_FORMAT_MOD_LINEAR && fb->modifier != DRM_FORMAT_MOD_INVALID) {
1501 BOOST_LOG(error) << "Unsupported non-linear cursor modifier: "sv << fb->modifier;
1502 captured_cursor.visible = false;
1503 cursor_plane_id = -1;
1504 return;
1505 }
1506
1507 // The SRC_* properties are in Q16.16 fixed point, so convert to integers
1508 auto src_x = *prop_src_x >> 16;
1509 auto src_y = *prop_src_y >> 16;
1510 auto src_w = *prop_src_w >> 16;
1511 auto src_h = *prop_src_h >> 16;
1512
1513 // Check for a legal source rectangle
1514 if (src_x + src_w > fb->width || src_y + src_h > fb->height) {
1515 BOOST_LOG(error) << "Illegal source size: ["sv << src_x + src_w << ',' << src_y + src_h << "] > ["sv << fb->width << ',' << fb->height << ']';
1516 captured_cursor.visible = false;
1517 return;
1518 }
1519
1520 file_t plane_fd = card.handleFD(fb->handles[0]);
1521 if (plane_fd.el < 0) {
1522 captured_cursor.visible = false;
1523 return;
1524 }
1525
1526 // We will map the entire region, but only copy what the source rectangle specifies
1527 size_t mapped_size = ((size_t) fb->pitches[0]) * fb->height;
1528 void *mapped_data = mmap(nullptr, mapped_size, PROT_READ, MAP_SHARED, plane_fd.el, fb->offsets[0]);
1529
1530 // If we got ENOSYS back, let's try to map it as a dumb buffer instead (required for Nvidia GPUs)
1531 if (mapped_data == MAP_FAILED && errno == ENOSYS) {
1532 drm_mode_map_dumb map = {};
1533 map.handle = fb->handles[0];
1534 if (drmIoctl(card.fd.el, DRM_IOCTL_MODE_MAP_DUMB, &map) < 0) {
1535 BOOST_LOG(error) << "Failed to map cursor FB as dumb buffer: "sv << strerror(errno);
1536 captured_cursor.visible = false;
1537 return;
1538 }
1539
1540 mapped_data = mmap(nullptr, mapped_size, PROT_READ, MAP_SHARED, card.fd.el, map.offset);
1541 }
1542
1543 if (mapped_data == MAP_FAILED) {
1544 BOOST_LOG(error) << "Failed to mmap cursor FB: "sv << strerror(errno);
1545 captured_cursor.visible = false;
1546 return;
1547 }
1548
1549 captured_cursor.pixels.resize(src_w * src_h * 4);
1550
1551 // Prepare to read the dmabuf from the CPU
1552 struct dma_buf_sync sync;
1553 sync.flags = DMA_BUF_SYNC_START | DMA_BUF_SYNC_READ;
1554 drmIoctl(plane_fd.el, DMA_BUF_IOCTL_SYNC, &sync);
1555
1556 // If the image is tightly packed, copy it in one shot
1557 if (fb->pitches[0] == src_w * 4 && src_x == 0) {
1558 memcpy(captured_cursor.pixels.data(), &((std::uint8_t *) mapped_data)[src_y * fb->pitches[0]], src_h * fb->pitches[0]);
1559 } else {
1560 // Copy row by row to deal with mismatched pitch or an X offset
1561 auto pixel_dst = captured_cursor.pixels.data();
1562 for (int y = 0; y < src_h; y++) {
1563 memcpy(&pixel_dst[y * (src_w * 4)], &((std::uint8_t *) mapped_data)[(y + src_y) * fb->pitches[0] + (src_x * 4)], src_w * 4);
1564 }
1565 }
1566
1567 // End the CPU read and unmap the dmabuf
1568 sync.flags = DMA_BUF_SYNC_END | DMA_BUF_SYNC_READ;
1569 drmIoctl(plane_fd.el, DMA_BUF_IOCTL_SYNC, &sync);
1570
1571 munmap(mapped_data, mapped_size);
1572
1573 captured_cursor.visible = true;
1574 captured_cursor.src_w = src_w;
1575 captured_cursor.src_h = src_h;
1576 captured_cursor.prop_src_x = *prop_src_x;
1577 captured_cursor.prop_src_y = *prop_src_y;
1578 captured_cursor.prop_src_w = *prop_src_w;
1579 captured_cursor.prop_src_h = *prop_src_h;
1580 captured_cursor.fb_id = plane->fb_id;
1581 ++captured_cursor.serial;
1582 }
1583 }
1584
1585 inline capture_e refresh(file_t *file, egl::surface_descriptor_t *sd, std::optional<std::chrono::steady_clock::time_point> &frame_timestamp) {
1586 // Check for a change in HDR metadata
1587 if (connector_id) {
1588 auto connector_props = card.connector_props(*connector_id);
1589 if (hdr_metadata_blob_id != card.prop_value_by_name(connector_props, "HDR_OUTPUT_METADATA"sv)) {
1590 BOOST_LOG(info) << "Reinitializing capture after HDR metadata change"sv;
1591 return capture_e::reinit;
1592 }
1593 }
1594
1595 plane_t plane = drmModeGetPlane(card.fd.el, plane_id);
1596 frame_timestamp = std::chrono::steady_clock::now();
1597
1598 if (!plane) {
1599 // The plane we captured from is gone, which a reconfigured display can
1600 // do at any moment. Every read below goes through this pointer, so
1601 // there is nothing to salvage here - re-enumerate instead of dying on
1602 // the first dereference.
1603 BOOST_LOG(warning) << "Couldn't get drm plane ["sv << plane_id << "]: "sv << strerror(errno);
1604 return capture_e::reinit;
1605 }
1606
1607 auto fb = card.fb(plane.get());
1608 if (!fb) {
1609 // The plane shows nothing while its output is off (framebuffer 0)
1610 // or being reconfigured. Capture retries every frame until it
1611 // returns, so say so once rather than on every frame.
1612 if (!plane_lost) {
1613 BOOST_LOG(warning) << "Couldn't get drm fb for plane ["sv << plane->fb_id << "]: "sv << strerror(errno)
1614 << "; waiting for the display to show a picture again"sv;
1615 plane_lost = true;
1616 }
1617 return capture_e::timeout;
1618 }
1619 if (plane_lost) {
1620 BOOST_LOG(info) << "The display shows a picture again; capture resumed"sv;
1621 plane_lost = false;
1622 }
1623
1624 if (!fb->handles[0]) {
1625 BOOST_LOG(error) << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Probably not permitted"sv;
1626 return capture_e::error;
1627 }
1628
1629 for (int y = 0; y < 4; ++y) {
1630 if (!fb->handles[y]) {
1631 // setting sd->fds[y] to a negative value indicates that sd->offsets[y] and sd->pitches[y]
1632 // are uninitialized and contain invalid values.
1633 sd->fds[y] = -1;
1634 // It's not clear whether there could still be valid handles left.
1635 // So, continue anyway.
1636 // TODO: Is this redundant?
1637 continue;
1638 }
1639
1640 file[y] = card.handleFD(fb->handles[y]);
1641 if (file[y].el < 0) {
1642 BOOST_LOG(error) << "Couldn't get primary file descriptor for Framebuffer ["sv << fb->fb_id << "]: "sv << strerror(errno);
1643 return capture_e::error;
1644 }
1645
1646 sd->fds[y] = file[y].el;
1647 sd->offsets[y] = fb->offsets[y];
1648 sd->pitches[y] = fb->pitches[y];
1649 }
1650
1651 sd->width = fb->width;
1652 sd->height = fb->height;
1653 sd->modifier = fb->modifier;
1654 sd->fourcc = fb->pixel_format;
1655
1656 if (
1657 fb->width != img_width ||
1658 fb->height != img_height
1659 ) {
1660 return capture_e::reinit;
1661 }
1662
1663 update_cursor();
1664
1665 return capture_e::ok;
1666 }
1667
1668 mem_type_e mem_type;
1669
1670 std::chrono::nanoseconds delay;
1671
1672 int img_width, img_height;
1673 int img_offset_x, img_offset_y;
1674
1675 int plane_id;
1676 int crtc_id;
1677 int crtc_index;
1678 bool plane_lost = false;
1679
1680 std::optional<uint32_t> connector_id;
1681 std::optional<uint64_t> hdr_metadata_blob_id;
1682
1683 int cursor_plane_id;
1684 cursor_t captured_cursor {};
1685
1686 card_t card;
1687 };
1688
1689 class display_ram_t: public display_t {
1690 public:
1691 display_ram_t(mem_type_e mem_type):
1692 display_t(mem_type) {
1693 }
1694
1695 int init(const std::string &display_name, const ::video::config_t &config) {
1696 if (!gbm::create_device) {
1697 BOOST_LOG(warning) << "libgbm not initialized"sv;
1698 return -1;
1699 }
1700
1701 if (display_t::init(display_name, config)) {
1702 return -1;
1703 }
1704
1705 gbm.reset(gbm::create_device(card.fd.el));
1706 if (!gbm) {
1707 BOOST_LOG(error) << "Couldn't create GBM device: ["sv << util::hex(eglGetError()).to_string_view() << ']';
1708 return -1;
1709 }
1710
1711 display = egl::make_display(gbm.get());
1712 if (!display) {
1713 return -1;
1714 }
1715
1716 auto ctx_opt = egl::make_ctx(display.get());
1717 if (!ctx_opt) {
1718 return -1;
1719 }
1720
1721 ctx = std::move(*ctx_opt);
1722
1723 return 0;
1724 }
1725
1726 capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor) override {
1727 auto next_frame = std::chrono::steady_clock::now();
1728
1729 sleep_overshoot_logger.reset();
1730
1731 while (true) {
1732 auto now = std::chrono::steady_clock::now();
1733
1734 if (next_frame > now) {
1735 std::this_thread::sleep_for(next_frame - now);
1736 sleep_overshoot_logger.first_point(next_frame);
1737 sleep_overshoot_logger.second_point_now_and_log();
1738 }
1739
1740 next_frame += delay;
1741 if (next_frame < now) { // some major slowdown happened; we couldn't keep up
1742 next_frame = now + delay;
1743 }
1744
1745 std::shared_ptr<platf::img_t> img_out;
1746 auto status = snapshot(pull_free_image_cb, img_out, 1000ms, *cursor);
1747 switch (status) {
1751 return status;
1753 if (!push_captured_image_cb(std::move(img_out), false)) {
1754 return platf::capture_e::ok;
1755 }
1756 break;
1758 if (!push_captured_image_cb(std::move(img_out), true)) {
1759 return platf::capture_e::ok;
1760 }
1761 break;
1762 default:
1763 BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']';
1764 return status;
1765 }
1766 }
1767
1768 return capture_e::ok;
1769 }
1770
1771#ifdef HAVE_PYROWAVE
1772 std::unique_ptr<avcodec_encode_device_t> make_pyrowave_encode_device() override {
1773 return pyrowave::make_ram_encode_device(width, height);
1774 }
1775#endif
1776
1777 std::unique_ptr<avcodec_encode_device_t> make_avcodec_encode_device(pix_fmt_e pix_fmt) override {
1778#ifdef HERMES_BUILD_VAAPI
1779 if (mem_type == mem_type_e::vaapi) {
1780 return va::make_avcodec_encode_device(width, height, false);
1781 }
1782#endif
1783
1784#ifdef HERMES_BUILD_CUDA
1785 if (mem_type == mem_type_e::cuda) {
1786 return cuda::make_avcodec_encode_device(width, height, false);
1787 }
1788#endif
1789
1790 return std::make_unique<avcodec_encode_device_t>();
1791 }
1792
1793 void blend_cursor(img_t &img) {
1794 // TODO: Cursor scaling is not supported in this codepath.
1795 // We always draw the cursor at the source size.
1796 auto pixels = (int *) img.data;
1797
1798 int32_t screen_height = img.height;
1799 int32_t screen_width = img.width;
1800
1801 // This is the position in the target that we will start drawing the cursor
1802 auto cursor_x = std::max<int32_t>(0, captured_cursor.x - img_offset_x);
1803 auto cursor_y = std::max<int32_t>(0, captured_cursor.y - img_offset_y);
1804
1805 // If the cursor is partially off screen, the coordinates may be negative
1806 // which means we will draw the top-right visible portion of the cursor only.
1807 auto cursor_delta_x = cursor_x - std::max<int32_t>(-captured_cursor.src_w, captured_cursor.x - img_offset_x);
1808 auto cursor_delta_y = cursor_y - std::max<int32_t>(-captured_cursor.src_h, captured_cursor.y - img_offset_y);
1809
1810 auto delta_height = std::min<uint32_t>(captured_cursor.src_h, std::max<int32_t>(0, screen_height - cursor_y)) - cursor_delta_y;
1811 auto delta_width = std::min<uint32_t>(captured_cursor.src_w, std::max<int32_t>(0, screen_width - cursor_x)) - cursor_delta_x;
1812 for (auto y = 0; y < delta_height; ++y) {
1813 // Offset into the cursor image to skip drawing the parts of the cursor image that are off screen
1814 //
1815 // NB: We must access the elements via the data() function because cursor_end may point to the
1816 // the first element beyond the valid range of the vector. Using vector's [] operator in that
1817 // manner is undefined behavior (and triggers errors when using debug libc++), while doing the
1818 // same with an array is fine.
1819 auto cursor_begin = (uint32_t *) &captured_cursor.pixels.data()[((y + cursor_delta_y) * captured_cursor.src_w + cursor_delta_x) * 4];
1820 auto cursor_end = (uint32_t *) &captured_cursor.pixels.data()[((y + cursor_delta_y) * captured_cursor.src_w + delta_width + cursor_delta_x) * 4];
1821
1822 auto pixels_begin = &pixels[(y + cursor_y) * (img.row_pitch / img.pixel_pitch) + cursor_x];
1823
1824 std::for_each(cursor_begin, cursor_end, [&](uint32_t cursor_pixel) {
1825 auto colors_in = (uint8_t *) pixels_begin;
1826
1827 auto alpha = (*(uint *) &cursor_pixel) >> 24u;
1828 if (alpha == 255) {
1829 *pixels_begin = cursor_pixel;
1830 } else {
1831 auto colors_out = (uint8_t *) &cursor_pixel;
1832 colors_in[0] = colors_out[0] + (colors_in[0] * (255 - alpha) + 255 / 2) / 255;
1833 colors_in[1] = colors_out[1] + (colors_in[1] * (255 - alpha) + 255 / 2) / 255;
1834 colors_in[2] = colors_out[2] + (colors_in[2] * (255 - alpha) + 255 / 2) / 255;
1835 }
1836 ++pixels_begin;
1837 });
1838 }
1839 }
1840
1841 capture_e snapshot(const pull_free_image_cb_t &pull_free_image_cb, std::shared_ptr<platf::img_t> &img_out, std::chrono::milliseconds timeout, bool cursor) {
1842 file_t fb_fd[4];
1843
1844 egl::surface_descriptor_t sd;
1845
1846 std::optional<std::chrono::steady_clock::time_point> frame_timestamp;
1847 auto status = refresh(fb_fd, &sd, frame_timestamp);
1848 if (status != capture_e::ok) {
1849 return status;
1850 }
1851
1852 auto rgb_opt = egl::import_source(display.get(), sd);
1853
1854 if (!rgb_opt) {
1855 return capture_e::error;
1856 }
1857
1858 auto &rgb = *rgb_opt;
1859
1860 gl::ctx.BindTexture(GL_TEXTURE_2D, rgb->tex[0]);
1861
1862 // Don't remove these lines, see https://github.com/LizardByte/Sunshine/issues/453
1863 int w, h;
1864 gl::ctx.GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w);
1865 gl::ctx.GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h);
1866 BOOST_LOG(debug) << "width and height: w "sv << w << " h "sv << h;
1867
1868 if (!pull_free_image_cb(img_out)) {
1869 return platf::capture_e::interrupted;
1870 }
1871
1872 gl::ctx.GetTextureSubImage(rgb->tex[0], 0, img_offset_x, img_offset_y, 0, width, height, 1, GL_BGRA, GL_UNSIGNED_BYTE, img_out->height * img_out->row_pitch, img_out->data);
1873
1874 img_out->frame_timestamp = frame_timestamp;
1875
1876 if (cursor && captured_cursor.visible) {
1877 blend_cursor(*img_out);
1878 }
1879
1880 return capture_e::ok;
1881 }
1882
1883 std::shared_ptr<img_t> alloc_img() override {
1884 auto img = std::make_shared<kms_img_t>();
1885 img->width = width;
1886 img->height = height;
1887 img->pixel_pitch = 4;
1888 img->row_pitch = img->pixel_pitch * width;
1889 img->data = new std::uint8_t[height * img->row_pitch];
1890
1891 return img;
1892 }
1893
1894 int dummy_img(platf::img_t *img) override {
1895 return 0;
1896 }
1897
1898 gbm::gbm_t gbm;
1899 egl::display_t display;
1900 egl::ctx_t ctx;
1901 };
1902
1903 // EVDI exposes a virtual DRM card but no render node. Feeding that card to
1904 // GBM/EGL can crash Mesa, so capture from libevdi's CPU BGRA buffer and
1905 // use Apollo's existing RAM-to-encoder upload path instead.
1906 class display_evdi_t: public platf::display_t {
1907 public:
1908 explicit display_evdi_t(mem_type_e mem_type): mem_type {mem_type} {}
1909
1910 int init(const std::string &display_name, const ::video::config_t &config) {
1911 buffer = VDISPLAY::getEvdiBuffer(display_name);
1912 if (!buffer) {
1913 BOOST_LOG(error) << "No EVDI pixel buffer is available for " << display_name;
1914 return -1;
1915 }
1916 delay = std::chrono::nanoseconds {1s} / config.framerate;
1917 width = static_cast<int>(buffer->width());
1918 height = static_cast<int>(buffer->height());
1919 offset_x = 0;
1920 offset_y = 0;
1921 env_width = width;
1922 env_height = height;
1923 return 0;
1924 }
1925
1926 capture_e capture(const push_captured_image_cb_t &push_captured_image_cb,
1927 const pull_free_image_cb_t &pull_free_image_cb,
1928 bool *) override {
1929 auto next_frame = std::chrono::steady_clock::now();
1930 auto last_frame = buffer->frame_number();
1931 // The first frame is always copied, so a new session starts with a picture.
1932 bool copied_any = false;
1933 std::uint64_t copied_frame = 0;
1934
1935 while (true) {
1936 const auto now = std::chrono::steady_clock::now();
1937 if (next_frame > now) {
1938 const auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(next_frame - now);
1939 last_frame = buffer->wait_for_update(last_frame, std::max(remaining, std::chrono::milliseconds {1}));
1940 }
1941 next_frame += delay;
1942 if (next_frame < now) {
1943 next_frame = now + delay;
1944 }
1945
1946 std::shared_ptr<platf::img_t> img_out;
1947 if (!pull_free_image_cb(img_out)) {
1949 }
1950 // Nothing was drawn since the last copy: report no new frame, like
1951 // the other backends do on a timeout. The encoder then repeats the
1952 // previous frame at its minimum rate instead of encoding an
1953 // identical frame at the full frame rate.
1954 if (copied_any && buffer->frame_number() == copied_frame) {
1955 if (!push_captured_image_cb(std::move(img_out), false)) {
1956 return capture_e::ok;
1957 }
1958 continue;
1959 }
1960 const auto t0 = std::chrono::steady_clock::now();
1961 copied_frame = buffer->copy_to(img_out->data, img_out->row_pitch);
1962 copied_any = true;
1963 const auto t1 = std::chrono::steady_clock::now();
1964 accumulate_capture_metric("evdi", std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count());
1965 img_out->frame_timestamp = std::chrono::steady_clock::now();
1966 if (!push_captured_image_cb(std::move(img_out), true)) {
1967 return capture_e::ok;
1968 }
1969 }
1970 }
1971
1972#ifdef HAVE_PYROWAVE
1973 std::unique_ptr<avcodec_encode_device_t> make_pyrowave_encode_device() override {
1974 return pyrowave::make_ram_encode_device(width, height);
1975 }
1976#endif
1977
1978 std::unique_ptr<avcodec_encode_device_t> make_avcodec_encode_device(pix_fmt_e) override {
1979#ifdef HERMES_BUILD_VAAPI
1980 if (mem_type == mem_type_e::vaapi) {
1981 return va::make_avcodec_encode_device(width, height, false);
1982 }
1983#endif
1984#ifdef HERMES_BUILD_CUDA
1985 if (mem_type == mem_type_e::cuda) {
1986 return cuda::make_avcodec_encode_device(width, height, false);
1987 }
1988#endif
1989 return std::make_unique<avcodec_encode_device_t>();
1990 }
1991
1992 std::shared_ptr<img_t> alloc_img() override {
1993 auto img = std::make_shared<kms_img_t>();
1994 img->width = width;
1995 img->height = height;
1996 img->pixel_pitch = 4;
1997 img->row_pitch = img->pixel_pitch * width;
1998 img->data = new std::uint8_t[height * img->row_pitch];
1999 return img;
2000 }
2001
2002 int dummy_img(platf::img_t *) override { return 0; }
2003
2004 private:
2005 mem_type_e mem_type;
2006 std::chrono::nanoseconds delay;
2007 std::shared_ptr<VDISPLAY::EvdiBuffer> buffer;
2008 };
2009
2010 class display_vram_t: public display_t {
2011 public:
2012 display_vram_t(mem_type_e mem_type):
2013 display_t(mem_type) {
2014 }
2015
2016#ifdef HAVE_PYROWAVE
2017 std::unique_ptr<avcodec_encode_device_t> make_pyrowave_encode_device() override {
2018 return pyrowave::make_gpu_encode_device(width, height, dup(card.render_fd.el), img_offset_x, img_offset_y);
2019 }
2020#endif
2021
2022 std::unique_ptr<avcodec_encode_device_t> make_avcodec_encode_device(pix_fmt_e pix_fmt) override {
2023#ifdef HERMES_BUILD_VAAPI
2024 if (mem_type == mem_type_e::vaapi) {
2025 return va::make_avcodec_encode_device(width, height, dup(card.render_fd.el), img_offset_x, img_offset_y, true);
2026 }
2027#endif
2028
2029#ifdef HERMES_BUILD_CUDA
2030 if (mem_type == mem_type_e::cuda) {
2031 return cuda::make_avcodec_gl_encode_device(width, height, img_offset_x, img_offset_y);
2032 }
2033#endif
2034
2035 BOOST_LOG(error) << "Unsupported pixel format for egl::display_vram_t: "sv << platf::from_pix_fmt(pix_fmt);
2036 return nullptr;
2037 }
2038
2039 std::shared_ptr<img_t> alloc_img() override {
2040 auto img = std::make_shared<egl::img_descriptor_t>();
2041
2042 img->width = width;
2043 img->height = height;
2044 img->serial = std::numeric_limits<decltype(img->serial)>::max();
2045 img->data = nullptr;
2046 img->pixel_pitch = 4;
2047
2048 img->sequence = 0;
2049 std::fill_n(img->sd.fds, 4, -1);
2050
2051 return img;
2052 }
2053
2054 int dummy_img(platf::img_t *img) override {
2055 // Empty images are recognized as dummies by the zero sequence number
2056 return 0;
2057 }
2058
2059 capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor) {
2060 auto next_frame = std::chrono::steady_clock::now();
2061
2062 sleep_overshoot_logger.reset();
2063
2064 while (true) {
2065 auto now = std::chrono::steady_clock::now();
2066
2067 if (next_frame > now) {
2068 std::this_thread::sleep_for(next_frame - now);
2069 sleep_overshoot_logger.first_point(next_frame);
2070 sleep_overshoot_logger.second_point_now_and_log();
2071 }
2072
2073 next_frame += delay;
2074 if (next_frame < now) { // some major slowdown happened; we couldn't keep up
2075 next_frame = now + delay;
2076 }
2077
2078 std::shared_ptr<platf::img_t> img_out;
2079 auto status = snapshot(pull_free_image_cb, img_out, 1000ms, *cursor);
2080 switch (status) {
2084 return status;
2086 if (!push_captured_image_cb(std::move(img_out), false)) {
2087 return platf::capture_e::ok;
2088 }
2089 break;
2091 if (!push_captured_image_cb(std::move(img_out), true)) {
2092 return platf::capture_e::ok;
2093 }
2094 break;
2095 default:
2096 BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']';
2097 return status;
2098 }
2099 }
2100
2101 return capture_e::ok;
2102 }
2103
2104 capture_e snapshot(const pull_free_image_cb_t &pull_free_image_cb, std::shared_ptr<platf::img_t> &img_out, std::chrono::milliseconds /* timeout */, bool cursor) {
2105 file_t fb_fd[4];
2106
2107 if (!pull_free_image_cb(img_out)) {
2109 }
2110 auto img = (egl::img_descriptor_t *) img_out.get();
2111 img->reset();
2112
2113 auto status = refresh(fb_fd, &img->sd, img->frame_timestamp);
2114 if (status != capture_e::ok) {
2115 return status;
2116 }
2117
2118 img->sequence = ++sequence;
2119
2120 if (cursor && captured_cursor.visible) {
2121 // Copy new cursor pixel data if it's been updated
2122 if (img->serial != captured_cursor.serial) {
2123 img->buffer = captured_cursor.pixels;
2124 img->serial = captured_cursor.serial;
2125 }
2126
2127 img->x = captured_cursor.x;
2128 img->y = captured_cursor.y;
2129 img->src_w = captured_cursor.src_w;
2130 img->src_h = captured_cursor.src_h;
2131 img->width = captured_cursor.dst_w;
2132 img->height = captured_cursor.dst_h;
2133 img->pixel_pitch = 4;
2134 img->row_pitch = img->pixel_pitch * img->width;
2135 img->data = img->buffer.data();
2136 } else {
2137 img->data = nullptr;
2138 }
2139
2140 for (auto x = 0; x < 4; ++x) {
2141 fb_fd[x].release();
2142 }
2143 return capture_e::ok;
2144 }
2145
2146 int init(const std::string &display_name, const ::video::config_t &config) {
2147 if (display_t::init(display_name, config)) {
2148 return -1;
2149 }
2150
2151#ifdef HERMES_BUILD_VAAPI
2152 if (mem_type == mem_type_e::vaapi && !va::validate(card.render_fd.el)) {
2153 BOOST_LOG(warning) << "Monitor "sv << display_name << " doesn't support hardware encoding. Reverting back to GPU -> RAM -> GPU"sv;
2154 return -1;
2155 }
2156#endif
2157
2158#ifndef HERMES_BUILD_CUDA
2159 if (mem_type == mem_type_e::cuda) {
2160 BOOST_LOG(warning) << "Attempting to use NVENC without CUDA support. Reverting back to GPU -> RAM -> GPU"sv;
2161 return -1;
2162 }
2163#endif
2164
2165 return 0;
2166 }
2167
2168 std::uint64_t sequence {};
2169 };
2170
2183 inline bool hermes_layout_changed(std::uint64_t &recorded) {
2184 const auto current = VDISPLAY::displayLayoutGeneration();
2185 if (current == recorded) {
2186 return false;
2187 }
2188 recorded = current;
2189 BOOST_LOG(info) << "Hermes-KMS capture: the desktop layout changed; reinitialising to re-resolve "
2190 "the input geometry."sv;
2191 return true;
2192 }
2193
2208 const std::string &display_name,
2209 int width,
2210 int height,
2211 int &offset_x,
2212 int &offset_y,
2213 int &env_width,
2214 int &env_height
2215 ) {
2216 offset_x = 0;
2217 offset_y = 0;
2218 env_width = width;
2219 env_height = height;
2220
2221 // A session-device output belongs to an isolated compositor that drives
2222 // only this display. Shared-host outputs still need host desktop geometry,
2223 // even when isolated-session capability is enabled for other clients.
2224 if (!VDISPLAY::getHermesKmsSeatName(display_name).empty()) {
2225 return;
2226 }
2227
2228 int desktop_x = 0;
2229 int desktop_y = 0;
2230 int desktop_width = 0;
2231 int desktop_height = 0;
2233 display_name,
2234 desktop_x,
2235 desktop_y,
2236 desktop_width,
2237 desktop_height
2238 )) {
2239 BOOST_LOG(warning) << "Could not resolve compositor geometry for ["sv << display_name
2240 << "]; absolute input will use output-local coordinates, which are only "
2241 "correct while the virtual display is the whole desktop."sv;
2242 return;
2243 }
2244
2245 // Deliberately loose: the offset has to land inside the envelope, but the
2246 // display is not required to fit it exactly, because a scaled desktop
2247 // converts through a rounding step.
2248 if (desktop_x < 0 || desktop_y < 0 || desktop_width <= 0 || desktop_height <= 0 ||
2249 desktop_x >= desktop_width || desktop_y >= desktop_height) {
2250 BOOST_LOG(warning) << "Compositor reported an unusable desktop geometry for ["sv << display_name
2251 << "]: "sv << width << 'x' << height << " at "sv << desktop_x << ',' << desktop_y
2252 << " in "sv << desktop_width << 'x' << desktop_height
2253 << "; keeping output-local coordinates."sv;
2254 return;
2255 }
2256
2257 offset_x = desktop_x;
2258 offset_y = desktop_y;
2259 env_width = desktop_width;
2260 env_height = desktop_height;
2261 BOOST_LOG(info) << "Hermes-KMS input geometry for ["sv << display_name << "]: "
2262 << offset_x << ',' << offset_y << " in "
2263 << env_width << 'x' << env_height;
2264 }
2265
2266 bool wait_hermes_capture_size(int fd, int &width, int &height) {
2267 // Output configuration is asynchronous. Both encoders need the actual
2268 // scanout and its first framebuffer, including after a modeset/reinit.
2269 constexpr uint32_t timeout_ms = 1000;
2270 if (VDISPLAY::hermesKmsCaptureSize(fd, width, height, timeout_ms)) {
2271 return true;
2272 }
2273 const int capture_error = errno;
2274 if (capture_error == ETIMEDOUT) {
2275 BOOST_LOG(error) << "Hermes-KMS capture: timed out after "sv << timeout_ms
2276 << "ms waiting for active scanout and its framebuffer."sv;
2277 } else {
2278 BOOST_LOG(error) << "Hermes-KMS capture: GET_STATUS failed: "sv
2279 << std::strerror(capture_error) << " (errno="sv << capture_error << ')';
2280 }
2281 return false;
2282 }
2283
2284 // Zero-copy capture of a Hermes-KMS virtual display.
2285 //
2286 // Unlike the KMS path, this never reads the scanout through drmModeGetFB +
2287 // drmPrimeHandleToFD (which needs DRM master and fails while the compositor
2288 // owns the card). Instead it opens the Hermes render node and pulls the
2289 // current framebuffer as DMA-BUFs via ACQUIRE_FRAME. The descriptor fields
2290 // map 1:1 onto egl::surface_descriptor_t, so the encoder path is unchanged.
2291 class display_hermes_vram_t: public display_vram_t {
2292 public:
2293 display_hermes_vram_t(mem_type_e mem_type):
2294 display_vram_t(mem_type) {
2295 }
2296
2297 bool is_hdr() override {
2298 return source_color.pq();
2299 }
2300
2301 bool get_hdr_metadata(SS_HDR_METADATA &metadata) override {
2302 return source_color.copy_hdr_metadata(metadata);
2303 }
2304
2305 VDISPLAY::hermes_kms::color_t source_color;
2306 bool probe_only {false};
2307 uint32_t source_fourcc {};
2308
2309 ~display_hermes_vram_t() override {
2310 if (hermes_fd >= 0) {
2311 ::close(hermes_fd);
2312 hermes_fd = -1;
2313 }
2314 }
2315
2316 int init(const std::string &display_name, const ::video::config_t &config) {
2317 probe_only = config.encoder_probe;
2318 BOOST_LOG(info) << "Hermes-KMS zero-copy capture path selected for ["sv << display_name << ']';
2319
2320 hermes_fd = VDISPLAY::hermesKmsOpenCapture(display_name);
2321 if (hermes_fd < 0) {
2322 return -1;
2323 }
2324
2325 int w = 0;
2326 int h = 0;
2327 if (!wait_hermes_capture_size(hermes_fd, w, h)) {
2328 return -1;
2329 }
2330
2331 if (!VDISPLAY::hermesKmsCaptureColor(hermes_fd, source_color, source_fourcc)) {
2332 BOOST_LOG(error) << "Hermes-KMS: cannot acquire initial colour state: " << strerror(errno);
2333 return -1;
2334 }
2335 if (source_color.pq() && !config.dynamicRange && !config.encoder_probe) {
2336 BOOST_LOG(error) << "Hermes-KMS output is HDR but the client requested SDR. Disable HDR on this KDE output or enable HDR in the client.";
2337 return -1;
2338 }
2339 if (source_color.known() && source_color.colorspace == VDISPLAY::hermes_kms::colorspace_bt2020_rgb && !source_color.pq()) {
2340 BOOST_LOG(error) << "Hermes-KMS: BT.2020 SDR capture requires a matching SDR colour conversion path.";
2341 return -1;
2342 }
2343
2344 width = img_width = w;
2345 height = img_height = h;
2346 img_offset_x = 0;
2347 img_offset_y = 0;
2348 resolve_hermes_input_geometry(display_name, w, h, offset_x, offset_y, env_width, env_height);
2350
2351 // The Hermes render node only exports DMA-BUFs; it is not a render GPU,
2352 // so VAAPI must run on a real GPU (e.g. amdgpu/renderD128). Honour an
2353 // explicitly configured adapter; only auto-scan when none was set.
2354 encode_render_fd.el = open_encode_render_node(mem_type == mem_type_e::cuda);
2355 if (encode_render_fd.el < 0) {
2356 BOOST_LOG(error) << "Hermes-KMS capture: no render GPU found for encoding."sv;
2357 return -1;
2358 }
2359
2360#ifdef HERMES_BUILD_VAAPI
2361 if (mem_type == mem_type_e::vaapi && !va::validate(encode_render_fd.el)) {
2362 BOOST_LOG(warning) << "Encoding GPU doesn't support VAAPI."sv;
2363 return -1;
2364 }
2365#endif
2366
2367#ifndef HERMES_BUILD_CUDA
2368 if (mem_type == mem_type_e::cuda) {
2369 BOOST_LOG(warning) << "Hermes-KMS NVENC path requested but Hermes was built without CUDA support."sv;
2370 return -1;
2371 }
2372#endif
2373
2374 BOOST_LOG(info) << "Hermes-KMS zero-copy capture ready: "sv << w << 'x' << h;
2375 return 0;
2376 }
2377
2378#ifdef HAVE_PYROWAVE
2379 std::unique_ptr<avcodec_encode_device_t> make_pyrowave_encode_device() override {
2380 // The same real GPU the VAAPI path encodes on; the Hermes render node
2381 // only exports.
2382 return pyrowave::make_gpu_encode_device(width, height, dup(encode_render_fd.el), img_offset_x, img_offset_y);
2383 }
2384#endif
2385
2386 std::unique_ptr<avcodec_encode_device_t> make_avcodec_encode_device(pix_fmt_e pix_fmt) override {
2387#ifdef HERMES_BUILD_VAAPI
2388 if (mem_type == mem_type_e::vaapi) {
2389 // Encode on the real GPU, importing the Hermes DMA-BUFs (vram=true).
2390 return va::make_avcodec_encode_device(width, height, dup(encode_render_fd.el), img_offset_x, img_offset_y, true);
2391 }
2392#endif
2393#ifdef HERMES_BUILD_CUDA
2394 if (mem_type == mem_type_e::cuda) {
2395 // Same descriptor flow as display_vram_t: the GL/CUDA device imports
2396 // the Hermes DMA-BUFs through EGL on the NVIDIA GPU and encodes with
2397 // NVENC. The Hermes render node stays capture-only.
2398 //
2399 // NOTE: NVENC sessions for Hermes-KMS displays currently capture
2400 // through a CPU copy, because NVIDIA's EGL import of these
2401 // system-memory DMA-BUFs reads wrong pages past the first ones.
2402 // This branch is the intended zero-copy path once that import is
2403 // reliable and is kept buildable on purpose.
2404 return cuda::make_avcodec_gl_encode_device(width, height, img_offset_x, img_offset_y);
2405 }
2406#endif
2407 BOOST_LOG(error) << "Hermes-KMS capture supports VAAPI and NVENC(CUDA) encoding only."sv;
2408 return nullptr;
2409 }
2410
2411 capture_e snapshot(const pull_free_image_cb_t &pull_free_image_cb, std::shared_ptr<platf::img_t> &img_out, std::chrono::milliseconds timeout, bool cursor_requested) {
2412 if (!pull_free_image_cb(img_out)) {
2414 }
2415 auto img = static_cast<egl::img_descriptor_t *>(img_out.get());
2416
2419 }
2420
2422 const auto timeout_ms = hermes_timeout_ms(timeout);
2423 const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds {timeout_ms};
2424 const bool cursor_mode_changed =
2425 !last_cursor_requested || *last_cursor_requested != cursor_requested;
2426 bool cursor_ready = false;
2427 errno = 0;
2428 if (cursor_requested && !cursor_mode_changed) {
2431 hermes_fd,
2432 last_sequence,
2433 last_cursor_sequence,
2434 timeout_ms,
2435 update)) {
2436 return hermes_acquire_failure("zero-copy update wait", errno);
2437 }
2438 cursor_ready = update.cursor_ready;
2439 } else if (cursor_requested) {
2440 cursor_ready = true;
2441 }
2442 if (!VDISPLAY::hermesKmsAcquireFrame(
2443 hermes_fd,
2444 last_sequence,
2445 (cursor_requested || cursor_mode_changed) ? 0U : timeout_ms,
2446 frame, source_color.known())) {
2447 // A real timeout re-emits the previous image. Authorization changes,
2448 // device removal and malformed replies must instead rebuild capture.
2449 return hermes_acquire_failure("zero-copy", errno);
2450 }
2451 // Measure only the ACQUIRE_FRAME cost (DMA-BUF export), excluding the
2452 // blocking wait for a new frame, to compare fairly against EVDI's
2453 // copy_to() which likewise excludes its wait_for_update().
2454 accumulate_capture_metric("hermes-kms", frame.acquire_ns);
2455
2456 if (frame.width != img_width || frame.height != img_height ||
2457 frame.fourcc != source_fourcc || !(frame.color == source_color)) {
2458 // Rebuild before handing a differently encoded frame to the encoder.
2459 // The display's immutable colour snapshot also supplies its HDR SEI.
2460
2461 frame.close();
2463 }
2464
2465 bool valid_layout = frame.fourcc != 0;
2466 for (std::uint32_t i = 0; i < frame.plane_count; ++i) {
2467 valid_layout = valid_layout && frame.dma_buf_fd[i] >= 0 && frame.pitch[i] > 0;
2468 }
2469 if (!valid_layout) {
2470 BOOST_LOG(error) << "Hermes-KMS zero-copy capture: invalid DMA-BUF plane metadata."sv;
2471 frame.close();
2473 }
2474
2475 if (frame.sync_file_fd >= 0) {
2476 const auto fence_status = wait_hermes_frame_fence(frame.sync_file_fd, deadline);
2477 if (fence_status == hermes_fence_wait_e::timeout) {
2478 BOOST_LOG(warning) << "Hermes-KMS zero-copy capture: frame fence timed out."sv;
2479 frame.close();
2481 }
2482 if (fence_status == hermes_fence_wait_e::failed) {
2483 const int fence_errno = errno;
2484 BOOST_LOG(warning) << "Hermes-KMS zero-copy capture: dropping frame "sv
2485 << frame.sequence << " after producer fence failure: "sv
2486 << strerror(fence_errno);
2487 last_sequence = frame.sequence;
2488 frame.close();
2490 }
2491 if (fence_status == hermes_fence_wait_e::error) {
2492 const int fence_errno = errno;
2493 BOOST_LOG(error) << "Hermes-KMS zero-copy capture: invalid sync file: "sv
2494 << strerror(fence_errno);
2495 frame.close();
2497 }
2498 }
2499
2500 std::optional<cursor_t> pending_cursor;
2501 uint64_t pending_cursor_sequence = last_cursor_sequence;
2502 if (cursor_ready) {
2503 pending_cursor = captured_cursor;
2504 const auto cursor_status = refresh_hermes_cursor(
2505 hermes_fd,
2506 deadline,
2507 *pending_cursor,
2508 pending_cursor_sequence
2509 );
2510 if (cursor_status != capture_e::ok) {
2511 frame.close();
2512 return cursor_status;
2513 }
2514 }
2515
2516 // Keep the old descriptor alive through acquisition and fence waiting:
2517 // timeout callbacks reuse it. Only replace it once the new frame is
2518 // known to be complete and all metadata has been validated.
2519 img->reset();
2520 img->sd.width = frame.width;
2521 img->sd.height = frame.height;
2522 img->sd.fourcc = frame.fourcc;
2523 img->sd.modifier = frame.modifier;
2524 std::fill_n(img->sd.offsets, 4, 0);
2525 std::fill_n(img->sd.pitches, 4, 0);
2526 for (std::uint32_t i = 0; i < frame.plane_count; ++i) {
2527 img->sd.fds[i] = frame.dma_buf_fd[i];
2528 img->sd.offsets[i] = frame.offset[i];
2529 img->sd.pitches[i] = frame.pitch[i];
2530 frame.dma_buf_fd[i] = -1; // ownership transferred to img->sd
2531 }
2532 frame.close(); // closes the fence and any unexpected surplus fds
2533
2534 const bool primary_advanced = frame.sequence != last_sequence;
2535 last_sequence = frame.sequence;
2536 if (primary_advanced || !sequence) {
2537 ++sequence;
2538 }
2539 img->sequence = sequence;
2540 img->frame_timestamp = std::chrono::steady_clock::now();
2541 attach_hermes_cursor(
2542 *img,
2543 cursor_requested,
2544 pending_cursor ? *pending_cursor : captured_cursor
2545 );
2546 if (pending_cursor) {
2547 captured_cursor = std::move(*pending_cursor);
2548 last_cursor_sequence = pending_cursor_sequence;
2549 }
2550 last_cursor_requested = cursor_requested;
2551
2552 // The descriptor now owns the DMA-BUF fds; the image holds them until
2553 // reuse, leaving the cursor fields available for the cursor UAPI path.
2554 return platf::capture_e::ok;
2555 }
2556
2557 capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor) {
2558 if (probe_only) {
2559 return capture_e::error; // Probe objects may encode dummy images only.
2560 }
2561 while (true) {
2562 std::shared_ptr<platf::img_t> img_out;
2563 auto status = snapshot(pull_free_image_cb, img_out, 200ms, *cursor);
2564 switch (status) {
2568 return status;
2570 if (!push_captured_image_cb(std::move(img_out), false)) {
2571 return platf::capture_e::ok;
2572 }
2573 break;
2575 if (!push_captured_image_cb(std::move(img_out), true)) {
2576 return platf::capture_e::ok;
2577 }
2578 break;
2579 default:
2580 BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']';
2581 return status;
2582 }
2583 }
2584 return capture_e::ok;
2585 }
2586
2587 int hermes_fd {-1};
2589 std::uint64_t layout_generation {0};
2590 file_t encode_render_fd;
2591 uint64_t last_sequence {0};
2592 uint64_t last_cursor_sequence {0};
2593 std::optional<bool> last_cursor_requested;
2594 };
2595
2596 // Hermes-KMS capture through a CPU copy of the scanout DMA-BUF.
2597 //
2598 // The CPU view of the Hermes framebuffer is always pixel-correct, while
2599 // NVIDIA's EGL import of these system-memory DMA-BUFs has been observed to
2600 // read the wrong pages beyond the first ones (visible as diagonal
2601 // stripes). Until that import path is proven reliable, NVENC sessions map
2602 // the buffer, de-pad the rows on the CPU and let the regular RAM->CUDA
2603 // upload path feed the encoder. Costs one memcpy per frame (~1-2 ms at
2604 // 1440p-class sizes); correctness over the last microseconds.
2605 class display_hermes_ram_t: public display_t {
2606 public:
2607 display_hermes_ram_t(mem_type_e mem_type):
2608 display_t(mem_type) {
2609 }
2610
2611 bool is_hdr() override {
2612 return source_color.pq();
2613 }
2614
2615 bool get_hdr_metadata(SS_HDR_METADATA &metadata) override {
2616 return source_color.copy_hdr_metadata(metadata);
2617 }
2618
2619 VDISPLAY::hermes_kms::color_t source_color;
2620 bool probe_only {false};
2621 uint32_t source_fourcc {};
2622
2623 ~display_hermes_ram_t() override {
2624 if (hermes_fd >= 0) {
2625 ::close(hermes_fd);
2626 hermes_fd = -1;
2627 }
2628 }
2629
2630 int init(const std::string &display_name, const ::video::config_t &config) {
2631 probe_only = config.encoder_probe;
2632 BOOST_LOG(info) << "Hermes-KMS CPU-copy capture path selected for ["sv << display_name << ']';
2633
2634 hermes_fd = VDISPLAY::hermesKmsOpenCapture(display_name);
2635 if (hermes_fd < 0) {
2636 return -1;
2637 }
2638
2639 int w = 0;
2640 int h = 0;
2641 if (!wait_hermes_capture_size(hermes_fd, w, h)) {
2642 return -1;
2643 }
2644
2645 if (!VDISPLAY::hermesKmsCaptureColor(hermes_fd, source_color, source_fourcc)) {
2646 BOOST_LOG(error) << "Hermes-KMS: cannot acquire initial colour state: " << strerror(errno);
2647 return -1;
2648 }
2649 if (source_color.pq() && !config.dynamicRange && !config.encoder_probe) {
2650 BOOST_LOG(error) << "Hermes-KMS output is HDR but the client requested SDR. Disable HDR on this KDE output or enable HDR in the client.";
2651 return -1;
2652 }
2653 if (source_color.known() && source_color.colorspace == VDISPLAY::hermes_kms::colorspace_bt2020_rgb && !source_color.pq()) {
2654 BOOST_LOG(error) << "Hermes-KMS: BT.2020 SDR capture requires a matching SDR colour conversion path.";
2655 return -1;
2656 }
2657
2658 constexpr auto bytes_per_pixel = std::size_t {4};
2659 if (static_cast<std::size_t>(w) >
2660 static_cast<std::size_t>(std::numeric_limits<std::int32_t>::max()) / bytes_per_pixel ||
2661 static_cast<std::size_t>(h) >
2662 std::numeric_limits<std::size_t>::max() / (static_cast<std::size_t>(w) * bytes_per_pixel)) {
2663 BOOST_LOG(error) << "Hermes-KMS CPU capture: scanout geometry is too large: "sv
2664 << w << 'x' << h;
2665 return -1;
2666 }
2667
2668 if (!hermes_cpu_copy_format(source_fourcc)) {
2669 BOOST_LOG(error) << "Hermes-KMS CPU capture: scanout format "sv << hermes_fourcc_name(source_fourcc)
2670 << " is not supported; the compositor must scan out XRGB8888, ARGB8888 or packed 10-bit RGB."sv;
2671 return -1;
2672 }
2673
2674 width = img_width = w;
2675 height = img_height = h;
2676 img_offset_x = 0;
2677 img_offset_y = 0;
2678 resolve_hermes_input_geometry(display_name, w, h, offset_x, offset_y, env_width, env_height);
2680
2681 BOOST_LOG(info) << "Hermes-KMS CPU-copy capture ready: "sv << w << 'x' << h << ' '
2682 << hermes_fourcc_name(source_fourcc);
2683 return 0;
2684 }
2685
2686 std::shared_ptr<img_t> alloc_img() override {
2687 const auto row_pitch = static_cast<std::size_t>(width) * std::size_t {4};
2688 const auto size = static_cast<std::size_t>(height) * row_pitch;
2689 const auto describe = [&](img_t &img) {
2690 img.width = width;
2691 img.height = height;
2692 img.pixel_pitch = 4;
2693 img.row_pitch = static_cast<std::int32_t>(row_pitch);
2694 };
2695
2696#ifdef HERMES_BUILD_CUDA
2697 if (mem_type == mem_type_e::cuda) {
2698 if (auto *pinned = static_cast<std::uint8_t *>(cuda::alloc_host(size))) {
2699 std::memset(pinned, 0, size);
2700 auto img = std::make_shared<cuda_host_img_t>();
2701 describe(*img);
2702 img->data = pinned;
2703 return img;
2704 }
2705 if (!warned_pageable) {
2706 BOOST_LOG(warning) << "Hermes-KMS CPU capture: page-locked frames unavailable; uploads use pageable memory."sv;
2707 warned_pageable = true;
2708 }
2709 }
2710#endif
2711
2712 auto img = std::make_shared<kms_img_t>();
2713 describe(*img);
2714 img->data = new std::uint8_t[size] {};
2715
2716 return img;
2717 }
2718
2719 int dummy_img(platf::img_t *img) override {
2720 return 0;
2721 }
2722
2723#ifdef HAVE_PYROWAVE
2724 std::unique_ptr<avcodec_encode_device_t> make_pyrowave_encode_device() override {
2725 // The route NVIDIA hosts take: their EGL import of Hermes-KMS buffers
2726 // is unreliable, so the frame arrives here by CPU copy and is
2727 // uploaded to the real GPU for conversion.
2728 return pyrowave::make_ram_encode_device(width, height, file_t {open_encode_render_node()}, source_fourcc);
2729 }
2730#endif
2731
2732 std::unique_ptr<avcodec_encode_device_t> make_avcodec_encode_device(pix_fmt_e pix_fmt) override {
2733#ifdef HERMES_BUILD_CUDA
2734 if (mem_type == mem_type_e::cuda) {
2735 // One CUDA kernel decodes the frame's layout and writes NV12 or
2736 // P010 from pinned memory; no OpenGL context, and no GL-CUDA
2737 // interop to synchronize on every frame.
2738 return cuda::make_avcodec_encode_device(width, height, false, hermes_cuda_layout(source_fourcc));
2739 }
2740#endif
2741#ifdef HERMES_BUILD_VAAPI
2742 if (mem_type == mem_type_e::vaapi) {
2743 // Only reachable through HERMES_KMS_FORCE_CPU_COPY; the VAAPI upload
2744 // reads 8-bit BGRA.
2745 if (hermes_ten_bit_format(source_fourcc)) {
2746 BOOST_LOG(error) << "Hermes-KMS CPU capture: the VAAPI upload supports 8-bit scanout only, not "sv
2747 << hermes_fourcc_name(source_fourcc) << '.';
2748 return nullptr;
2749 }
2750 return va::make_avcodec_encode_device(width, height, false);
2751 }
2752#endif
2753 return std::make_unique<avcodec_encode_device_t>();
2754 }
2755
2756 capture_e snapshot(const pull_free_image_cb_t &pull_free_image_cb, std::shared_ptr<platf::img_t> &img_out, std::chrono::milliseconds timeout, bool cursor_requested) {
2757 // Pull the destination image before acquiring, like
2758 // display_hermes_vram_t does: the timeout path below re-emits
2759 // img_out, so it must already hold a valid image by then.
2760 if (!pull_free_image_cb(img_out)) {
2762 }
2763
2766 }
2767
2769 const auto timeout_ms = hermes_timeout_ms(timeout);
2770 const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds {timeout_ms};
2771 const bool cursor_mode_changed =
2772 !last_cursor_requested || *last_cursor_requested != cursor_requested;
2773 bool cursor_ready = false;
2774 errno = 0;
2775 if (cursor_requested && !cursor_mode_changed) {
2778 hermes_fd,
2779 last_sequence,
2780 last_cursor_sequence,
2781 timeout_ms,
2782 update)) {
2783 return hermes_acquire_failure("CPU-copy update wait", errno);
2784 }
2785 cursor_ready = update.cursor_ready;
2786 } else if (cursor_requested) {
2787 cursor_ready = true;
2788 }
2789 if (!VDISPLAY::hermesKmsAcquireFrame(
2790 hermes_fd,
2791 last_sequence,
2792 (cursor_requested || cursor_mode_changed) ? 0U : timeout_ms,
2793 frame, source_color.known())) {
2794 return hermes_acquire_failure("CPU-copy", errno);
2795 }
2796 accumulate_capture_metric("hermes-kms-cpu", frame.acquire_ns);
2797
2798 // The encoder was built for one channel layout and one colour
2799 // description; a compositor that switches either needs a new one.
2800 // The display's immutable colour snapshot also supplies its HDR SEI.
2801 if (frame.width != img_width || frame.height != img_height ||
2802 frame.fourcc != source_fourcc || !(frame.color == source_color)) {
2803 if (frame.fourcc != source_fourcc) {
2804 BOOST_LOG(info) << "Hermes-KMS CPU capture: scanout format changed from "sv
2805 << hermes_fourcc_name(source_fourcc) << " to "sv << hermes_fourcc_name(frame.fourcc);
2806 }
2807 frame.close();
2809 }
2810
2811 const auto frame_height = static_cast<std::size_t>(frame.height);
2812 const auto row_bytes = static_cast<std::size_t>(img_width) * std::size_t {4};
2813 const bool valid_layout =
2814 frame.plane_count == 1 &&
2815 frame.dma_buf_fd[0] >= 0 &&
2816 hermes_cpu_copy_format(frame.fourcc) &&
2817 (frame.modifier == DRM_FORMAT_MOD_LINEAR || frame.modifier == DRM_FORMAT_MOD_INVALID) &&
2818 static_cast<std::size_t>(frame.pitch[0]) >= row_bytes;
2819 const bool valid_destination =
2820 img_out->data && img_out->width == img_width && img_out->height == img_height &&
2821 img_out->pixel_pitch == 4 && img_out->row_pitch > 0 &&
2822 static_cast<std::size_t>(img_out->row_pitch) >= row_bytes;
2823 if (!valid_layout || !valid_destination) {
2824 BOOST_LOG(error) << "Hermes-KMS CPU capture: unexpected frame layout (planes="sv << frame.plane_count
2825 << ", fourcc=0x"sv << std::hex << frame.fourcc << std::dec
2826 << ", modifier=0x"sv << std::hex << frame.modifier << std::dec
2827 << ", pitch="sv << frame.pitch[0] << ')';
2828 frame.close();
2830 }
2831
2832 // A successful ACQUIRE_FRAME only means the frame was exported, not
2833 // that the producer finished writing it. The driver exports the
2834 // framebuffer's write fence as a sync file; wait for it before
2835 // touching the pixels.
2836 if (frame.sync_file_fd >= 0) {
2837 const auto fence_status = wait_hermes_frame_fence(frame.sync_file_fd, deadline);
2838 if (fence_status == hermes_fence_wait_e::timeout) {
2839 BOOST_LOG(warning) << "Hermes-KMS CPU capture: frame fence timed out."sv;
2840 frame.close();
2842 }
2843 if (fence_status == hermes_fence_wait_e::failed) {
2844 const int fence_errno = errno;
2845 BOOST_LOG(warning) << "Hermes-KMS CPU capture: dropping frame "sv
2846 << frame.sequence << " after producer fence failure: "sv
2847 << strerror(fence_errno);
2848 last_sequence = frame.sequence;
2849 frame.close();
2851 }
2852 if (fence_status == hermes_fence_wait_e::error) {
2853 const int fence_errno = errno;
2854 BOOST_LOG(error) << "Hermes-KMS CPU capture: invalid sync file: "sv
2855 << strerror(fence_errno);
2856 frame.close();
2858 }
2859 }
2860
2861 // The frame exists from here on. Stamp it now, so the copy below is
2862 // part of the reported processing latency instead of hiding before
2863 // the timestamp the way it used to.
2864 const auto frame_ready = std::chrono::steady_clock::now();
2865
2866 std::optional<cursor_t> pending_cursor;
2867 uint64_t pending_cursor_sequence = last_cursor_sequence;
2868 if (cursor_ready) {
2869 pending_cursor = captured_cursor;
2870 const auto cursor_status = refresh_hermes_cursor(
2871 hermes_fd,
2872 deadline,
2873 *pending_cursor,
2874 pending_cursor_sequence
2875 );
2876 if (cursor_status != capture_e::ok) {
2877 frame.close();
2878 return cursor_status;
2879 }
2880 }
2881
2882 const auto source_pitch = static_cast<std::size_t>(frame.pitch[0]);
2883 const auto source_offset = static_cast<std::size_t>(frame.offset[0]);
2884 const auto last_row = frame_height - 1;
2885 if (last_row > (std::numeric_limits<std::size_t>::max() - source_offset) / source_pitch) {
2886 BOOST_LOG(error) << "Hermes-KMS CPU capture: DMA-BUF row offset overflows size_t."sv;
2887 frame.close();
2889 }
2890 const auto last_row_offset = source_offset + last_row * source_pitch;
2891 if (row_bytes > std::numeric_limits<std::size_t>::max() - last_row_offset) {
2892 BOOST_LOG(error) << "Hermes-KMS CPU capture: DMA-BUF mapping length overflows size_t."sv;
2893 frame.close();
2895 }
2896 const auto map_len = last_row_offset + row_bytes;
2897
2898 // Mapped once per scanout buffer, not once per frame: see
2899 // platf::dmabuf::mapping_cache_t for what a per-frame mmap cost.
2900 const std::uint8_t *map = mappings.map(frame.dma_buf_fd[0], map_len);
2901 if (!map) {
2902 const int map_errno = errno;
2903 if (map_errno == EINVAL) {
2904 BOOST_LOG(error) << "Hermes-KMS CPU capture: frame metadata exceeds the DMA-BUF (needs "sv
2905 << map_len << " bytes)"sv;
2906 } else {
2907 BOOST_LOG(error) << "Hermes-KMS CPU capture: could not map the DMA-BUF: "sv
2908 << strerror(map_errno);
2909 }
2910 frame.close();
2912 }
2913
2914 // Bracket the CPU read as the DMA-BUF mmap contract requires.
2915 if (hermes_dma_buf_sync(frame.dma_buf_fd[0], DMA_BUF_SYNC_START | DMA_BUF_SYNC_READ) < 0) {
2916 const int sync_errno = errno;
2917 BOOST_LOG(error) << "Hermes-KMS CPU capture: DMA_BUF_SYNC_START failed: "sv
2918 << strerror(sync_errno);
2919 frame.close();
2921 }
2922
2924 img_out->data,
2925 static_cast<std::size_t>(img_out->row_pitch),
2926 map + frame.offset[0],
2927 source_pitch,
2928 row_bytes,
2929 frame_height
2930 );
2931
2932 if (hermes_dma_buf_sync(frame.dma_buf_fd[0], DMA_BUF_SYNC_END | DMA_BUF_SYNC_READ) < 0) {
2933 const int sync_errno = errno;
2934 BOOST_LOG(error) << "Hermes-KMS CPU capture: DMA_BUF_SYNC_END failed: "sv
2935 << strerror(sync_errno);
2936 frame.close();
2938 }
2939
2940 const cursor_t &cursor_for_frame = pending_cursor ? *pending_cursor : captured_cursor;
2941 if (cursor_requested && cursor_for_frame.visible) {
2942 blend_hermes_cursor(*img_out, cursor_for_frame, source_fourcc);
2943 }
2944
2945 last_sequence = frame.sequence;
2946 frame.close();
2947 if (pending_cursor) {
2948 captured_cursor = std::move(*pending_cursor);
2949 last_cursor_sequence = pending_cursor_sequence;
2950 }
2951 last_cursor_requested = cursor_requested;
2952
2953 img_out->frame_timestamp = frame_ready;
2954 return platf::capture_e::ok;
2955 }
2956
2957 capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor) override {
2958 if (probe_only) {
2959 return capture_e::error; // Probe objects may encode dummy images only.
2960 }
2961 while (true) {
2962 std::shared_ptr<platf::img_t> img_out;
2963 auto status = snapshot(pull_free_image_cb, img_out, 200ms, *cursor);
2964 switch (status) {
2968 return status;
2970 if (!push_captured_image_cb(std::move(img_out), false)) {
2971 return platf::capture_e::ok;
2972 }
2973 break;
2975 if (!push_captured_image_cb(std::move(img_out), true)) {
2976 return platf::capture_e::ok;
2977 }
2978 break;
2979 default:
2980 BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']';
2981 return status;
2982 }
2983 }
2984 return capture_e::ok;
2985 }
2986
2987 int hermes_fd {-1};
2989 std::uint64_t layout_generation {0};
2990 uint64_t last_sequence {0};
2991 uint64_t last_cursor_sequence {0};
2992 std::optional<bool> last_cursor_requested;
2995 bool warned_pageable {false};
2996 };
2997
2998 } // namespace kms
2999
3000 std::shared_ptr<display_t> kms_display(mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config) {
3001 const bool hermes_kms_display = VDISPLAY::isHermesKmsDisplay(display_name);
3002 if (VDISPLAY::isEvdiDisplay(display_name)) {
3003 auto display = std::make_shared<kms::display_evdi_t>(hwdevice_type);
3004 return display->init(display_name, config) ? nullptr : display;
3005 }
3006
3007 // Hermes-KMS streams zero-copy through its render node (ACQUIRE_FRAME),
3008 // never through KMS, so the compositor keeps DRM master and scans out the
3009 // desktop. Use the dedicated capture path and never fall back to a KMS
3010 // card, which would stream a physical monitor.
3011 if (hermes_kms_display) {
3012 if (hwdevice_type != mem_type_e::vaapi && hwdevice_type != mem_type_e::cuda) {
3013 BOOST_LOG(error) << "Hermes-KMS capture requires VAAPI or NVENC(CUDA); "sv
3014 << "the selected encoder is not supported."sv;
3015 return nullptr;
3016 }
3017
3018 // NVENC: NVIDIA's EGL import of these system-memory DMA-BUFs reads the
3019 // wrong pages beyond the first ones (diagonal-stripe corruption), so
3020 // route CUDA sessions through the always-correct CPU copy. VAAPI keeps
3021 // the validated zero-copy import.
3022 //
3023 // HERMES_KMS_FORCE_CPU_COPY=1 sends VAAPI sessions down the CPU copy as
3024 // well, so the path NVIDIA users depend on can be exercised and
3025 // measured on hardware that does not need it.
3026 const char *force_cpu_copy = std::getenv("HERMES_KMS_FORCE_CPU_COPY");
3027 const bool forced_cpu_copy = force_cpu_copy && !std::strcmp(force_cpu_copy, "1");
3028 if (forced_cpu_copy && hwdevice_type != mem_type_e::cuda) {
3029 BOOST_LOG(warning) << "HERMES_KMS_FORCE_CPU_COPY=1: using the CPU-copy capture path instead of zero-copy."sv;
3030 }
3031 if (hwdevice_type == mem_type_e::cuda || forced_cpu_copy) {
3032 auto disp = std::make_shared<kms::display_hermes_ram_t>(hwdevice_type);
3033 if (!disp->init(display_name, config)) {
3034 return disp;
3035 }
3036 BOOST_LOG(error) << "Hermes-KMS CPU-copy capture failed; refusing physical-display fallback."sv;
3037 return nullptr;
3038 }
3039
3040 auto disp = std::make_shared<kms::display_hermes_vram_t>(hwdevice_type);
3041 if (!disp->init(display_name, config)) {
3042 return disp;
3043 }
3044 BOOST_LOG(error) << "Hermes-KMS zero-copy capture failed; refusing physical-display fallback."sv;
3045 return nullptr;
3046 }
3047
3048 if (hwdevice_type == mem_type_e::vaapi || hwdevice_type == mem_type_e::cuda) {
3049 auto disp = std::make_shared<kms::display_vram_t>(hwdevice_type);
3050
3051 if (!disp->init(display_name, config)) {
3052 return disp;
3053 }
3054 }
3055
3056 if (hermes_kms_display) {
3057 BOOST_LOG(error) << "Hermes-KMS RAM capture is not supported; no active scanout framebuffer was found."sv;
3058 return nullptr;
3059 }
3060
3061 auto disp = std::make_shared<kms::display_ram_t>(hwdevice_type);
3062
3063 if (disp->init(display_name, config)) {
3064 return nullptr;
3065 }
3066
3067 return disp;
3068 }
3069
3080 void correlate_to_wayland(std::vector<kms::card_descriptor_t> &cds) {
3081 auto monitors = wl::monitors();
3082
3083 BOOST_LOG(info) << "-------- Start of KMS monitor list --------"sv;
3084
3085 for (auto &monitor : monitors) {
3086 std::string_view name = monitor->name;
3087
3088 // Try to convert names in the format:
3089 // {type}-{index}
3090 // {index} is n'th occurrence of {type}
3091 auto index_begin = name.find_last_of('-');
3092
3093 std::uint32_t index;
3094 if (index_begin == std::string_view::npos) {
3095 index = 1;
3096 } else {
3097 index = std::max<int64_t>(1, util::from_view(name.substr(index_begin + 1)));
3098 }
3099
3100 auto type = kms::from_view(name.substr(0, index_begin));
3101
3102 // A connector that drives nothing still carries a type and an index, so
3103 // the name Wayland reports can describe a live output on one card and a
3104 // disconnected connector on another. Taking the first type/index hit hands
3105 // the desktop offset to whichever card was enumerated first, which is how
3106 // a descriptor left at 0x0 comes to own the position of a real 2560x1440
3107 // output - and the offset the real one needed is then never applied.
3108 // Prefer the candidate whose resolution is the one Wayland just gave us,
3109 // and keep the bare type/index match, warning as before, as the fallback.
3110 kms::monitor_t *chosen = nullptr;
3111 kms::monitor_t *fallback = nullptr;
3112
3113 for (auto &card_descriptor : cds) {
3114 for (auto &[_, monitor_descriptor] : card_descriptor.crtc_to_monitor) {
3115 if (monitor_descriptor.index != index || monitor_descriptor.type != type) {
3116 continue;
3117 }
3118
3119 if (monitor_descriptor.viewport.width == monitor->viewport.width &&
3120 monitor_descriptor.viewport.height == monitor->viewport.height) {
3121 chosen = &monitor_descriptor;
3122 break;
3123 }
3124
3125 if (!fallback) {
3126 fallback = &monitor_descriptor;
3127 }
3128 }
3129
3130 if (chosen) {
3131 break;
3132 }
3133 }
3134
3135 if (!chosen) {
3136 chosen = fallback;
3137 }
3138
3139 if (chosen) {
3140 chosen->viewport.offset_x = monitor->viewport.offset_x;
3141 chosen->viewport.offset_y = monitor->viewport.offset_y;
3142
3143 // A sanity check, it's guesswork after all.
3144 if (
3145 chosen->viewport.width != monitor->viewport.width ||
3146 chosen->viewport.height != monitor->viewport.height
3147 ) {
3148 BOOST_LOG(warning)
3149 << "Mismatch on expected Resolution compared to actual resolution: "sv
3150 << chosen->viewport.width << 'x' << chosen->viewport.height
3151 << " vs "sv
3152 << monitor->viewport.width << 'x' << monitor->viewport.height;
3153 }
3154
3155 BOOST_LOG(info) << "Monitor " << chosen->monitor_index << " is "sv << name << ": "sv << monitor->description;
3156 }
3157
3158 BOOST_LOG(verbose) << "Reduced to name: "sv << name << ": "sv << index;
3159 }
3160
3161 BOOST_LOG(info) << "--------- End of KMS monitor list ---------"sv;
3162 }
3163
3164 // A list of names of displays accepted as display_name
3165 std::vector<std::string> kms_display_names(mem_type_e hwdevice_type) {
3166 int count = 0;
3167
3168 if (!fs::exists("/dev/dri")) {
3169 BOOST_LOG(warning) << "Couldn't find /dev/dri, kmsgrab won't be enabled"sv;
3170 return {};
3171 }
3172
3173 if (!gbm::create_device) {
3174 BOOST_LOG(warning) << "libgbm not initialized"sv;
3175 return {};
3176 }
3177
3178 kms::conn_type_count_t conn_type_count;
3179
3180 std::vector<kms::card_descriptor_t> cds;
3181 std::vector<std::string> display_names;
3182 std::map<std::string, int> index_by_connector;
3183
3184 fs::path card_dir {"/dev/dri"sv};
3185 for (auto &entry : fs::directory_iterator {card_dir}) {
3186 auto file = entry.path().filename();
3187
3188 auto filestring = file.generic_string();
3189 if (std::string_view {filestring}.substr(0, 4) != "card"sv) {
3190 continue;
3191 }
3192
3193 kms::card_t card;
3194 if (card.init(entry.path().c_str())) {
3195 continue;
3196 }
3197
3198 // Skip non-Nvidia cards if we're looking for CUDA devices
3199 // unless NVENC is selected manually by the user
3200 if (hwdevice_type == mem_type_e::cuda && !card.is_nvidia()) {
3201 BOOST_LOG(debug) << file << " is not a CUDA device"sv;
3202 if (config::video.encoder == "nvenc") {
3203 BOOST_LOG(warning) << "Using NVENC with your display connected to a different GPU may not work properly!"sv;
3204 } else {
3205 continue;
3206 }
3207 }
3208
3209 const auto monitors = card.monitors(conn_type_count);
3210 auto crtc_to_monitor = kms::map_crtc_to_monitor(monitors);
3211
3212 // Kernel connector names ("DP-2") by CRTC, to find the desktop's primary output.
3213 std::map<std::uint32_t, std::string> connector_by_crtc;
3214 for (const auto &monitor : monitors) {
3215 if (auto conn = card.connector(monitor.connector_id)) {
3216 connector_by_crtc.emplace(monitor.crtc_id, kms::kernel_connector_name(conn->connector_type, conn->connector_type_id));
3217 }
3218 }
3219
3220 auto end = std::end(card);
3221 for (auto plane = std::begin(card); plane != end; ++plane) {
3222 // Skip unused planes
3223 if (!plane->fb_id) {
3224 continue;
3225 }
3226
3227 if (card.is_cursor(plane->plane_id)) {
3228 continue;
3229 }
3230
3231 auto fb = card.fb(plane.get());
3232 if (!fb) {
3233 BOOST_LOG(error) << "Couldn't get drm fb for plane ["sv << plane->fb_id << "]: "sv << strerror(errno);
3234 continue;
3235 }
3236
3237 if (!fb->handles[0]) {
3238 BOOST_LOG(error) << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Probably not permitted"sv;
3239 BOOST_LOG((window_system != window_system_e::X11 || config::video.capture == "kms") ? fatal : error)
3240 << "You must run [sudo setcap cap_sys_admin+p $(readlink -f $(which hermes))] for KMS display capture to work!\n"sv
3241 << "The packages set this in their post-install script; a binary you built yourself needs it applied by hand.\n"sv
3242 << "See https://github.com/MrOz59/Hermes/blob/main/docs/troubleshooting.md"sv;
3243 break;
3244 }
3245
3246 // This appears to return the offset of the monitor
3247 auto crtc = card.crtc(plane->crtc_id);
3248 if (!crtc) {
3249 BOOST_LOG(error) << "Couldn't get CRTC info: "sv << strerror(errno);
3250 continue;
3251 }
3252
3253 auto it = crtc_to_monitor.find(plane->crtc_id);
3254 if (it != std::end(crtc_to_monitor)) {
3255 it->second.viewport = platf::touch_port_t {
3256 (int) crtc->x,
3257 (int) crtc->y,
3258 (int) crtc->width,
3259 (int) crtc->height,
3260 };
3261 it->second.monitor_index = count;
3262 }
3263
3264 if (const auto name = connector_by_crtc.find(plane->crtc_id); name != connector_by_crtc.end() && !name->second.empty()) {
3265 index_by_connector.emplace(name->second, count);
3266 }
3267
3268 kms::env_width = std::max(kms::env_width, (int) (crtc->x + crtc->width));
3269 kms::env_height = std::max(kms::env_height, (int) (crtc->y + crtc->height));
3270
3271 kms::print(plane.get(), fb.get(), crtc.get());
3272
3273 display_names.emplace_back(std::to_string(count++));
3274 }
3275
3276 cds.emplace_back(kms::card_descriptor_t {
3277 std::move(file),
3278 std::move(crtc_to_monitor),
3279 });
3280 }
3281
3282 if (!wl::init()) {
3284 }
3285
3286 // Deduce the full virtual desktop size
3287 kms::env_width = 0;
3288 kms::env_height = 0;
3289
3290 for (auto &card_descriptor : cds) {
3291 for (auto &[_, monitor_descriptor] : card_descriptor.crtc_to_monitor) {
3292 BOOST_LOG(debug) << "Monitor description"sv;
3293 BOOST_LOG(debug) << "Resolution: "sv << monitor_descriptor.viewport.width << 'x' << monitor_descriptor.viewport.height;
3294 BOOST_LOG(debug) << "Offset: "sv << monitor_descriptor.viewport.offset_x << 'x' << monitor_descriptor.viewport.offset_y;
3295
3296 kms::env_width = std::max(kms::env_width, (int) (monitor_descriptor.viewport.offset_x + monitor_descriptor.viewport.width));
3297 kms::env_height = std::max(kms::env_height, (int) (monitor_descriptor.viewport.offset_y + monitor_descriptor.viewport.height));
3298 }
3299 }
3300
3301 BOOST_LOG(debug) << "Desktop resolution: "sv << kms::env_width << 'x' << kms::env_height;
3302
3303 kms::card_descriptors = std::move(cds);
3304
3305 // Monitor numbers follow DRM plane order, which has nothing to do with the
3306 // desktop layout: monitor 0 can be a capture device or a dummy plug. When
3307 // no display is configured, the first name in this list is streamed, so
3308 // put the desktop's primary output first. Every number keeps its meaning,
3309 // so a configured display number still selects the same monitor.
3310 if (const auto primary = VDISPLAY::primaryPhysicalOutputName(); !primary.empty()) {
3311 const auto it = index_by_connector.find(primary);
3312 if (it == index_by_connector.end()) {
3313 BOOST_LOG(info) << "The desktop's primary output "sv << primary
3314 << " is dark (switched off or asleep), so it can't be the default display yet."sv;
3315 } else {
3316 const auto pos = std::find(display_names.begin(), display_names.end(), std::to_string(it->second));
3317 if (pos != display_names.end() && pos != display_names.begin()) {
3318 std::rotate(display_names.begin(), pos, pos + 1);
3319 BOOST_LOG(info) << "Monitor "sv << it->second << " ("sv << primary
3320 << ") is the desktop's primary output; it is streamed when no display is configured."sv;
3321 }
3322 }
3323 }
3324
3325 // Active Hermes-KMS virtual displays are capturable through their render
3326 // node even when no physical framebuffer handle is readable (no DRM
3327 // master, no CAP_SYS_ADMIN), so expose them alongside the physical
3328 // outputs. Session display lookups match these by name (e.g. HERMES-1).
3329 for (auto &name : VDISPLAY::listHermesKmsDisplayNames()) {
3330 if (std::find(display_names.begin(), display_names.end(), name) == display_names.end()) {
3331 display_names.emplace_back(std::move(name));
3332 }
3333 }
3334
3335 return display_names;
3336 }
3337
3338} // namespace platf
std::function< bool(std::shared_ptr< img_t > &&img, bool frame_captured)> push_captured_image_cb_t
Callback for when a new image is ready. When display has a new image ready or a timeout occurs,...
Definition common.h:452
std::function< bool(std::shared_ptr< img_t > &img_out)> pull_free_image_cb_t
Get free image from pool. Calls must be synchronized. Blocks until there is free image in the pool or...
Definition common.h:461
virtual std::unique_ptr< avcodec_encode_device_t > make_pyrowave_encode_device()
Make a device that converts captured frames into PyroWave's GPU planes.
Definition common.h:500
capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *) override
Capture a frame.
Definition kmsgrab.cpp:1926
std::uint64_t layout_generation
The desktop layout this capture resolved its geometry against.
Definition kmsgrab.cpp:2989
platf::dmabuf::mapping_cache_t mappings
CPU mappings of the scanout buffers the compositor rotates through.
Definition kmsgrab.cpp:2994
capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor) override
Capture a frame.
Definition kmsgrab.cpp:2957
std::uint64_t layout_generation
The desktop layout this capture resolved its geometry against.
Definition kmsgrab.cpp:2589
capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor)
Capture a frame.
Definition kmsgrab.cpp:2557
capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor) override
Capture a frame.
Definition kmsgrab.cpp:1726
bool plane_lost
The plane had no framebuffer at the last refresh().
Definition kmsgrab.cpp:1678
bool requires_hdr_for_hdr_output() const override
Whether this capture backend requires an HDR encoder when the display is in HDR mode.
Definition kmsgrab.cpp:1361
capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor)
Capture a frame.
Definition kmsgrab.cpp:2059
Declarations for common platform specific utilities.
mem_type_e
Definition common.h:211
@ vaapi
VAAPI.
Definition common.h:213
std::shared_ptr< display_t > display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config)
Get the display_t instance for the given hwdevice_type. If display_name is empty, use the first monit...
Definition misc.cpp:1658
pix_fmt_e
Definition common.h:218
capture_e
Definition common.h:435
@ ok
Success.
Definition common.h:436
@ timeout
Timeout.
Definition common.h:438
@ reinit
Need to reinitialize.
Definition common.h:437
@ error
Error.
Definition common.h:440
@ interrupted
Capture was interrupted.
Definition common.h:439
Declarations for the configuration of Sunshine.
std::unique_ptr< platf::avcodec_encode_device_t > make_avcodec_gl_encode_device(int width, int height, int offset_x, int offset_y)
Create a GL->CUDA encoding device for consuming captured dmabufs.
Definition cuda.cpp:612
Definitions for CUDA implementation.
layout_e
How the 32-bit little-endian words of a CPU-copied frame hold their channels.
Definition cuda_pixel.h:21
@ bgra8
DRM XRGB8888 / ARGB8888: bytes B, G, R, X.
Definition cuda_pixel.h:22
@ bgr10
DRM XBGR2101010 / ABGR2101010: B in bits 29:20, G in 19:10, R in 9:0.
Definition cuda_pixel.h:24
@ rgb10
DRM XRGB2101010 / ARGB2101010: R in bits 29:20, G in 19:10, B in 9:0.
Definition cuda_pixel.h:23
std::optional< client_t > find(const std::filesystem::path &proc, uid_t uid, const std::filesystem::path &pid_file, std::string_view own_cgroup)
The user's running Steam client.
std::unique_ptr< platf::deinit_t > init(const std::filesystem::path &persistence_filepath, const config::video_t &video_config)
Initialize the implementation and perform the initial state recovery (if needed).
Persistent CPU mappings of DMA-BUFs, and a copy suited to reading them.
void copy_rows(std::uint8_t *dst, std::size_t dst_pitch, const std::uint8_t *src, std::size_t src_pitch, std::size_t row_bytes, std::size_t rows, std::size_t block_bytes=copy_block_bytes)
int open_encode_render_node(bool nvenc)
Open the render node of the best GPU to encode a stream on.
Declarations for graphics related functions.
std::string hermes_fourcc_name(uint32_t fourcc)
"XR30" for a printable fourcc, its hex value otherwise.
Definition kmsgrab.cpp:619
bool hermes_layout_changed(std::uint64_t &recorded)
Definition kmsgrab.cpp:2183
void blend_hermes_cursor(img_t &img, const cursor_t &cursor, uint32_t fourcc=DRM_FORMAT_ARGB8888)
Definition kmsgrab.cpp:651
void correlate_to_wayland(std::vector< kms::card_descriptor_t > &cds)
Definition kmsgrab.cpp:3080
constexpr bool hermes_cpu_copy_format(uint32_t fourcc)
Definition kmsgrab.cpp:641
void resolve_hermes_input_geometry(const std::string &display_name, int width, int height, int &offset_x, int &offset_y, int &env_width, int &env_height)
Definition kmsgrab.cpp:2207
constexpr bool hermes_ten_bit_format(uint32_t fourcc)
A frame word packing 10-bit R, G and B, in either channel order.
Definition kmsgrab.cpp:634
Declarations for logging related functions.
int open_drm_node(const char *path, int flags)
Open a DRM device node without becoming its DRM master.
Definition misc.cpp:138
Miscellaneous declarations for Linux.
@ X11
X11.
Definition misc.h:22
GPU conversion for the experimental PyroWave codec.
Declarations for a round-robin iterator.
uint32_t src_x
DRM 16.16 fixed point.
uint32_t src_h
DRM 16.16 fixed point.
void close()
Close all owned fds (dma_buf_fd[] and sync_file_fd).
uint32_t src_w
DRM 16.16 fixed point.
uint32_t src_y
DRM 16.16 fixed point.
long long acquire_ns
Time spent in the ACQUIRE_FRAME ioctl only.
void close()
Close all owned fds (dma_buf_fd[] and sync_file_fd).
Declarations for utility functions.
Declarations for VA-API hardware accelerated capture.
Declarations for video.
bool hermesKmsAcquireCursor(int render_fd, bool request_buffer, HermesKmsCursor &out)
int getEvdiCardIndex(const std::string &displayName)
Get the DRM card index for an EVDI display.
bool isEvdiDisplay(const std::string &displayName)
Check if a display name is an EVDI virtual display.
std::vector< std::string > listHermesKmsDisplayNames()
uint64_t displayLayoutGeneration()
A counter bumped whenever the desktop layout changes underneath a running session.
int hermesKmsOpenCapture(const std::string &display_name)
bool hermesKmsWaitUpdate(int render_fd, uint64_t after_frame_sequence, uint64_t after_cursor_sequence, uint32_t timeout_ms, HermesKmsUpdate &out)
int getHermesKmsCardIndex(const std::string &displayName)
bool getHermesKmsDisplayGeometry(const std::string &display_name, int &offset_x, int &offset_y, int &environment_width, int &environment_height)
bool hermesKmsCaptureColor(int render_fd, hermes_kms::color_t &color, uint32_t &fourcc)
bool hermesKmsCaptureSize(int render_fd, int &width, int &height, uint32_t timeout_ms)
std::shared_ptr< EvdiBuffer > getEvdiBuffer(const std::string &display_name)
bool isHermesKmsDisplay(const std::string &displayName)
std::string primaryPhysicalOutputName()
The desktop's primary physical output ("DP-2"), or empty.
std::string getHermesKmsSeatName(const std::string &displayName)
Virtual display declarations for Linux.
@ primary
Side-by-side like extend, with the virtual output as the primary one.
Declarations for Wayland capture.