xcomposite-input.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. #include <obs-module.h>
  2. #include <obs-nix-platform.h>
  3. #include <glad/glad.h>
  4. #include <X11/Xlib.h>
  5. #include <X11/Xutil.h>
  6. #include <X11/Xlib-xcb.h>
  7. #include <xcb/xcb.h>
  8. #include <xcb/composite.h>
  9. #include <pthread.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <stdint.h>
  13. #include <stdbool.h>
  14. #include <stdio.h>
  15. #include <ctype.h>
  16. #include "xhelpers.h"
  17. #include "xcursor-xcb.h"
  18. #include "xcomposite-input.h"
  19. #include <util/platform.h>
  20. #include <util/dstr.h>
  21. #include <util/darray.h>
  22. #define WIN_STRING_DIV "\r\n"
  23. #define FIND_WINDOW_INTERVAL 0.5
  24. static Display *disp = NULL;
  25. static xcb_connection_t *conn = NULL;
  26. // Atoms used throughout our plugin
  27. xcb_atom_t ATOM_UTF8_STRING;
  28. xcb_atom_t ATOM_STRING;
  29. xcb_atom_t ATOM_TEXT;
  30. xcb_atom_t ATOM_COMPOUND_TEXT;
  31. xcb_atom_t ATOM_WM_NAME;
  32. xcb_atom_t ATOM_WM_CLASS;
  33. xcb_atom_t ATOM__NET_WM_NAME;
  34. xcb_atom_t ATOM__NET_SUPPORTING_WM_CHECK;
  35. xcb_atom_t ATOM__NET_CLIENT_LIST;
  36. struct xcompcap {
  37. obs_source_t *source;
  38. const char *windowName;
  39. xcb_window_t win;
  40. int crop_top;
  41. int crop_left;
  42. int crop_right;
  43. int crop_bot;
  44. bool include_border;
  45. bool exclude_alpha;
  46. float window_check_time;
  47. bool window_changed;
  48. bool window_hooked;
  49. uint32_t width;
  50. uint32_t height;
  51. uint32_t border;
  52. Pixmap pixmap;
  53. gs_texture_t *gltex;
  54. pthread_mutex_t lock;
  55. bool show_cursor;
  56. bool cursor_outside;
  57. xcb_xcursor_t *cursor;
  58. };
  59. static void xcompcap_update(void *data, obs_data_t *settings);
  60. xcb_atom_t get_atom(xcb_connection_t *conn, const char *name)
  61. {
  62. xcb_intern_atom_cookie_t atom_c =
  63. xcb_intern_atom(conn, 1, strlen(name), name);
  64. xcb_intern_atom_reply_t *atom_r =
  65. xcb_intern_atom_reply(conn, atom_c, NULL);
  66. xcb_atom_t a = atom_r->atom;
  67. free(atom_r);
  68. return a;
  69. }
  70. void xcomp_gather_atoms(xcb_connection_t *conn)
  71. {
  72. ATOM_UTF8_STRING = get_atom(conn, "UTF8_STRING");
  73. ATOM_STRING = get_atom(conn, "STRING");
  74. ATOM_TEXT = get_atom(conn, "TEXT");
  75. ATOM_COMPOUND_TEXT = get_atom(conn, "COMPOUND_TEXT");
  76. ATOM_WM_NAME = get_atom(conn, "WM_NAME");
  77. ATOM_WM_CLASS = get_atom(conn, "WM_CLASS");
  78. ATOM__NET_WM_NAME = get_atom(conn, "_NET_WM_NAME");
  79. ATOM__NET_SUPPORTING_WM_CHECK =
  80. get_atom(conn, "_NET_SUPPORTING_WM_CHECK");
  81. ATOM__NET_CLIENT_LIST = get_atom(conn, "_NET_CLIENT_LIST");
  82. }
  83. bool xcomp_window_exists(xcb_connection_t *conn, xcb_window_t win)
  84. {
  85. xcb_generic_error_t *err = NULL;
  86. xcb_get_window_attributes_cookie_t attr_cookie =
  87. xcb_get_window_attributes(conn, win);
  88. xcb_get_window_attributes_reply_t *attr =
  89. xcb_get_window_attributes_reply(conn, attr_cookie, &err);
  90. bool exists = err == NULL && attr->map_state == XCB_MAP_STATE_VIEWABLE;
  91. free(attr);
  92. return exists;
  93. }
  94. xcb_get_property_reply_t *xcomp_property_sync(xcb_connection_t *conn,
  95. xcb_window_t win, xcb_atom_t atom)
  96. {
  97. if (atom == XCB_ATOM_NONE)
  98. return NULL;
  99. xcb_generic_error_t *err = NULL;
  100. // Read properties up to 4096*4 bytes
  101. xcb_get_property_cookie_t prop_cookie =
  102. xcb_get_property(conn, 0, win, atom, 0, 0, 4096);
  103. xcb_get_property_reply_t *prop =
  104. xcb_get_property_reply(conn, prop_cookie, &err);
  105. if (err != NULL || xcb_get_property_value_length(prop) == 0) {
  106. free(prop);
  107. return NULL;
  108. }
  109. return prop;
  110. }
  111. // See ICCCM https://www.x.org/releases/X11R7.6/doc/xorg-docs/specs/ICCCM/icccm.html#text_properties
  112. // for more info on the galactic brained string types used in Xorg.
  113. struct dstr xcomp_window_name(xcb_connection_t *conn, Display *disp,
  114. xcb_window_t win)
  115. {
  116. struct dstr ret = {0};
  117. xcb_get_property_reply_t *name =
  118. xcomp_property_sync(conn, win, ATOM__NET_WM_NAME);
  119. if (name) {
  120. // Guaranteed to be UTF8_STRING.
  121. const char *data = (const char *)xcb_get_property_value(name);
  122. dstr_ncopy(&ret, data, xcb_get_property_value_length(name));
  123. free(name);
  124. return ret;
  125. }
  126. name = xcomp_property_sync(conn, win, ATOM_WM_NAME);
  127. if (!name) {
  128. goto fail;
  129. }
  130. char *data = (char *)xcb_get_property_value(name);
  131. if (name->type == ATOM_UTF8_STRING) {
  132. dstr_ncopy(&ret, data, xcb_get_property_value_length(name));
  133. free(name);
  134. return ret;
  135. }
  136. if (name->type == ATOM_STRING) { // Latin-1, safe enough
  137. dstr_ncopy(&ret, data, xcb_get_property_value_length(name));
  138. free(name);
  139. return ret;
  140. }
  141. if (name->type == ATOM_TEXT) { // Default charset
  142. char *utf8;
  143. if (!os_mbs_to_utf8_ptr(
  144. data, xcb_get_property_value_length(name), &utf8)) {
  145. free(name);
  146. goto fail;
  147. }
  148. free(name);
  149. dstr_init_move_array(&ret, utf8);
  150. return ret;
  151. }
  152. if (name->type ==
  153. ATOM_COMPOUND_TEXT) { // LibX11 is the only decoder for these.
  154. XTextProperty xname = {
  155. (unsigned char *)data, name->type,
  156. 8, // 8 by definition.
  157. 1, // Only decode the first element of string arrays.
  158. };
  159. char **list;
  160. int len = 0;
  161. if (XmbTextPropertyToTextList(disp, &xname, &list, &len) <
  162. Success ||
  163. !list || len < 1) {
  164. free(name);
  165. goto fail;
  166. }
  167. char *utf8;
  168. if (!os_mbs_to_utf8_ptr(list[0], 0, &utf8)) {
  169. XFreeStringList(list);
  170. free(name);
  171. goto fail;
  172. }
  173. dstr_init_move_array(&ret, utf8);
  174. XFreeStringList(list);
  175. free(name);
  176. return ret;
  177. }
  178. fail:
  179. dstr_copy(&ret, "unknown");
  180. return ret;
  181. }
  182. struct dstr xcomp_window_class(xcb_connection_t *conn, xcb_window_t win)
  183. {
  184. struct dstr ret = {0};
  185. dstr_copy(&ret, "unknown");
  186. xcb_get_property_reply_t *cls =
  187. xcomp_property_sync(conn, win, ATOM_WM_CLASS);
  188. if (!cls)
  189. return ret;
  190. // WM_CLASS is formatted differently from other strings, it's two null terminated strings.
  191. // Since we want the first one, let's just let copy run strlen.
  192. dstr_copy(&ret, (const char *)xcb_get_property_value(cls));
  193. free(cls);
  194. return ret;
  195. }
  196. // Specification for checking for ewmh support at
  197. // http://standards.freedesktop.org/wm-spec/wm-spec-latest.html#idm140200472693600
  198. bool xcomp_check_ewmh(xcb_connection_t *conn, xcb_window_t root)
  199. {
  200. xcb_get_property_reply_t *check =
  201. xcomp_property_sync(conn, root, ATOM__NET_SUPPORTING_WM_CHECK);
  202. if (!check)
  203. return false;
  204. xcb_window_t ewmh_window =
  205. ((xcb_window_t *)xcb_get_property_value(check))[0];
  206. free(check);
  207. xcb_get_property_reply_t *check2 = xcomp_property_sync(
  208. conn, ewmh_window, ATOM__NET_SUPPORTING_WM_CHECK);
  209. if (!check2)
  210. return false;
  211. free(check2);
  212. return true;
  213. }
  214. struct darray xcomp_top_level_windows(xcb_connection_t *conn)
  215. {
  216. DARRAY(xcb_window_t) res = {0};
  217. // EWMH top level window listing is not supported.
  218. if (ATOM__NET_CLIENT_LIST == XCB_ATOM_NONE)
  219. return res.da;
  220. xcb_screen_iterator_t screen_iter =
  221. xcb_setup_roots_iterator(xcb_get_setup(conn));
  222. for (; screen_iter.rem > 0; xcb_screen_next(&screen_iter)) {
  223. xcb_generic_error_t *err = NULL;
  224. // Read properties up to 4096*4 bytes
  225. xcb_get_property_cookie_t cl_list_cookie =
  226. xcb_get_property(conn, 0, screen_iter.data->root,
  227. ATOM__NET_CLIENT_LIST, 0, 0, 4096);
  228. xcb_get_property_reply_t *cl_list =
  229. xcb_get_property_reply(conn, cl_list_cookie, &err);
  230. if (err != NULL) {
  231. goto done;
  232. }
  233. uint32_t len = xcb_get_property_value_length(cl_list) /
  234. sizeof(xcb_window_t);
  235. for (uint32_t i = 0; i < len; i++)
  236. da_push_back(res,
  237. &(((xcb_window_t *)xcb_get_property_value(
  238. cl_list))[i]));
  239. done:
  240. free(cl_list);
  241. }
  242. return res.da;
  243. }
  244. xcb_window_t xcomp_find_window(xcb_connection_t *conn, Display *disp,
  245. const char *str)
  246. {
  247. xcb_window_t ret = 0;
  248. DARRAY(xcb_window_t) tlw = {0};
  249. tlw.da = xcomp_top_level_windows(conn);
  250. if (!str || strlen(str) == 0) {
  251. if (tlw.num > 0)
  252. ret = *(xcb_window_t *)darray_item(sizeof(xcb_window_t),
  253. &tlw.da, 0);
  254. goto cleanup1;
  255. }
  256. size_t markSize = strlen(WIN_STRING_DIV);
  257. const char *firstMark = strstr(str, WIN_STRING_DIV);
  258. const char *secondMark =
  259. firstMark ? strstr(firstMark + markSize, WIN_STRING_DIV) : NULL;
  260. const char *strEnd = str + strlen(str);
  261. const char *secondStr = firstMark + markSize;
  262. const char *thirdStr = secondMark + markSize;
  263. // wstr only consists of the window-id
  264. if (!firstMark)
  265. return (xcb_window_t)atol(str);
  266. // wstr also contains window-name and window-class
  267. char *wname = bzalloc(secondMark - secondStr + 1);
  268. char *wcls = bzalloc(strEnd - thirdStr + 1);
  269. memcpy(wname, secondStr, secondMark - secondStr);
  270. memcpy(wcls, thirdStr, strEnd - thirdStr);
  271. ret = (xcb_window_t)strtol(str, NULL, 10);
  272. // first try to find a match by the window-id
  273. if (da_find(tlw, &ret, 0) != DARRAY_INVALID) {
  274. goto cleanup2;
  275. }
  276. // then try to find a match by name & class
  277. for (size_t i = 0; i < tlw.num; i++) {
  278. xcb_window_t cwin = *(xcb_window_t *)darray_item(
  279. sizeof(xcb_window_t), &tlw.da, i);
  280. struct dstr cwname = xcomp_window_name(conn, disp, cwin);
  281. struct dstr cwcls = xcomp_window_class(conn, cwin);
  282. bool found = strcmp(wname, cwname.array) == 0 &&
  283. strcmp(wcls, cwcls.array) == 0;
  284. dstr_free(&cwname);
  285. dstr_free(&cwcls);
  286. if (found) {
  287. ret = cwin;
  288. goto cleanup2;
  289. }
  290. }
  291. blog(LOG_DEBUG,
  292. "Did not find new window id for Name '%s' or Class '%s'", wname,
  293. wcls);
  294. cleanup2:
  295. bfree(wname);
  296. bfree(wcls);
  297. cleanup1:
  298. da_free(tlw);
  299. return ret;
  300. }
  301. void xcomp_cleanup_pixmap(Display *disp, struct xcompcap *s)
  302. {
  303. if (s->gltex) {
  304. gs_texture_destroy(s->gltex);
  305. s->gltex = 0;
  306. }
  307. if (s->pixmap) {
  308. XFreePixmap(disp, s->pixmap);
  309. s->pixmap = 0;
  310. }
  311. }
  312. static enum gs_color_format gs_format_from_tex()
  313. {
  314. GLint iformat = 0;
  315. // consider GL_ARB_internalformat_query
  316. glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT,
  317. &iformat);
  318. // These formats are known to be wrong on Intel platforms. We intentionally
  319. // use swapped internal formats here to preserve historic behavior which
  320. // swapped colors accidentally and because D3D11 would not support a
  321. // GS_RGBX format.
  322. switch (iformat) {
  323. case GL_RGB:
  324. return GS_BGRX_UNORM;
  325. case GL_RGBA:
  326. return GS_RGBA_UNORM;
  327. default:
  328. return GS_RGBA_UNORM;
  329. }
  330. }
  331. static int silence_x11_errors(Display *display, XErrorEvent *err)
  332. {
  333. UNUSED_PARAMETER(display);
  334. UNUSED_PARAMETER(err);
  335. return 0;
  336. }
  337. void xcomp_create_pixmap(xcb_connection_t *conn, struct xcompcap *s,
  338. int log_level)
  339. {
  340. if (!s->win)
  341. return;
  342. xcb_generic_error_t *err = NULL;
  343. xcb_get_geometry_cookie_t geom_cookie = xcb_get_geometry(conn, s->win);
  344. xcb_get_geometry_reply_t *geom =
  345. xcb_get_geometry_reply(conn, geom_cookie, &err);
  346. if (err != NULL) {
  347. return;
  348. }
  349. s->border = s->include_border ? geom->border_width : 0;
  350. s->width = geom->width;
  351. s->height = geom->height;
  352. // We don't have an alpha channel, but may have garbage in the texture.
  353. int32_t depth = geom->depth;
  354. if (depth != 32) {
  355. s->exclude_alpha = true;
  356. }
  357. xcb_window_t root = geom->root;
  358. free(geom);
  359. uint32_t vert_borders = s->crop_top + s->crop_bot + 2 * s->border;
  360. uint32_t hori_borders = s->crop_left + s->crop_right + 2 * s->border;
  361. // Skip 0 sized textures.
  362. if (vert_borders > s->height || hori_borders > s->width)
  363. return;
  364. s->pixmap = xcb_generate_id(conn);
  365. xcb_void_cookie_t name_cookie =
  366. xcb_composite_name_window_pixmap_checked(conn, s->win,
  367. s->pixmap);
  368. err = NULL;
  369. if ((err = xcb_request_check(conn, name_cookie)) != NULL) {
  370. blog(log_level, "xcb_composite_name_window_pixmap failed");
  371. s->pixmap = 0;
  372. return;
  373. }
  374. XErrorHandler prev = XSetErrorHandler(silence_x11_errors);
  375. s->gltex = gs_texture_create_from_pixmap(s->width, s->height,
  376. GS_BGRA_UNORM, GL_TEXTURE_2D,
  377. (void *)s->pixmap);
  378. XSetErrorHandler(prev);
  379. }
  380. struct reg_item {
  381. struct xcompcap *src;
  382. xcb_window_t win;
  383. };
  384. static DARRAY(struct reg_item) watcher_registry = {0};
  385. static pthread_mutex_t watcher_lock = PTHREAD_MUTEX_INITIALIZER;
  386. void watcher_register(xcb_connection_t *conn, struct xcompcap *s)
  387. {
  388. pthread_mutex_lock(&watcher_lock);
  389. if (xcomp_window_exists(conn, s->win)) {
  390. // Subscribe to Events
  391. uint32_t vals[1] = {StructureNotifyMask | ExposureMask |
  392. VisibilityChangeMask};
  393. xcb_change_window_attributes(conn, s->win, XCB_CW_EVENT_MASK,
  394. vals);
  395. xcb_composite_redirect_window(conn, s->win,
  396. XCB_COMPOSITE_REDIRECT_AUTOMATIC);
  397. da_push_back(watcher_registry, (&(struct reg_item){s, s->win}));
  398. }
  399. pthread_mutex_unlock(&watcher_lock);
  400. }
  401. void watcher_unregister(xcb_connection_t *conn, struct xcompcap *s)
  402. {
  403. pthread_mutex_lock(&watcher_lock);
  404. size_t idx = DARRAY_INVALID;
  405. xcb_window_t win = 0;
  406. for (size_t i = 0; i < watcher_registry.num; i++) {
  407. struct reg_item *item = (struct reg_item *)darray_item(
  408. sizeof(struct reg_item), &watcher_registry.da, i);
  409. if (item->src == s) {
  410. idx = i;
  411. win = item->win;
  412. break;
  413. }
  414. }
  415. if (idx == DARRAY_INVALID)
  416. goto done;
  417. da_erase(watcher_registry, idx);
  418. // Check if there are still sources listening for the same window.
  419. bool windowInUse = false;
  420. for (size_t i = 0; i < watcher_registry.num; i++) {
  421. struct reg_item *item = (struct reg_item *)darray_item(
  422. sizeof(struct reg_item), &watcher_registry.da, i);
  423. if (item->win == win) {
  424. windowInUse = true;
  425. break;
  426. }
  427. }
  428. if (!windowInUse && xcomp_window_exists(conn, s->win)) {
  429. // Last source released, stop listening for events.
  430. uint32_t vals[1] = {0};
  431. xcb_change_window_attributes(conn, win, XCB_CW_EVENT_MASK,
  432. vals);
  433. }
  434. done:
  435. pthread_mutex_unlock(&watcher_lock);
  436. }
  437. void watcher_process(xcb_generic_event_t *ev)
  438. {
  439. if (!ev)
  440. return;
  441. pthread_mutex_lock(&watcher_lock);
  442. xcb_window_t win = 0;
  443. switch (ev->response_type & ~0x80) {
  444. case XCB_CONFIGURE_NOTIFY:
  445. win = ((xcb_configure_notify_event_t *)ev)->event;
  446. break;
  447. case XCB_MAP_NOTIFY:
  448. win = ((xcb_map_notify_event_t *)ev)->event;
  449. break;
  450. case XCB_EXPOSE:
  451. win = ((xcb_expose_event_t *)ev)->window;
  452. break;
  453. case XCB_VISIBILITY_NOTIFY:
  454. win = ((xcb_visibility_notify_event_t *)ev)->window;
  455. break;
  456. case XCB_DESTROY_NOTIFY:
  457. win = ((xcb_destroy_notify_event_t *)ev)->event;
  458. break;
  459. };
  460. if (win != 0) {
  461. for (size_t i = 0; i < watcher_registry.num; i++) {
  462. struct reg_item *item = (struct reg_item *)darray_item(
  463. sizeof(struct reg_item), &watcher_registry.da,
  464. i);
  465. if (item->win == win) {
  466. item->src->window_changed = true;
  467. }
  468. }
  469. }
  470. pthread_mutex_unlock(&watcher_lock);
  471. }
  472. void watcher_unload()
  473. {
  474. da_free(watcher_registry);
  475. }
  476. static void xcompcap_get_hooked(void *data, calldata_t *cd)
  477. {
  478. struct xcompcap *s = data;
  479. if (!s)
  480. return;
  481. calldata_set_bool(cd, "hooked", s->window_hooked);
  482. if (s->window_hooked) {
  483. struct dstr wname = xcomp_window_name(conn, disp, s->win);
  484. struct dstr wcls = xcomp_window_class(conn, s->win);
  485. calldata_set_string(cd, "name", wname.array);
  486. calldata_set_string(cd, "class", wcls.array);
  487. dstr_free(&wname);
  488. dstr_free(&wcls);
  489. } else {
  490. calldata_set_string(cd, "name", "");
  491. calldata_set_string(cd, "class", "");
  492. }
  493. }
  494. static uint32_t xcompcap_get_width(void *data)
  495. {
  496. struct xcompcap *s = (struct xcompcap *)data;
  497. if (!s->gltex)
  498. return 0;
  499. int32_t border = s->crop_left + s->crop_right + 2 * s->border;
  500. int32_t width = s->width - border;
  501. return width < 0 ? 0 : width;
  502. }
  503. static uint32_t xcompcap_get_height(void *data)
  504. {
  505. struct xcompcap *s = (struct xcompcap *)data;
  506. if (!s->gltex)
  507. return 0;
  508. int32_t border = s->crop_bot + s->crop_top + 2 * s->border;
  509. int32_t height = s->height - border;
  510. return height < 0 ? 0 : height;
  511. }
  512. static void *xcompcap_create(obs_data_t *settings, obs_source_t *source)
  513. {
  514. struct xcompcap *s =
  515. (struct xcompcap *)bzalloc(sizeof(struct xcompcap));
  516. pthread_mutex_init(&s->lock, NULL);
  517. s->show_cursor = true;
  518. s->source = source;
  519. s->window_hooked = false;
  520. obs_enter_graphics();
  521. s->cursor = xcb_xcursor_init(conn);
  522. obs_leave_graphics();
  523. signal_handler_t *sh = obs_source_get_signal_handler(source);
  524. signal_handler_add(sh, "void unhooked(ptr source)");
  525. signal_handler_add(
  526. sh, "void hooked(ptr source, string name, string class)");
  527. proc_handler_t *ph = obs_source_get_proc_handler(source);
  528. proc_handler_add(
  529. ph,
  530. "void get_hooked(out bool hooked, out string name, out string class)",
  531. xcompcap_get_hooked, s);
  532. xcompcap_update(s, settings);
  533. return s;
  534. }
  535. static void xcompcap_destroy(void *data)
  536. {
  537. struct xcompcap *s = (struct xcompcap *)data;
  538. obs_enter_graphics();
  539. pthread_mutex_lock(&s->lock);
  540. watcher_unregister(conn, s);
  541. xcomp_cleanup_pixmap(disp, s);
  542. if (s->cursor)
  543. xcb_xcursor_destroy(s->cursor);
  544. pthread_mutex_unlock(&s->lock);
  545. obs_leave_graphics();
  546. pthread_mutex_destroy(&s->lock);
  547. bfree(s);
  548. }
  549. static void xcompcap_video_tick(void *data, float seconds)
  550. {
  551. struct xcompcap *s = (struct xcompcap *)data;
  552. if (!obs_source_showing(s->source))
  553. return;
  554. obs_enter_graphics();
  555. pthread_mutex_lock(&s->lock);
  556. xcb_generic_event_t *event;
  557. while ((event = xcb_poll_for_queued_event(conn)))
  558. watcher_process(event);
  559. // Send an unhooked signal if the window isn't found anymore
  560. if (s->window_hooked && !xcomp_window_exists(conn, s->win)) {
  561. s->window_hooked = false;
  562. signal_handler_t *sh = obs_source_get_signal_handler(s->source);
  563. calldata_t data = {0};
  564. calldata_set_ptr(&data, "source", s->source);
  565. signal_handler_signal(sh, "unhooked", &data);
  566. calldata_free(&data);
  567. }
  568. // Reacquire window after interval or immediately if reconfigured.
  569. s->window_check_time += seconds;
  570. bool window_lost = !xcomp_window_exists(conn, s->win) || !s->gltex;
  571. if ((window_lost && s->window_check_time > FIND_WINDOW_INTERVAL) ||
  572. s->window_changed) {
  573. watcher_unregister(conn, s);
  574. s->window_changed = false;
  575. s->window_check_time = 0.0;
  576. s->win = xcomp_find_window(conn, disp, s->windowName);
  577. // Send a hooked signal if a new window has been found
  578. if (!s->window_hooked && xcomp_window_exists(conn, s->win)) {
  579. s->window_hooked = true;
  580. signal_handler_t *sh =
  581. obs_source_get_signal_handler(s->source);
  582. calldata_t data = {0};
  583. calldata_set_ptr(&data, "source", s->source);
  584. struct dstr wname =
  585. xcomp_window_name(conn, disp, s->win);
  586. struct dstr wcls = xcomp_window_class(conn, s->win);
  587. calldata_set_string(&data, "name", wname.array);
  588. calldata_set_string(&data, "class", wcls.array);
  589. signal_handler_signal(sh, "hooked", &data);
  590. dstr_free(&wname);
  591. dstr_free(&wcls);
  592. calldata_free(&data);
  593. }
  594. watcher_register(conn, s);
  595. xcomp_cleanup_pixmap(disp, s);
  596. // Avoid excessive logging. We expect this to fail while windows are
  597. // minimized or on offscreen workspaces or already captured on NVIDIA.
  598. xcomp_create_pixmap(conn, s, LOG_DEBUG);
  599. xcb_xcursor_offset_win(conn, s->cursor, s->win);
  600. xcb_xcursor_offset(s->cursor, s->cursor->x_org + s->crop_left,
  601. s->cursor->y_org + s->crop_top);
  602. }
  603. if (!s->gltex)
  604. goto done;
  605. if (xcompcap_get_height(s) == 0 || xcompcap_get_width(s) == 0)
  606. goto done;
  607. if (s->show_cursor) {
  608. xcb_xcursor_update(conn, s->cursor);
  609. s->cursor_outside = s->cursor->x < 0 || s->cursor->y < 0 ||
  610. s->cursor->x > (int)xcompcap_get_width(s) ||
  611. s->cursor->y > (int)xcompcap_get_height(s);
  612. }
  613. done:
  614. pthread_mutex_unlock(&s->lock);
  615. obs_leave_graphics();
  616. }
  617. static void xcompcap_video_render(void *data, gs_effect_t *effect)
  618. {
  619. gs_eparam_t *image; // Placate C++ goto rules.
  620. struct xcompcap *s = (struct xcompcap *)data;
  621. pthread_mutex_lock(&s->lock);
  622. if (!s->gltex)
  623. goto done;
  624. effect = obs_get_base_effect(OBS_EFFECT_DEFAULT);
  625. if (s->exclude_alpha)
  626. effect = obs_get_base_effect(OBS_EFFECT_OPAQUE);
  627. image = gs_effect_get_param_by_name(effect, "image");
  628. gs_effect_set_texture(image, s->gltex);
  629. while (gs_effect_loop(effect, "Draw")) {
  630. gs_draw_sprite_subregion(s->gltex, 0, s->crop_left, s->crop_top,
  631. xcompcap_get_width(s),
  632. xcompcap_get_height(s));
  633. }
  634. if (s->gltex && s->show_cursor && !s->cursor_outside) {
  635. effect = obs_get_base_effect(OBS_EFFECT_DEFAULT);
  636. while (gs_effect_loop(effect, "Draw")) {
  637. xcb_xcursor_render(s->cursor);
  638. }
  639. }
  640. done:
  641. pthread_mutex_unlock(&s->lock);
  642. }
  643. struct WindowInfo {
  644. struct dstr name_lower;
  645. struct dstr name;
  646. struct dstr desc;
  647. };
  648. static int cmp_wi(const void *a, const void *b)
  649. {
  650. struct WindowInfo *awi = (struct WindowInfo *)a;
  651. struct WindowInfo *bwi = (struct WindowInfo *)b;
  652. return strcmp(awi->name_lower.array, bwi->name_lower.array);
  653. }
  654. static obs_properties_t *xcompcap_props(void *unused)
  655. {
  656. UNUSED_PARAMETER(unused);
  657. obs_properties_t *props = obs_properties_create();
  658. obs_property_t *prop;
  659. prop = obs_properties_add_list(props, "capture_window",
  660. obs_module_text("Window"),
  661. OBS_COMBO_TYPE_LIST,
  662. OBS_COMBO_FORMAT_STRING);
  663. DARRAY(struct WindowInfo) window_strings = {0};
  664. struct darray windows = xcomp_top_level_windows(conn);
  665. for (size_t w = 0; w < windows.num; w++) {
  666. xcb_window_t win = *(xcb_window_t *)darray_item(
  667. sizeof(xcb_window_t), &windows, w);
  668. struct dstr name = xcomp_window_name(conn, disp, win);
  669. struct dstr cls = xcomp_window_class(conn, win);
  670. struct dstr desc = {0};
  671. dstr_printf(&desc, "%d" WIN_STRING_DIV "%s" WIN_STRING_DIV "%s",
  672. win, name.array, cls.array);
  673. dstr_free(&cls);
  674. struct dstr name_lower;
  675. dstr_init_copy_dstr(&name_lower, &name);
  676. dstr_to_lower(&name_lower);
  677. da_push_back(window_strings,
  678. (&(struct WindowInfo){name_lower, name, desc}));
  679. }
  680. darray_free(&windows);
  681. qsort(window_strings.array, window_strings.num,
  682. sizeof(struct WindowInfo), cmp_wi);
  683. for (size_t i = 0; i < window_strings.num; i++) {
  684. struct WindowInfo *s = (struct WindowInfo *)darray_item(
  685. sizeof(struct WindowInfo), &window_strings.da, i);
  686. obs_property_list_add_string(prop, s->name.array,
  687. s->desc.array);
  688. dstr_free(&s->name_lower);
  689. dstr_free(&s->name);
  690. dstr_free(&s->desc);
  691. }
  692. da_free(window_strings);
  693. prop = obs_properties_add_int(props, "cut_top",
  694. obs_module_text("CropTop"), 0, 4096, 1);
  695. obs_property_int_set_suffix(prop, " px");
  696. prop = obs_properties_add_int(props, "cut_left",
  697. obs_module_text("CropLeft"), 0, 4096, 1);
  698. obs_property_int_set_suffix(prop, " px");
  699. prop = obs_properties_add_int(props, "cut_right",
  700. obs_module_text("CropRight"), 0, 4096, 1);
  701. obs_property_int_set_suffix(prop, " px");
  702. prop = obs_properties_add_int(
  703. props, "cut_bot", obs_module_text("CropBottom"), 0, 4096, 1);
  704. obs_property_int_set_suffix(prop, " px");
  705. obs_properties_add_bool(props, "show_cursor",
  706. obs_module_text("CaptureCursor"));
  707. obs_properties_add_bool(props, "include_border",
  708. obs_module_text("IncludeXBorder"));
  709. obs_properties_add_bool(props, "exclude_alpha",
  710. obs_module_text("ExcludeAlpha"));
  711. return props;
  712. }
  713. static void xcompcap_defaults(obs_data_t *settings)
  714. {
  715. obs_data_set_default_string(settings, "capture_window", "");
  716. obs_data_set_default_int(settings, "cut_top", 0);
  717. obs_data_set_default_int(settings, "cut_left", 0);
  718. obs_data_set_default_int(settings, "cut_right", 0);
  719. obs_data_set_default_int(settings, "cut_bot", 0);
  720. obs_data_set_default_bool(settings, "show_cursor", true);
  721. obs_data_set_default_bool(settings, "include_border", false);
  722. obs_data_set_default_bool(settings, "exclude_alpha", false);
  723. }
  724. static void xcompcap_update(void *data, obs_data_t *settings)
  725. {
  726. struct xcompcap *s = (struct xcompcap *)data;
  727. obs_enter_graphics();
  728. pthread_mutex_lock(&s->lock);
  729. char *prev_name = bstrdup(s->windowName);
  730. s->crop_top = obs_data_get_int(settings, "cut_top");
  731. s->crop_left = obs_data_get_int(settings, "cut_left");
  732. s->crop_right = obs_data_get_int(settings, "cut_right");
  733. s->crop_bot = obs_data_get_int(settings, "cut_bot");
  734. s->show_cursor = obs_data_get_bool(settings, "show_cursor");
  735. s->include_border = obs_data_get_bool(settings, "include_border");
  736. s->exclude_alpha = obs_data_get_bool(settings, "exclude_alpha");
  737. s->windowName = obs_data_get_string(settings, "capture_window");
  738. if (s->window_hooked && strcmp(prev_name, s->windowName) != 0) {
  739. s->window_hooked = false;
  740. signal_handler_t *sh = obs_source_get_signal_handler(s->source);
  741. calldata_t data = {0};
  742. calldata_set_ptr(&data, "source", s->source);
  743. signal_handler_signal(sh, "unhooked", &data);
  744. calldata_free(&data);
  745. }
  746. bfree(prev_name);
  747. s->win = xcomp_find_window(conn, disp, s->windowName);
  748. if (!s->window_hooked && xcomp_window_exists(conn, s->win)) {
  749. s->window_hooked = true;
  750. signal_handler_t *sh = obs_source_get_signal_handler(s->source);
  751. calldata_t data = {0};
  752. calldata_set_ptr(&data, "source", s->source);
  753. struct dstr wname = xcomp_window_name(conn, disp, s->win);
  754. struct dstr wcls = xcomp_window_class(conn, s->win);
  755. calldata_set_string(&data, "name", wname.array);
  756. calldata_set_string(&data, "class", wcls.array);
  757. signal_handler_signal(sh, "hooked", &data);
  758. dstr_free(&wname);
  759. dstr_free(&wcls);
  760. calldata_free(&data);
  761. }
  762. if (s->win && s->windowName) {
  763. struct dstr wname = xcomp_window_name(conn, disp, s->win);
  764. struct dstr wcls = xcomp_window_class(conn, s->win);
  765. blog(LOG_INFO,
  766. "[window-capture: '%s'] update settings:\n"
  767. "\ttitle: %s\n"
  768. "\tclass: %s\n",
  769. obs_source_get_name(s->source), wname.array, wcls.array);
  770. dstr_free(&wname);
  771. dstr_free(&wcls);
  772. }
  773. watcher_register(conn, s);
  774. xcomp_cleanup_pixmap(disp, s);
  775. xcomp_create_pixmap(conn, s, LOG_ERROR);
  776. xcb_xcursor_offset_win(conn, s->cursor, s->win);
  777. xcb_xcursor_offset(s->cursor, s->cursor->x_org + s->crop_left,
  778. s->cursor->y_org + s->crop_top);
  779. pthread_mutex_unlock(&s->lock);
  780. obs_leave_graphics();
  781. }
  782. static const char *xcompcap_getname(void *data)
  783. {
  784. UNUSED_PARAMETER(data);
  785. return obs_module_text("XCCapture");
  786. }
  787. void xcomposite_load(void)
  788. {
  789. disp = XOpenDisplay(NULL);
  790. conn = XGetXCBConnection(disp);
  791. if (xcb_connection_has_error(conn)) {
  792. blog(LOG_ERROR, "failed opening display");
  793. return;
  794. }
  795. const xcb_query_extension_reply_t *xcomp_ext =
  796. xcb_get_extension_data(conn, &xcb_composite_id);
  797. if (!xcomp_ext->present) {
  798. blog(LOG_ERROR, "Xcomposite extension not supported");
  799. return;
  800. }
  801. xcb_composite_query_version_cookie_t version_cookie =
  802. xcb_composite_query_version(conn, 0, 2);
  803. xcb_composite_query_version_reply_t *version =
  804. xcb_composite_query_version_reply(conn, version_cookie, NULL);
  805. if (version->major_version == 0 && version->minor_version < 2) {
  806. blog(LOG_ERROR, "Xcomposite extension is too old: %d.%d < 0.2",
  807. version->major_version, version->minor_version);
  808. free(version);
  809. return;
  810. }
  811. free(version);
  812. // Must be done before other helpers called.
  813. xcomp_gather_atoms(conn);
  814. xcb_screen_t *screen_default =
  815. xcb_get_screen(conn, DefaultScreen(disp));
  816. if (!screen_default || !xcomp_check_ewmh(conn, screen_default->root)) {
  817. blog(LOG_ERROR,
  818. "window manager does not support Extended Window Manager Hints (EWMH).\nXComposite capture disabled.");
  819. return;
  820. }
  821. struct obs_source_info sinfo = {
  822. .id = "xcomposite_input",
  823. .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW |
  824. OBS_SOURCE_DO_NOT_DUPLICATE,
  825. .get_name = xcompcap_getname,
  826. .create = xcompcap_create,
  827. .destroy = xcompcap_destroy,
  828. .get_properties = xcompcap_props,
  829. .get_defaults = xcompcap_defaults,
  830. .update = xcompcap_update,
  831. .video_tick = xcompcap_video_tick,
  832. .video_render = xcompcap_video_render,
  833. .get_width = xcompcap_get_width,
  834. .get_height = xcompcap_get_height,
  835. .icon_type = OBS_ICON_TYPE_WINDOW_CAPTURE,
  836. };
  837. obs_register_source(&sinfo);
  838. }
  839. void xcomposite_unload(void)
  840. {
  841. XCloseDisplay(disp);
  842. disp = NULL;
  843. conn = NULL;
  844. watcher_unload();
  845. }