12#include <X11/extensions/Xfixes.h>
13#include <X11/extensions/Xrandr.h>
18#include <xcb/xfixes.h>
34using namespace std::literals;
41#define _FN(x, ret, args) \
42 typedef ret(*x##_fn) args; \
45 _FN(GetImage, XImage *, (Display * display, Drawable d,
int x,
int y,
unsigned int width,
unsigned int height,
unsigned long plane_mask,
int format));
47 _FN(OpenDisplay, Display *, (_Xconst
char *display_name));
48 _FN(GetWindowAttributes, Status, (Display * display, Window w, XWindowAttributes *window_attributes_return));
50 _FN(CloseDisplay,
int, (Display * display));
51 _FN(Free,
int, (
void *data));
52 _FN(InitThreads, Status, (
void) );
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));
63 static void *handle {
nullptr};
64 static bool funcs_loaded =
false;
71 handle = dyn::handle({
"libXrandr.so.2",
"libXrandr.so"});
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"},
86 if (dyn::load(handle, funcs)) {
97 _FN(GetCursorImage, XFixesCursorImage *, (Display * dpy));
100 static void *handle {
nullptr};
101 static bool funcs_loaded =
false;
108 handle = dyn::handle({
"libXfixes.so.3",
"libXfixes.so"});
114 std::vector<std::tuple<dyn::apiproc *, const char *>> funcs {
115 {(dyn::apiproc *) &GetCursorImage,
"XFixesGetCursorImage"},
118 if (dyn::load(handle, funcs)) {
128 static void *handle {
nullptr};
129 static bool funcs_loaded =
false;
136 handle = dyn::handle({
"libX11.so.6",
"libX11.so"});
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"},
151 if (dyn::load(handle, funcs)) {
161 static xcb_extension_t *shm_id;
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));
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));
167 _FN(shm_attach, xcb_void_cookie_t, (xcb_connection_t * c, xcb_shm_seg_t shmseg, uint32_t shmid, uint8_t read_only));
169 _FN(get_extension_data, xcb_query_extension_reply_t *, (xcb_connection_t * c, xcb_extension_t *ext));
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));
179 static void *handle {
nullptr};
180 static bool funcs_loaded =
false;
187 handle = dyn::handle({
"libxcb-shm.so.0",
"libxcb-shm.so"});
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"},
200 if (dyn::load(handle, funcs)) {
209 static void *handle {
nullptr};
210 static bool funcs_loaded =
false;
217 handle = dyn::handle({
"libxcb.so.1",
"libxcb.so"});
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"},
233 if (dyn::load(handle, funcs)) {
244 void freeImage(XImage *);
245 void freeX(XFixesCursorImage *);
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>;
250 using ximg_t = util::safe_ptr<XImage, freeImage>;
251 using xcursor_t = util::safe_ptr<XFixesCursorImage, freeX>;
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>;
267 shm_id_t(shm_id_t &&other)
noexcept:
274 shmctl(
id, IPC_RMID,
nullptr);
288 shm_data_t(
void *data):
292 shm_data_t(shm_data_t &&other)
noexcept:
294 other.data = (
void *) -1;
298 if ((std::uintptr_t) data != -1) {
317 static void blend_cursor(Display *
display,
img_t &img,
int offsetX,
int offsetY) {
318 xcursor_t overlay {x11::fix::GetCursorImage(
display)};
321 BOOST_LOG(error) <<
"Couldn't get cursor from XFixesGetCursorImage"sv;
325 overlay->x -= overlay->xhot;
326 overlay->y -= overlay->yhot;
328 overlay->x -= offsetX;
329 overlay->y -= offsetY;
331 overlay->x = std::max((
short) 0, overlay->x);
332 overlay->y = std::max((
short) 0, overlay->y);
334 auto pixels = (
int *) img.data;
336 auto screen_height = img.height;
337 auto screen_width = img.width;
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];
345 auto pixels_begin = &pixels[(y + overlay->y) * (img.row_pitch / img.pixel_pitch) + overlay->x];
347 std::for_each(overlay_begin, overlay_end, [&](
long pixel) {
348 int *pixel_p = (
int *) &pixel;
350 auto colors_in = (uint8_t *) pixels_begin;
352 auto alpha = (*(uint *) pixel_p) >> 24u;
354 *pixels_begin = *pixel_p;
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;
367 std::chrono::nanoseconds delay;
369 x11::xdisplay_t xdisplay;
371 XWindowAttributes xattr;
382 xdisplay {x11::OpenDisplay(nullptr)},
385 mem_type {mem_type} {
389 int init(
const std::string &display_name, const ::video::config_t &config) {
391 BOOST_LOG(error) <<
"Could not open X11 display"sv;
395 delay = std::chrono::nanoseconds {1s} / config.framerate;
397 xwindow = DefaultRootWindow(xdisplay.get());
401 int streamedMonitor = -1;
402 if (!display_name.empty() && display_name.rfind(
"VIRTUAL-", 0) != 0) {
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;
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;
414 output_info_t result;
416 for (
int x = 0; x < output; ++x) {
417 output_info_t out_info {x11::rr::GetOutputInfo(xdisplay.get(), screenr.get(), screenr->outputs[x])};
419 if (monitor++ == streamedMonitor) {
420 result = std::move(out_info);
427 BOOST_LOG(error) <<
"Could not stream display number ["sv << streamedMonitor <<
"], there are only ["sv << monitor <<
"] displays."sv;
432 crtc_info_t crt_info {x11::rr::GetCrtcInfo(xdisplay.get(), screenr.get(), result->crtc)};
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;
436 width = crt_info->width;
437 height = crt_info->height;
438 offset_x = crt_info->x;
439 offset_y = crt_info->y;
441 BOOST_LOG(warning) <<
"Couldn't get requested display info, defaulting to recording entire virtual desktop"sv;
443 height = xattr.height;
447 height = xattr.height;
450 env_width = xattr.width;
451 env_height = xattr.height;
460 x11::GetWindowAttributes(xdisplay.get(), xwindow, &xattr);
464 auto next_frame = std::chrono::steady_clock::now();
466 sleep_overshoot_logger.reset();
469 auto now = std::chrono::steady_clock::now();
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();
478 if (next_frame < now) {
479 next_frame = now + delay;
482 std::shared_ptr<platf::img_t> img_out;
483 auto status = snapshot(pull_free_image_cb, img_out, 1000ms, *cursor);
490 if (!push_captured_image_cb(std::move(img_out),
false)) {
495 if (!push_captured_image_cb(std::move(img_out),
true)) {
500 BOOST_LOG(error) <<
"Unrecognized capture status ["sv << (int) status <<
']';
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) {
512 if (xattr.width != env_width || xattr.height != env_height) {
513 BOOST_LOG(warning) <<
"X dimensions changed in non-SHM mode, request reinit"sv;
517 if (!pull_free_image_cb(img_out)) {
520 auto img = (x11_img_t *) img_out.get();
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();
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);
533 blend_cursor(xdisplay.get(), *img, offset_x, offset_y);
536 return capture_e::ok;
539 std::shared_ptr<img_t> alloc_img()
override {
540 return std::make_shared<x11_img_t>();
545 return pyrowave::make_ram_encode_device(width, height);
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);
556#ifdef HERMES_BUILD_CUDA
557 if (mem_type == mem_type_e::cuda) {
558 return cuda::make_avcodec_encode_device(width, height,
false);
562 return std::make_unique<avcodec_encode_device_t>();
565 int dummy_img(img_t *img)
override {
570 auto pull_dummy_img_callback = [&img](std::shared_ptr<platf::img_t> &img_out) ->
bool {
571 img_out = img->shared_from_this();
574 std::shared_ptr<platf::img_t> img_out;
575 snapshot(pull_dummy_img_callback, img_out, 0s,
true);
581 x11::xdisplay_t shm_xdisplay;
583 xcb_screen_t *display;
590 task_pool_util::TaskPool::task_id_t refresh_task_id;
592 void delayed_refresh() {
595 refresh_task_id =
task_pool.pushDelayed(&shm_attr_t::delayed_refresh, 2s,
this).task_id;
600 shm_xdisplay {x11::OpenDisplay(
nullptr)} {
601 refresh_task_id =
task_pool.pushDelayed(&shm_attr_t::delayed_refresh, 2s,
this).task_id;
604 ~shm_attr_t()
override {
605 while (!
task_pool.cancel(refresh_task_id));
609 auto next_frame = std::chrono::steady_clock::now();
611 sleep_overshoot_logger.reset();
614 auto now = std::chrono::steady_clock::now();
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();
623 if (next_frame < now) {
624 next_frame = now + delay;
627 std::shared_ptr<platf::img_t> img_out;
628 auto status = snapshot(pull_free_image_cb, img_out, 1000ms, *cursor);
635 if (!push_captured_image_cb(std::move(img_out),
false)) {
640 if (!push_captured_image_cb(std::move(img_out),
true)) {
645 BOOST_LOG(error) <<
"Unrecognized capture status ["sv << (int) status <<
']';
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) {
655 if (xattr.width != env_width || xattr.height != env_height) {
656 BOOST_LOG(warning) <<
"X dimensions changed in SHM mode, request reinit"sv;
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();
662 xcb_img_t img_reply {xcb::shm_get_image_reply(xcb.get(), img_cookie,
nullptr)};
664 BOOST_LOG(error) <<
"Could not get image reply"sv;
665 return capture_e::reinit;
668 if (!pull_free_image_cb(img_out)) {
669 return platf::capture_e::interrupted;
672 std::copy_n((std::uint8_t *) data.data, frame_size(), img_out->data);
673 img_out->frame_timestamp = frame_timestamp;
676 blend_cursor(shm_xdisplay.get(), *img_out, offset_x, offset_y);
679 return capture_e::ok;
683 std::shared_ptr<img_t> alloc_img()
override {
684 auto img = std::make_shared<shm_img_t>();
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];
694 int dummy_img(platf::img_t *img)
override {
698 int init(
const std::string &display_name, const ::video::config_t &config) {
699 if (x11_attr_t::init(display_name, config)) {
703 shm_xdisplay.reset(x11::OpenDisplay(
nullptr));
704 xcb.reset(xcb::connect(
nullptr,
nullptr));
705 if (xcb::connection_has_error(xcb.get())) {
709 if (!xcb::get_extension_data(xcb.get(), xcb::shm_id)->present) {
710 BOOST_LOG(error) <<
"Missing SHM extension"sv;
715 auto iter = xcb::setup_roots_iterator(xcb::get_setup(xcb.get()));
717 seg = xcb::generate_id(xcb.get());
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;
725 xcb::shm_attach(xcb.get(), seg, shm_id.id,
false);
726 data.data = shmat(shm_id.id,
nullptr, 0);
728 if ((uintptr_t) data.data == -1) {
729 BOOST_LOG(error) <<
"shmat failed"sv;
737 std::uint32_t frame_size() {
738 return width * height * 4;
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;
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;
755 auto shm_disp = std::make_shared<shm_attr_t>(hwdevice_type);
757 auto status = shm_disp->init(display_name, config);
768 auto x11_disp = std::make_shared<x11_attr_t>(hwdevice_type);
769 if (x11_disp->init(display_name, config)) {
776 std::vector<std::string> x11_display_names() {
777 if (load_x11() || load_xcb()) {
778 BOOST_LOG(
error) <<
"Couldn't init x11 libraries"sv;
783 BOOST_LOG(info) <<
"Detecting displays"sv;
785 x11::xdisplay_t xdisplay {x11::OpenDisplay(
nullptr)};
790 auto xwindow = DefaultRootWindow(xdisplay.get());
791 screen_res_t screenr {x11::rr::GetScreenResources(xdisplay.get(), xwindow)};
792 int output = screenr->noutput;
795 for (
int x = 0; x < output; ++x) {
796 output_info_t out_info {x11::rr::GetOutputInfo(xdisplay.get(), screenr.get(), screenr->outputs[x])};
798 BOOST_LOG(info) <<
"Detected display: "sv << out_info->name <<
" (id: "sv << monitor <<
")"sv << out_info->name <<
" connected: "sv << (out_info->connection == RR_Connected);
803 std::vector<std::string> names;
804 names.reserve(monitor);
806 for (
auto x = 0; x < monitor; ++x) {
807 names.emplace_back(std::to_string(x));
813 void freeImage(XImage *p) {
817 void freeX(XFixesCursorImage *p) {
823 static int xcb_status = xcb::init_shm() || xcb::init();
830 static int x11_status =
832 x11::init() || x11::rr::init() || x11::fix::init();
838 std::optional<cursor_t> cursor_t::make() {
845 cursor.ctx.reset((cursor_ctx_t::pointer) x11::OpenDisplay(
nullptr));
850 void cursor_t::capture(egl::cursor_t &img) {
851 auto display = (xdisplay_t::pointer) ctx.get();
853 xcursor_t xcursor = fix::GetCursorImage(display);
855 if (img.serial != xcursor->cursor_serial) {
856 auto buf_size = xcursor->width * xcursor->height *
sizeof(int);
858 if (img.buffer.size() < buf_size) {
859 img.buffer.resize(buf_size);
862 std::transform(xcursor->pixels, xcursor->pixels + buf_size / 4, (
int *) img.buffer.data(), [](
long pixel) ->
int {
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;
873 img.row_pitch = img.pixel_pitch * img.width;
874 img.serial = xcursor->cursor_serial;
878 blend_cursor((xdisplay_t::pointer) ctx.get(), img, offsetX, offsetY);
881 xdisplay_t make_display() {
882 return OpenDisplay(
nullptr);
885 void freeDisplay(_XDisplay *xdisplay) {
886 CloseDisplay(xdisplay);
889 void freeCursorCtx(cursor_ctx_t::pointer ctx) {
890 CloseDisplay((xdisplay_t::pointer) ctx);
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,...
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...
virtual std::unique_ptr< avcodec_encode_device_t > make_pyrowave_encode_device()
Make a device that converts captured frames into PyroWave's GPU planes.
void blend(img_t &img, int offsetX, int offsetY)
Declarations for common platform specific utilities.
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...
@ reinit
Need to reinitialize.
@ interrupted
Capture was interrupted.
Declarations for the configuration of Sunshine.
Definitions for CUDA implementation.
thread_pool_util::ThreadPool task_pool
A thread pool for processing tasks.
Declarations for globally accessible variables and functions.
Declarations for graphics related functions.
Declarations for logging related functions.
Miscellaneous declarations for Linux.
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.
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.
x11_attr_t(mem_type_e mem_type)
Declarations for the task pool system.
Declarations for VA-API hardware accelerated capture.
Declarations for x11 capture.