Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
x11grab.cpp
Go to the documentation of this file.
1
5// standard includes
6#include <fstream>
7#include <thread>
8
9// plaform includes
10#include <sys/ipc.h>
11#include <sys/shm.h>
12#include <X11/extensions/Xfixes.h>
13#include <X11/extensions/Xrandr.h>
14#include <X11/X.h>
15#include <X11/Xlib.h>
16#include <X11/Xutil.h>
17#include <xcb/shm.h>
18#include <xcb/xfixes.h>
19
20// local includes
21#include "cuda.h"
22#include "graphics.h"
23#include "misc.h"
24#include "pyrowave.h"
25#include "src/config.h"
26#include "src/globals.h"
27#include "src/logging.h"
28#include "src/platform/common.h"
29#include "src/task_pool.h"
30#include "src/video.h"
31#include "vaapi.h"
32#include "x11grab.h"
33
34using namespace std::literals;
35
36namespace platf {
37 int load_xcb();
38 int load_x11();
39
40 namespace x11 {
41#define _FN(x, ret, args) \
42 typedef ret(*x##_fn) args; \
43 static x##_fn x
44
45 _FN(GetImage, XImage *, (Display * display, Drawable d, int x, int y, unsigned int width, unsigned int height, unsigned long plane_mask, int format));
46
47 _FN(OpenDisplay, Display *, (_Xconst char *display_name));
48 _FN(GetWindowAttributes, Status, (Display * display, Window w, XWindowAttributes *window_attributes_return));
49
50 _FN(CloseDisplay, int, (Display * display));
51 _FN(Free, int, (void *data));
52 _FN(InitThreads, Status, (void) );
53
54 namespace rr {
55 _FN(GetScreenResources, XRRScreenResources *, (Display * dpy, Window window));
56 _FN(GetOutputInfo, XRROutputInfo *, (Display * dpy, XRRScreenResources *resources, RROutput output));
57 _FN(GetCrtcInfo, XRRCrtcInfo *, (Display * dpy, XRRScreenResources *resources, RRCrtc crtc));
58 _FN(FreeScreenResources, void, (XRRScreenResources * resources));
59 _FN(FreeOutputInfo, void, (XRROutputInfo * outputInfo));
60 _FN(FreeCrtcInfo, void, (XRRCrtcInfo * crtcInfo));
61
62 static int init() {
63 static void *handle {nullptr};
64 static bool funcs_loaded = false;
65
66 if (funcs_loaded) {
67 return 0;
68 }
69
70 if (!handle) {
71 handle = dyn::handle({"libXrandr.so.2", "libXrandr.so"});
72 if (!handle) {
73 return -1;
74 }
75 }
76
77 std::vector<std::tuple<dyn::apiproc *, const char *>> funcs {
78 {(dyn::apiproc *) &GetScreenResources, "XRRGetScreenResources"},
79 {(dyn::apiproc *) &GetOutputInfo, "XRRGetOutputInfo"},
80 {(dyn::apiproc *) &GetCrtcInfo, "XRRGetCrtcInfo"},
81 {(dyn::apiproc *) &FreeScreenResources, "XRRFreeScreenResources"},
82 {(dyn::apiproc *) &FreeOutputInfo, "XRRFreeOutputInfo"},
83 {(dyn::apiproc *) &FreeCrtcInfo, "XRRFreeCrtcInfo"},
84 };
85
86 if (dyn::load(handle, funcs)) {
87 return -1;
88 }
89
90 funcs_loaded = true;
91 return 0;
92 }
93
94 } // namespace rr
95
96 namespace fix {
97 _FN(GetCursorImage, XFixesCursorImage *, (Display * dpy));
98
99 static int init() {
100 static void *handle {nullptr};
101 static bool funcs_loaded = false;
102
103 if (funcs_loaded) {
104 return 0;
105 }
106
107 if (!handle) {
108 handle = dyn::handle({"libXfixes.so.3", "libXfixes.so"});
109 if (!handle) {
110 return -1;
111 }
112 }
113
114 std::vector<std::tuple<dyn::apiproc *, const char *>> funcs {
115 {(dyn::apiproc *) &GetCursorImage, "XFixesGetCursorImage"},
116 };
117
118 if (dyn::load(handle, funcs)) {
119 return -1;
120 }
121
122 funcs_loaded = true;
123 return 0;
124 }
125 } // namespace fix
126
127 static int init() {
128 static void *handle {nullptr};
129 static bool funcs_loaded = false;
130
131 if (funcs_loaded) {
132 return 0;
133 }
134
135 if (!handle) {
136 handle = dyn::handle({"libX11.so.6", "libX11.so"});
137 if (!handle) {
138 return -1;
139 }
140 }
141
142 std::vector<std::tuple<dyn::apiproc *, const char *>> funcs {
143 {(dyn::apiproc *) &GetImage, "XGetImage"},
144 {(dyn::apiproc *) &OpenDisplay, "XOpenDisplay"},
145 {(dyn::apiproc *) &GetWindowAttributes, "XGetWindowAttributes"},
146 {(dyn::apiproc *) &Free, "XFree"},
147 {(dyn::apiproc *) &CloseDisplay, "XCloseDisplay"},
148 {(dyn::apiproc *) &InitThreads, "XInitThreads"},
149 };
150
151 if (dyn::load(handle, funcs)) {
152 return -1;
153 }
154
155 funcs_loaded = true;
156 return 0;
157 }
158 } // namespace x11
159
160 namespace xcb {
161 static xcb_extension_t *shm_id;
162
163 _FN(shm_get_image_reply, xcb_shm_get_image_reply_t *, (xcb_connection_t * c, xcb_shm_get_image_cookie_t cookie, xcb_generic_error_t **e));
164
165 _FN(shm_get_image_unchecked, xcb_shm_get_image_cookie_t, (xcb_connection_t * c, xcb_drawable_t drawable, int16_t x, int16_t y, uint16_t width, uint16_t height, uint32_t plane_mask, uint8_t format, xcb_shm_seg_t shmseg, uint32_t offset));
166
167 _FN(shm_attach, xcb_void_cookie_t, (xcb_connection_t * c, xcb_shm_seg_t shmseg, uint32_t shmid, uint8_t read_only));
168
169 _FN(get_extension_data, xcb_query_extension_reply_t *, (xcb_connection_t * c, xcb_extension_t *ext));
170
171 _FN(get_setup, xcb_setup_t *, (xcb_connection_t * c));
172 _FN(disconnect, void, (xcb_connection_t * c));
173 _FN(connection_has_error, int, (xcb_connection_t * c));
174 _FN(connect, xcb_connection_t *, (const char *displayname, int *screenp));
175 _FN(setup_roots_iterator, xcb_screen_iterator_t, (const xcb_setup_t *R));
176 _FN(generate_id, std::uint32_t, (xcb_connection_t * c));
177
178 int init_shm() {
179 static void *handle {nullptr};
180 static bool funcs_loaded = false;
181
182 if (funcs_loaded) {
183 return 0;
184 }
185
186 if (!handle) {
187 handle = dyn::handle({"libxcb-shm.so.0", "libxcb-shm.so"});
188 if (!handle) {
189 return -1;
190 }
191 }
192
193 std::vector<std::tuple<dyn::apiproc *, const char *>> funcs {
194 {(dyn::apiproc *) &shm_id, "xcb_shm_id"},
195 {(dyn::apiproc *) &shm_get_image_reply, "xcb_shm_get_image_reply"},
196 {(dyn::apiproc *) &shm_get_image_unchecked, "xcb_shm_get_image_unchecked"},
197 {(dyn::apiproc *) &shm_attach, "xcb_shm_attach"},
198 };
199
200 if (dyn::load(handle, funcs)) {
201 return -1;
202 }
203
204 funcs_loaded = true;
205 return 0;
206 }
207
208 int init() {
209 static void *handle {nullptr};
210 static bool funcs_loaded = false;
211
212 if (funcs_loaded) {
213 return 0;
214 }
215
216 if (!handle) {
217 handle = dyn::handle({"libxcb.so.1", "libxcb.so"});
218 if (!handle) {
219 return -1;
220 }
221 }
222
223 std::vector<std::tuple<dyn::apiproc *, const char *>> funcs {
224 {(dyn::apiproc *) &get_extension_data, "xcb_get_extension_data"},
225 {(dyn::apiproc *) &get_setup, "xcb_get_setup"},
226 {(dyn::apiproc *) &disconnect, "xcb_disconnect"},
227 {(dyn::apiproc *) &connection_has_error, "xcb_connection_has_error"},
228 {(dyn::apiproc *) &connect, "xcb_connect"},
229 {(dyn::apiproc *) &setup_roots_iterator, "xcb_setup_roots_iterator"},
230 {(dyn::apiproc *) &generate_id, "xcb_generate_id"},
231 };
232
233 if (dyn::load(handle, funcs)) {
234 return -1;
235 }
236
237 funcs_loaded = true;
238 return 0;
239 }
240
241#undef _FN
242 } // namespace xcb
243
244 void freeImage(XImage *);
245 void freeX(XFixesCursorImage *);
246
247 using xcb_connect_t = util::dyn_safe_ptr<xcb_connection_t, &xcb::disconnect>;
248 using xcb_img_t = util::c_ptr<xcb_shm_get_image_reply_t>;
249
250 using ximg_t = util::safe_ptr<XImage, freeImage>;
251 using xcursor_t = util::safe_ptr<XFixesCursorImage, freeX>;
252
253 using crtc_info_t = util::dyn_safe_ptr<_XRRCrtcInfo, &x11::rr::FreeCrtcInfo>;
254 using output_info_t = util::dyn_safe_ptr<_XRROutputInfo, &x11::rr::FreeOutputInfo>;
255 using screen_res_t = util::dyn_safe_ptr<_XRRScreenResources, &x11::rr::FreeScreenResources>;
256
257 class shm_id_t {
258 public:
259 shm_id_t():
260 id {-1} {
261 }
262
263 shm_id_t(int id):
264 id {id} {
265 }
266
267 shm_id_t(shm_id_t &&other) noexcept:
268 id(other.id) {
269 other.id = -1;
270 }
271
272 ~shm_id_t() {
273 if (id != -1) {
274 shmctl(id, IPC_RMID, nullptr);
275 id = -1;
276 }
277 }
278
279 int id;
280 };
281
282 class shm_data_t {
283 public:
284 shm_data_t():
285 data {(void *) -1} {
286 }
287
288 shm_data_t(void *data):
289 data {data} {
290 }
291
292 shm_data_t(shm_data_t &&other) noexcept:
293 data(other.data) {
294 other.data = (void *) -1;
295 }
296
297 ~shm_data_t() {
298 if ((std::uintptr_t) data != -1) {
299 shmdt(data);
300 }
301 }
302
303 void *data;
304 };
305
306 struct x11_img_t: public img_t {
307 ximg_t img;
308 };
309
310 struct shm_img_t: public img_t {
311 ~shm_img_t() override {
312 delete[] data;
313 data = nullptr;
314 }
315 };
316
317 static void blend_cursor(Display *display, img_t &img, int offsetX, int offsetY) {
318 xcursor_t overlay {x11::fix::GetCursorImage(display)};
319
320 if (!overlay) {
321 BOOST_LOG(error) << "Couldn't get cursor from XFixesGetCursorImage"sv;
322 return;
323 }
324
325 overlay->x -= overlay->xhot;
326 overlay->y -= overlay->yhot;
327
328 overlay->x -= offsetX;
329 overlay->y -= offsetY;
330
331 overlay->x = std::max((short) 0, overlay->x);
332 overlay->y = std::max((short) 0, overlay->y);
333
334 auto pixels = (int *) img.data;
335
336 auto screen_height = img.height;
337 auto screen_width = img.width;
338
339 auto delta_height = std::min<uint16_t>(overlay->height, std::max(0, screen_height - overlay->y));
340 auto delta_width = std::min<uint16_t>(overlay->width, std::max(0, screen_width - overlay->x));
341 for (auto y = 0; y < delta_height; ++y) {
342 auto overlay_begin = &overlay->pixels[y * overlay->width];
343 auto overlay_end = &overlay->pixels[y * overlay->width + delta_width];
344
345 auto pixels_begin = &pixels[(y + overlay->y) * (img.row_pitch / img.pixel_pitch) + overlay->x];
346
347 std::for_each(overlay_begin, overlay_end, [&](long pixel) {
348 int *pixel_p = (int *) &pixel;
349
350 auto colors_in = (uint8_t *) pixels_begin;
351
352 auto alpha = (*(uint *) pixel_p) >> 24u;
353 if (alpha == 255) {
354 *pixels_begin = *pixel_p;
355 } else {
356 auto colors_out = (uint8_t *) pixel_p;
357 colors_in[0] = colors_out[0] + (colors_in[0] * (255 - alpha) + 255 / 2) / 255;
358 colors_in[1] = colors_out[1] + (colors_in[1] * (255 - alpha) + 255 / 2) / 255;
359 colors_in[2] = colors_out[2] + (colors_in[2] * (255 - alpha) + 255 / 2) / 255;
360 }
361 ++pixels_begin;
362 });
363 }
364 }
365
366 struct x11_attr_t: public display_t {
367 std::chrono::nanoseconds delay;
368
369 x11::xdisplay_t xdisplay;
370 Window xwindow;
371 XWindowAttributes xattr;
372
373 mem_type_e mem_type;
374
379 // int env_width, env_height;
380
382 xdisplay {x11::OpenDisplay(nullptr)},
383 xwindow {},
384 xattr {},
385 mem_type {mem_type} {
386 x11::InitThreads();
387 }
388
389 int init(const std::string &display_name, const ::video::config_t &config) {
390 if (!xdisplay) {
391 BOOST_LOG(error) << "Could not open X11 display"sv;
392 return -1;
393 }
394
395 delay = std::chrono::nanoseconds {1s} / config.framerate;
396
397 xwindow = DefaultRootWindow(xdisplay.get());
398
399 refresh();
400
401 int streamedMonitor = -1;
402 if (!display_name.empty() && display_name.rfind("VIRTUAL-", 0) != 0) {
403 // Not a virtual display, parse as numeric index
404 streamedMonitor = (int) util::from_view(display_name);
405 } else if (display_name.rfind("VIRTUAL-", 0) == 0) {
406 BOOST_LOG(debug) << "Virtual display detected ["sv << display_name << "], using primary monitor for X11 capture"sv;
407 }
408
409 if (streamedMonitor != -1) {
410 BOOST_LOG(info) << "Configuring selected display ("sv << streamedMonitor << ") to stream"sv;
411 screen_res_t screenr {x11::rr::GetScreenResources(xdisplay.get(), xwindow)};
412 int output = screenr->noutput;
413
414 output_info_t result;
415 int monitor = 0;
416 for (int x = 0; x < output; ++x) {
417 output_info_t out_info {x11::rr::GetOutputInfo(xdisplay.get(), screenr.get(), screenr->outputs[x])};
418 if (out_info) {
419 if (monitor++ == streamedMonitor) {
420 result = std::move(out_info);
421 break;
422 }
423 }
424 }
425
426 if (!result) {
427 BOOST_LOG(error) << "Could not stream display number ["sv << streamedMonitor << "], there are only ["sv << monitor << "] displays."sv;
428 return -1;
429 }
430
431 if (result->crtc) {
432 crtc_info_t crt_info {x11::rr::GetCrtcInfo(xdisplay.get(), screenr.get(), result->crtc)};
433 BOOST_LOG(info)
434 << "Streaming display: "sv << result->name << " with res "sv << crt_info->width << 'x' << crt_info->height << " offset by "sv << crt_info->x << 'x' << crt_info->y;
435
436 width = crt_info->width;
437 height = crt_info->height;
438 offset_x = crt_info->x;
439 offset_y = crt_info->y;
440 } else {
441 BOOST_LOG(warning) << "Couldn't get requested display info, defaulting to recording entire virtual desktop"sv;
442 width = xattr.width;
443 height = xattr.height;
444 }
445 } else {
446 width = xattr.width;
447 height = xattr.height;
448 }
449
450 env_width = xattr.width;
451 env_height = xattr.height;
452
453 return 0;
454 }
455
459 void refresh() {
460 x11::GetWindowAttributes(xdisplay.get(), xwindow, &xattr); // Update xattr's
461 }
462
463 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 {
464 auto next_frame = std::chrono::steady_clock::now();
465
466 sleep_overshoot_logger.reset();
467
468 while (true) {
469 auto now = std::chrono::steady_clock::now();
470
471 if (next_frame > now) {
472 std::this_thread::sleep_for(next_frame - now);
473 sleep_overshoot_logger.first_point(next_frame);
474 sleep_overshoot_logger.second_point_now_and_log();
475 }
476
477 next_frame += delay;
478 if (next_frame < now) { // some major slowdown happened; we couldn't keep up
479 next_frame = now + delay;
480 }
481
482 std::shared_ptr<platf::img_t> img_out;
483 auto status = snapshot(pull_free_image_cb, img_out, 1000ms, *cursor);
484 switch (status) {
488 return status;
490 if (!push_captured_image_cb(std::move(img_out), false)) {
492 }
493 break;
495 if (!push_captured_image_cb(std::move(img_out), true)) {
497 }
498 break;
499 default:
500 BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']';
501 return status;
502 }
503 }
504
505 return capture_e::ok;
506 }
507
508 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) {
509 refresh();
510
511 // The whole X server changed, so we must reinit everything
512 if (xattr.width != env_width || xattr.height != env_height) {
513 BOOST_LOG(warning) << "X dimensions changed in non-SHM mode, request reinit"sv;
514 return capture_e::reinit;
515 }
516
517 if (!pull_free_image_cb(img_out)) {
519 }
520 auto img = (x11_img_t *) img_out.get();
521
522 XImage *x_img {x11::GetImage(xdisplay.get(), xwindow, offset_x, offset_y, width, height, AllPlanes, ZPixmap)};
523 img->frame_timestamp = std::chrono::steady_clock::now();
524
525 img->width = x_img->width;
526 img->height = x_img->height;
527 img->data = (uint8_t *) x_img->data;
528 img->row_pitch = x_img->bytes_per_line;
529 img->pixel_pitch = x_img->bits_per_pixel / 8;
530 img->img.reset(x_img);
531
532 if (cursor) {
533 blend_cursor(xdisplay.get(), *img, offset_x, offset_y);
534 }
535
536 return capture_e::ok;
537 }
538
539 std::shared_ptr<img_t> alloc_img() override {
540 return std::make_shared<x11_img_t>();
541 }
542
543#ifdef HAVE_PYROWAVE
544 std::unique_ptr<avcodec_encode_device_t> make_pyrowave_encode_device() override {
545 return pyrowave::make_ram_encode_device(width, height);
546 }
547#endif
548
549 std::unique_ptr<avcodec_encode_device_t> make_avcodec_encode_device(pix_fmt_e pix_fmt) override {
550#ifdef HERMES_BUILD_VAAPI
551 if (mem_type == mem_type_e::vaapi) {
552 return va::make_avcodec_encode_device(width, height, false);
553 }
554#endif
555
556#ifdef HERMES_BUILD_CUDA
557 if (mem_type == mem_type_e::cuda) {
558 return cuda::make_avcodec_encode_device(width, height, false);
559 }
560#endif
561
562 return std::make_unique<avcodec_encode_device_t>();
563 }
564
565 int dummy_img(img_t *img) override {
566 // TODO: stop cheating and give black image
567 if (!img) {
568 return -1;
569 };
570 auto pull_dummy_img_callback = [&img](std::shared_ptr<platf::img_t> &img_out) -> bool {
571 img_out = img->shared_from_this();
572 return true;
573 };
574 std::shared_ptr<platf::img_t> img_out;
575 snapshot(pull_dummy_img_callback, img_out, 0s, true);
576 return 0;
577 }
578 };
579
580 struct shm_attr_t: public x11_attr_t {
581 x11::xdisplay_t shm_xdisplay; // Prevent race condition with x11_attr_t::xdisplay
582 xcb_connect_t xcb;
583 xcb_screen_t *display;
584 std::uint32_t seg;
585
586 shm_id_t shm_id;
587
588 shm_data_t data;
589
590 task_pool_util::TaskPool::task_id_t refresh_task_id;
591
592 void delayed_refresh() {
593 refresh();
594
595 refresh_task_id = task_pool.pushDelayed(&shm_attr_t::delayed_refresh, 2s, this).task_id;
596 }
597
598 shm_attr_t(mem_type_e mem_type):
599 x11_attr_t(mem_type),
600 shm_xdisplay {x11::OpenDisplay(nullptr)} {
601 refresh_task_id = task_pool.pushDelayed(&shm_attr_t::delayed_refresh, 2s, this).task_id;
602 }
603
604 ~shm_attr_t() override {
605 while (!task_pool.cancel(refresh_task_id));
606 }
607
608 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 {
609 auto next_frame = std::chrono::steady_clock::now();
610
611 sleep_overshoot_logger.reset();
612
613 while (true) {
614 auto now = std::chrono::steady_clock::now();
615
616 if (next_frame > now) {
617 std::this_thread::sleep_for(next_frame - now);
618 sleep_overshoot_logger.first_point(next_frame);
619 sleep_overshoot_logger.second_point_now_and_log();
620 }
621
622 next_frame += delay;
623 if (next_frame < now) { // some major slowdown happened; we couldn't keep up
624 next_frame = now + delay;
625 }
626
627 std::shared_ptr<platf::img_t> img_out;
628 auto status = snapshot(pull_free_image_cb, img_out, 1000ms, *cursor);
629 switch (status) {
633 return status;
635 if (!push_captured_image_cb(std::move(img_out), false)) {
637 }
638 break;
640 if (!push_captured_image_cb(std::move(img_out), true)) {
642 }
643 break;
644 default:
645 BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']';
646 return status;
647 }
648 }
649
650 return capture_e::ok;
651 }
652
653 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) {
654 // The whole X server changed, so we must reinit everything
655 if (xattr.width != env_width || xattr.height != env_height) {
656 BOOST_LOG(warning) << "X dimensions changed in SHM mode, request reinit"sv;
657 return capture_e::reinit;
658 } else {
659 auto img_cookie = xcb::shm_get_image_unchecked(xcb.get(), display->root, offset_x, offset_y, width, height, ~0, XCB_IMAGE_FORMAT_Z_PIXMAP, seg, 0);
660 auto frame_timestamp = std::chrono::steady_clock::now();
661
662 xcb_img_t img_reply {xcb::shm_get_image_reply(xcb.get(), img_cookie, nullptr)};
663 if (!img_reply) {
664 BOOST_LOG(error) << "Could not get image reply"sv;
665 return capture_e::reinit;
666 }
667
668 if (!pull_free_image_cb(img_out)) {
669 return platf::capture_e::interrupted;
670 }
671
672 std::copy_n((std::uint8_t *) data.data, frame_size(), img_out->data);
673 img_out->frame_timestamp = frame_timestamp;
674
675 if (cursor) {
676 blend_cursor(shm_xdisplay.get(), *img_out, offset_x, offset_y);
677 }
678
679 return capture_e::ok;
680 }
681 }
682
683 std::shared_ptr<img_t> alloc_img() override {
684 auto img = std::make_shared<shm_img_t>();
685 img->width = width;
686 img->height = height;
687 img->pixel_pitch = 4;
688 img->row_pitch = img->pixel_pitch * width;
689 img->data = new std::uint8_t[height * img->row_pitch];
690
691 return img;
692 }
693
694 int dummy_img(platf::img_t *img) override {
695 return 0;
696 }
697
698 int init(const std::string &display_name, const ::video::config_t &config) {
699 if (x11_attr_t::init(display_name, config)) {
700 return 1;
701 }
702
703 shm_xdisplay.reset(x11::OpenDisplay(nullptr));
704 xcb.reset(xcb::connect(nullptr, nullptr));
705 if (xcb::connection_has_error(xcb.get())) {
706 return -1;
707 }
708
709 if (!xcb::get_extension_data(xcb.get(), xcb::shm_id)->present) {
710 BOOST_LOG(error) << "Missing SHM extension"sv;
711
712 return -1;
713 }
714
715 auto iter = xcb::setup_roots_iterator(xcb::get_setup(xcb.get()));
716 display = iter.data;
717 seg = xcb::generate_id(xcb.get());
718
719 shm_id.id = shmget(IPC_PRIVATE, frame_size(), IPC_CREAT | 0777);
720 if (shm_id.id == -1) {
721 BOOST_LOG(error) << "shmget failed"sv;
722 return -1;
723 }
724
725 xcb::shm_attach(xcb.get(), seg, shm_id.id, false);
726 data.data = shmat(shm_id.id, nullptr, 0);
727
728 if ((uintptr_t) data.data == -1) {
729 BOOST_LOG(error) << "shmat failed"sv;
730
731 return -1;
732 }
733
734 return 0;
735 }
736
737 std::uint32_t frame_size() {
738 return width * height * 4;
739 }
740 };
741
742 std::shared_ptr<display_t> x11_display(platf::mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config) {
743 if (hwdevice_type != platf::mem_type_e::system && hwdevice_type != platf::mem_type_e::vaapi && hwdevice_type != platf::mem_type_e::cuda) {
744 BOOST_LOG(error) << "Could not initialize x11 display with the given hw device type"sv;
745 return nullptr;
746 }
747
748 if (xcb::init_shm() || xcb::init() || x11::init() || x11::rr::init() || x11::fix::init()) {
749 BOOST_LOG(error) << "Couldn't init x11 libraries"sv;
750
751 return nullptr;
752 }
753
754 // Attempt to use shared memory X11 to avoid copying the frame
755 auto shm_disp = std::make_shared<shm_attr_t>(hwdevice_type);
756
757 auto status = shm_disp->init(display_name, config);
758 if (status > 0) {
759 // x11_attr_t::init() failed, don't bother trying again.
760 return nullptr;
761 }
762
763 if (status == 0) {
764 return shm_disp;
765 }
766
767 // Fallback
768 auto x11_disp = std::make_shared<x11_attr_t>(hwdevice_type);
769 if (x11_disp->init(display_name, config)) {
770 return nullptr;
771 }
772
773 return x11_disp;
774 }
775
776 std::vector<std::string> x11_display_names() {
777 if (load_x11() || load_xcb()) {
778 BOOST_LOG(error) << "Couldn't init x11 libraries"sv;
779
780 return {};
781 }
782
783 BOOST_LOG(info) << "Detecting displays"sv;
784
785 x11::xdisplay_t xdisplay {x11::OpenDisplay(nullptr)};
786 if (!xdisplay) {
787 return {};
788 }
789
790 auto xwindow = DefaultRootWindow(xdisplay.get());
791 screen_res_t screenr {x11::rr::GetScreenResources(xdisplay.get(), xwindow)};
792 int output = screenr->noutput;
793
794 int monitor = 0;
795 for (int x = 0; x < output; ++x) {
796 output_info_t out_info {x11::rr::GetOutputInfo(xdisplay.get(), screenr.get(), screenr->outputs[x])};
797 if (out_info) {
798 BOOST_LOG(info) << "Detected display: "sv << out_info->name << " (id: "sv << monitor << ")"sv << out_info->name << " connected: "sv << (out_info->connection == RR_Connected);
799 ++monitor;
800 }
801 }
802
803 std::vector<std::string> names;
804 names.reserve(monitor);
805
806 for (auto x = 0; x < monitor; ++x) {
807 names.emplace_back(std::to_string(x));
808 }
809
810 return names;
811 }
812
813 void freeImage(XImage *p) {
814 XDestroyImage(p);
815 }
816
817 void freeX(XFixesCursorImage *p) {
818 x11::Free(p);
819 }
820
821 int load_xcb() {
822 // This will be called once only
823 static int xcb_status = xcb::init_shm() || xcb::init();
824
825 return xcb_status;
826 }
827
828 int load_x11() {
829 // This will be called once only
830 static int x11_status =
831 window_system == window_system_e::NONE ||
832 x11::init() || x11::rr::init() || x11::fix::init();
833
834 return x11_status;
835 }
836
837 namespace x11 {
838 std::optional<cursor_t> cursor_t::make() {
839 if (load_x11()) {
840 return std::nullopt;
841 }
842
843 cursor_t cursor;
844
845 cursor.ctx.reset((cursor_ctx_t::pointer) x11::OpenDisplay(nullptr));
846
847 return cursor;
848 }
849
850 void cursor_t::capture(egl::cursor_t &img) {
851 auto display = (xdisplay_t::pointer) ctx.get();
852
853 xcursor_t xcursor = fix::GetCursorImage(display);
854
855 if (img.serial != xcursor->cursor_serial) {
856 auto buf_size = xcursor->width * xcursor->height * sizeof(int);
857
858 if (img.buffer.size() < buf_size) {
859 img.buffer.resize(buf_size);
860 }
861
862 std::transform(xcursor->pixels, xcursor->pixels + buf_size / 4, (int *) img.buffer.data(), [](long pixel) -> int {
863 return pixel;
864 });
865 }
866
867 img.data = img.buffer.data();
868 img.width = img.src_w = xcursor->width;
869 img.height = img.src_h = xcursor->height;
870 img.x = xcursor->x - xcursor->xhot;
871 img.y = xcursor->y - xcursor->yhot;
872 img.pixel_pitch = 4;
873 img.row_pitch = img.pixel_pitch * img.width;
874 img.serial = xcursor->cursor_serial;
875 }
876
877 void cursor_t::blend(img_t &img, int offsetX, int offsetY) {
878 blend_cursor((xdisplay_t::pointer) ctx.get(), img, offsetX, offsetY);
879 }
880
881 xdisplay_t make_display() {
882 return OpenDisplay(nullptr);
883 }
884
885 void freeDisplay(_XDisplay *xdisplay) {
886 CloseDisplay(xdisplay);
887 }
888
889 void freeCursorCtx(cursor_ctx_t::pointer ctx) {
890 CloseDisplay((xdisplay_t::pointer) ctx);
891 }
892 } // namespace x11
893} // 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
void blend(img_t &img, int offsetX, int offsetY)
Definition x11grab.cpp:877
Declarations for common platform specific utilities.
mem_type_e
Definition common.h:211
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
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.
Definitions for CUDA implementation.
thread_pool_util::ThreadPool task_pool
A thread pool for processing tasks.
Definition globals.cpp:9
Declarations for globally accessible variables and functions.
Declarations for graphics related functions.
Declarations for logging related functions.
Miscellaneous declarations for Linux.
@ NONE
No window system.
Definition misc.h:21
GPU conversion for the experimental PyroWave codec.
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 x11grab.cpp:608
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 x11grab.cpp:463
x11_attr_t(mem_type_e mem_type)
Definition x11grab.cpp:381
Declarations for the task pool system.
Declarations for VA-API hardware accelerated capture.
Declarations for video.
Declarations for x11 capture.