1
0

xcomposite-input.c 27 KB

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