game-capture.c 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259
  1. #include <inttypes.h>
  2. #include <obs-module.h>
  3. #include <obs-hotkey.h>
  4. #include <util/platform.h>
  5. #include <util/threading.h>
  6. #include <windows.h>
  7. #include <dxgi.h>
  8. #include <util/sse-intrin.h>
  9. #include <util/util_uint64.h>
  10. #include <ipc-util/pipe.h>
  11. #include "obfuscate.h"
  12. #include "inject-library.h"
  13. #include "graphics-hook-info.h"
  14. #include "graphics-hook-ver.h"
  15. #include "window-helpers.h"
  16. #include "cursor-capture.h"
  17. #include "app-helpers.h"
  18. #include "nt-stuff.h"
  19. #define do_log(level, format, ...) \
  20. blog(level, "[game-capture: '%s'] " format, \
  21. obs_source_get_name(gc->source), ##__VA_ARGS__)
  22. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  23. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  24. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  25. /* clang-format off */
  26. #define SETTING_MODE "capture_mode"
  27. #define SETTING_CAPTURE_WINDOW "window"
  28. #define SETTING_ACTIVE_WINDOW "active_window"
  29. #define SETTING_WINDOW_PRIORITY "priority"
  30. #define SETTING_COMPATIBILITY "sli_compatibility"
  31. #define SETTING_CURSOR "capture_cursor"
  32. #define SETTING_TRANSPARENCY "allow_transparency"
  33. #define SETTING_LIMIT_FRAMERATE "limit_framerate"
  34. #define SETTING_CAPTURE_OVERLAYS "capture_overlays"
  35. #define SETTING_ANTI_CHEAT_HOOK "anti_cheat_hook"
  36. #define SETTING_HOOK_RATE "hook_rate"
  37. /* deprecated */
  38. #define SETTING_ANY_FULLSCREEN "capture_any_fullscreen"
  39. #define SETTING_MODE_ANY "any_fullscreen"
  40. #define SETTING_MODE_WINDOW "window"
  41. #define SETTING_MODE_HOTKEY "hotkey"
  42. #define HOTKEY_START "hotkey_start"
  43. #define HOTKEY_STOP "hotkey_stop"
  44. #define TEXT_MODE obs_module_text("Mode")
  45. #define TEXT_GAME_CAPTURE obs_module_text("GameCapture")
  46. #define TEXT_ANY_FULLSCREEN obs_module_text("GameCapture.AnyFullscreen")
  47. #define TEXT_SLI_COMPATIBILITY obs_module_text("SLIFix")
  48. #define TEXT_ALLOW_TRANSPARENCY obs_module_text("AllowTransparency")
  49. #define TEXT_WINDOW obs_module_text("WindowCapture.Window")
  50. #define TEXT_MATCH_PRIORITY obs_module_text("WindowCapture.Priority")
  51. #define TEXT_MATCH_TITLE obs_module_text("WindowCapture.Priority.Title")
  52. #define TEXT_MATCH_CLASS obs_module_text("WindowCapture.Priority.Class")
  53. #define TEXT_MATCH_EXE obs_module_text("WindowCapture.Priority.Exe")
  54. #define TEXT_CAPTURE_CURSOR obs_module_text("CaptureCursor")
  55. #define TEXT_LIMIT_FRAMERATE obs_module_text("GameCapture.LimitFramerate")
  56. #define TEXT_CAPTURE_OVERLAYS obs_module_text("GameCapture.CaptureOverlays")
  57. #define TEXT_ANTI_CHEAT_HOOK obs_module_text("GameCapture.AntiCheatHook")
  58. #define TEXT_HOOK_RATE obs_module_text("GameCapture.HookRate")
  59. #define TEXT_HOOK_RATE_SLOW obs_module_text("GameCapture.HookRate.Slow")
  60. #define TEXT_HOOK_RATE_NORMAL obs_module_text("GameCapture.HookRate.Normal")
  61. #define TEXT_HOOK_RATE_FAST obs_module_text("GameCapture.HookRate.Fast")
  62. #define TEXT_HOOK_RATE_FASTEST obs_module_text("GameCapture.HookRate.Fastest")
  63. #define TEXT_MODE_ANY TEXT_ANY_FULLSCREEN
  64. #define TEXT_MODE_WINDOW obs_module_text("GameCapture.CaptureWindow")
  65. #define TEXT_MODE_HOTKEY obs_module_text("GameCapture.UseHotkey")
  66. #define TEXT_HOTKEY_START obs_module_text("GameCapture.HotkeyStart")
  67. #define TEXT_HOTKEY_STOP obs_module_text("GameCapture.HotkeyStop")
  68. /* clang-format on */
  69. #define DEFAULT_RETRY_INTERVAL 2.0f
  70. #define ERROR_RETRY_INTERVAL 4.0f
  71. enum capture_mode {
  72. CAPTURE_MODE_ANY,
  73. CAPTURE_MODE_WINDOW,
  74. CAPTURE_MODE_HOTKEY
  75. };
  76. enum hook_rate {
  77. HOOK_RATE_SLOW,
  78. HOOK_RATE_NORMAL,
  79. HOOK_RATE_FAST,
  80. HOOK_RATE_FASTEST
  81. };
  82. struct game_capture_config {
  83. char *title;
  84. char *class;
  85. char *executable;
  86. enum window_priority priority;
  87. enum capture_mode mode;
  88. bool cursor;
  89. bool force_shmem;
  90. bool allow_transparency;
  91. bool limit_framerate;
  92. bool capture_overlays;
  93. bool anticheat_hook;
  94. enum hook_rate hook_rate;
  95. };
  96. typedef DPI_AWARENESS_CONTEXT(WINAPI *PFN_SetThreadDpiAwarenessContext)(
  97. DPI_AWARENESS_CONTEXT);
  98. typedef DPI_AWARENESS_CONTEXT(WINAPI *PFN_GetThreadDpiAwarenessContext)(VOID);
  99. typedef DPI_AWARENESS_CONTEXT(WINAPI *PFN_GetWindowDpiAwarenessContext)(HWND);
  100. struct game_capture {
  101. obs_source_t *source;
  102. struct cursor_data cursor_data;
  103. HANDLE injector_process;
  104. uint32_t cx;
  105. uint32_t cy;
  106. uint32_t pitch;
  107. DWORD process_id;
  108. DWORD thread_id;
  109. HWND next_window;
  110. HWND window;
  111. float retry_time;
  112. float fps_reset_time;
  113. float retry_interval;
  114. struct dstr title;
  115. struct dstr class;
  116. struct dstr executable;
  117. enum window_priority priority;
  118. obs_hotkey_pair_id hotkey_pair;
  119. volatile long hotkey_window;
  120. volatile bool deactivate_hook;
  121. volatile bool activate_hook_now;
  122. bool wait_for_target_startup;
  123. bool showing;
  124. bool active;
  125. bool capturing;
  126. bool activate_hook;
  127. bool process_is_64bit;
  128. bool error_acquiring;
  129. bool dwm_capture;
  130. bool initial_config;
  131. bool convert_16bit;
  132. bool is_app;
  133. bool cursor_hidden;
  134. struct game_capture_config config;
  135. ipc_pipe_server_t pipe;
  136. gs_texture_t *texture;
  137. gs_texture_t *extra_texture;
  138. gs_texrender_t *extra_texrender;
  139. bool linear_sample;
  140. struct hook_info *global_hook_info;
  141. HANDLE keepalive_mutex;
  142. HANDLE hook_init;
  143. HANDLE hook_restart;
  144. HANDLE hook_stop;
  145. HANDLE hook_ready;
  146. HANDLE hook_exit;
  147. HANDLE hook_data_map;
  148. HANDLE global_hook_info_map;
  149. HANDLE target_process;
  150. HANDLE texture_mutexes[2];
  151. wchar_t *app_sid;
  152. int retrying;
  153. float cursor_check_time;
  154. union {
  155. struct {
  156. struct shmem_data *shmem_data;
  157. uint8_t *texture_buffers[2];
  158. };
  159. struct shtex_data *shtex_data;
  160. void *data;
  161. };
  162. void (*copy_texture)(struct game_capture *);
  163. PFN_SetThreadDpiAwarenessContext set_thread_dpi_awareness_context;
  164. PFN_GetThreadDpiAwarenessContext get_thread_dpi_awareness_context;
  165. PFN_GetWindowDpiAwarenessContext get_window_dpi_awareness_context;
  166. };
  167. struct graphics_offsets offsets32 = {0};
  168. struct graphics_offsets offsets64 = {0};
  169. static inline bool use_anticheat(struct game_capture *gc)
  170. {
  171. return gc->config.anticheat_hook && !gc->is_app;
  172. }
  173. static inline HANDLE open_mutex_plus_id(struct game_capture *gc,
  174. const wchar_t *name, DWORD id)
  175. {
  176. wchar_t new_name[64];
  177. _snwprintf(new_name, 64, L"%s%lu", name, id);
  178. return gc->is_app ? open_app_mutex(gc->app_sid, new_name)
  179. : open_mutex(new_name);
  180. }
  181. static inline HANDLE open_mutex_gc(struct game_capture *gc, const wchar_t *name)
  182. {
  183. return open_mutex_plus_id(gc, name, gc->process_id);
  184. }
  185. static inline HANDLE open_event_plus_id(struct game_capture *gc,
  186. const wchar_t *name, DWORD id)
  187. {
  188. wchar_t new_name[64];
  189. _snwprintf(new_name, 64, L"%s%lu", name, id);
  190. return gc->is_app ? open_app_event(gc->app_sid, new_name)
  191. : open_event(new_name);
  192. }
  193. static inline HANDLE open_event_gc(struct game_capture *gc, const wchar_t *name)
  194. {
  195. return open_event_plus_id(gc, name, gc->process_id);
  196. }
  197. static inline HANDLE open_map_plus_id(struct game_capture *gc,
  198. const wchar_t *name, DWORD id)
  199. {
  200. wchar_t new_name[64];
  201. swprintf(new_name, 64, L"%s%lu", name, id);
  202. debug("map id: %S", new_name);
  203. return gc->is_app ? open_app_map(gc->app_sid, new_name)
  204. : OpenFileMappingW(GC_MAPPING_FLAGS, false, new_name);
  205. }
  206. static inline HANDLE open_hook_info(struct game_capture *gc)
  207. {
  208. return open_map_plus_id(gc, SHMEM_HOOK_INFO, gc->process_id);
  209. }
  210. static inline enum gs_color_format convert_format(uint32_t format)
  211. {
  212. switch (format) {
  213. case DXGI_FORMAT_R8G8B8A8_UNORM:
  214. return GS_RGBA;
  215. case DXGI_FORMAT_B8G8R8X8_UNORM:
  216. return GS_BGRX;
  217. case DXGI_FORMAT_B8G8R8A8_UNORM:
  218. return GS_BGRA;
  219. case DXGI_FORMAT_R10G10B10A2_UNORM:
  220. return GS_R10G10B10A2;
  221. case DXGI_FORMAT_R16G16B16A16_UNORM:
  222. return GS_RGBA16;
  223. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  224. return GS_RGBA16F;
  225. case DXGI_FORMAT_R32G32B32A32_FLOAT:
  226. return GS_RGBA32F;
  227. }
  228. return GS_UNKNOWN;
  229. }
  230. static void close_handle(HANDLE *p_handle)
  231. {
  232. HANDLE handle = *p_handle;
  233. if (handle) {
  234. if (handle != INVALID_HANDLE_VALUE)
  235. CloseHandle(handle);
  236. *p_handle = NULL;
  237. }
  238. }
  239. static inline HMODULE kernel32(void)
  240. {
  241. static HMODULE kernel32_handle = NULL;
  242. if (!kernel32_handle)
  243. kernel32_handle = GetModuleHandleW(L"kernel32");
  244. return kernel32_handle;
  245. }
  246. static inline HANDLE open_process(DWORD desired_access, bool inherit_handle,
  247. DWORD process_id)
  248. {
  249. typedef HANDLE(WINAPI * PFN_OpenProcess)(DWORD, BOOL, DWORD);
  250. PFN_OpenProcess open_process_proc = NULL;
  251. if (!open_process_proc)
  252. open_process_proc = (PFN_OpenProcess)get_obfuscated_func(
  253. kernel32(), "NuagUykjcxr", 0x1B694B59451ULL);
  254. return open_process_proc(desired_access, inherit_handle, process_id);
  255. }
  256. static inline float hook_rate_to_float(enum hook_rate rate)
  257. {
  258. switch (rate) {
  259. case HOOK_RATE_SLOW:
  260. return 2.0f;
  261. case HOOK_RATE_FAST:
  262. return 0.5f;
  263. case HOOK_RATE_FASTEST:
  264. return 0.1f;
  265. case HOOK_RATE_NORMAL:
  266. /* FALLTHROUGH */
  267. default:
  268. return 1.0f;
  269. }
  270. }
  271. static void stop_capture(struct game_capture *gc)
  272. {
  273. ipc_pipe_server_free(&gc->pipe);
  274. if (gc->hook_stop) {
  275. SetEvent(gc->hook_stop);
  276. }
  277. if (gc->global_hook_info) {
  278. UnmapViewOfFile(gc->global_hook_info);
  279. gc->global_hook_info = NULL;
  280. }
  281. if (gc->data) {
  282. UnmapViewOfFile(gc->data);
  283. gc->data = NULL;
  284. }
  285. if (gc->app_sid) {
  286. LocalFree(gc->app_sid);
  287. gc->app_sid = NULL;
  288. }
  289. close_handle(&gc->hook_restart);
  290. close_handle(&gc->hook_stop);
  291. close_handle(&gc->hook_ready);
  292. close_handle(&gc->hook_exit);
  293. close_handle(&gc->hook_init);
  294. close_handle(&gc->hook_data_map);
  295. close_handle(&gc->keepalive_mutex);
  296. close_handle(&gc->global_hook_info_map);
  297. close_handle(&gc->target_process);
  298. close_handle(&gc->texture_mutexes[0]);
  299. close_handle(&gc->texture_mutexes[1]);
  300. obs_enter_graphics();
  301. gs_texrender_destroy(gc->extra_texrender);
  302. gc->extra_texrender = NULL;
  303. gs_texture_destroy(gc->extra_texture);
  304. gc->extra_texture = NULL;
  305. gs_texture_destroy(gc->texture);
  306. gc->texture = NULL;
  307. obs_leave_graphics();
  308. if (gc->active)
  309. info("capture stopped");
  310. gc->copy_texture = NULL;
  311. gc->wait_for_target_startup = false;
  312. gc->active = false;
  313. gc->capturing = false;
  314. if (gc->retrying)
  315. gc->retrying--;
  316. }
  317. static inline void free_config(struct game_capture_config *config)
  318. {
  319. bfree(config->title);
  320. bfree(config->class);
  321. bfree(config->executable);
  322. memset(config, 0, sizeof(*config));
  323. }
  324. static void game_capture_destroy(void *data)
  325. {
  326. struct game_capture *gc = data;
  327. stop_capture(gc);
  328. if (gc->hotkey_pair)
  329. obs_hotkey_pair_unregister(gc->hotkey_pair);
  330. obs_enter_graphics();
  331. cursor_data_free(&gc->cursor_data);
  332. obs_leave_graphics();
  333. dstr_free(&gc->title);
  334. dstr_free(&gc->class);
  335. dstr_free(&gc->executable);
  336. free_config(&gc->config);
  337. bfree(gc);
  338. }
  339. static inline bool using_older_non_mode_format(obs_data_t *settings)
  340. {
  341. return obs_data_has_user_value(settings, SETTING_ANY_FULLSCREEN) &&
  342. !obs_data_has_user_value(settings, SETTING_MODE);
  343. }
  344. static inline void get_config(struct game_capture_config *cfg,
  345. obs_data_t *settings, const char *window)
  346. {
  347. const char *mode_str = NULL;
  348. build_window_strings(window, &cfg->class, &cfg->title,
  349. &cfg->executable);
  350. if (using_older_non_mode_format(settings)) {
  351. bool any = obs_data_get_bool(settings, SETTING_ANY_FULLSCREEN);
  352. mode_str = any ? SETTING_MODE_ANY : SETTING_MODE_WINDOW;
  353. } else {
  354. mode_str = obs_data_get_string(settings, SETTING_MODE);
  355. }
  356. if (mode_str && strcmp(mode_str, SETTING_MODE_WINDOW) == 0)
  357. cfg->mode = CAPTURE_MODE_WINDOW;
  358. else if (mode_str && strcmp(mode_str, SETTING_MODE_HOTKEY) == 0)
  359. cfg->mode = CAPTURE_MODE_HOTKEY;
  360. else
  361. cfg->mode = CAPTURE_MODE_ANY;
  362. cfg->priority = (enum window_priority)obs_data_get_int(
  363. settings, SETTING_WINDOW_PRIORITY);
  364. cfg->force_shmem = obs_data_get_bool(settings, SETTING_COMPATIBILITY);
  365. cfg->cursor = obs_data_get_bool(settings, SETTING_CURSOR);
  366. cfg->allow_transparency =
  367. obs_data_get_bool(settings, SETTING_TRANSPARENCY);
  368. cfg->limit_framerate =
  369. obs_data_get_bool(settings, SETTING_LIMIT_FRAMERATE);
  370. cfg->capture_overlays =
  371. obs_data_get_bool(settings, SETTING_CAPTURE_OVERLAYS);
  372. cfg->anticheat_hook =
  373. obs_data_get_bool(settings, SETTING_ANTI_CHEAT_HOOK);
  374. cfg->hook_rate =
  375. (enum hook_rate)obs_data_get_int(settings, SETTING_HOOK_RATE);
  376. }
  377. static inline int s_cmp(const char *str1, const char *str2)
  378. {
  379. if (!str1 || !str2)
  380. return -1;
  381. return strcmp(str1, str2);
  382. }
  383. static inline bool capture_needs_reset(struct game_capture_config *cfg1,
  384. struct game_capture_config *cfg2)
  385. {
  386. if (cfg1->mode != cfg2->mode) {
  387. return true;
  388. } else if (cfg1->mode == CAPTURE_MODE_WINDOW &&
  389. (s_cmp(cfg1->class, cfg2->class) != 0 ||
  390. s_cmp(cfg1->title, cfg2->title) != 0 ||
  391. s_cmp(cfg1->executable, cfg2->executable) != 0 ||
  392. cfg1->priority != cfg2->priority)) {
  393. return true;
  394. } else if (cfg1->force_shmem != cfg2->force_shmem) {
  395. return true;
  396. } else if (cfg1->limit_framerate != cfg2->limit_framerate) {
  397. return true;
  398. } else if (cfg1->capture_overlays != cfg2->capture_overlays) {
  399. return true;
  400. }
  401. return false;
  402. }
  403. static bool hotkey_start(void *data, obs_hotkey_pair_id id,
  404. obs_hotkey_t *hotkey, bool pressed)
  405. {
  406. UNUSED_PARAMETER(id);
  407. UNUSED_PARAMETER(hotkey);
  408. struct game_capture *gc = data;
  409. if (pressed && gc->config.mode == CAPTURE_MODE_HOTKEY) {
  410. info("Activate hotkey pressed");
  411. os_atomic_set_long(&gc->hotkey_window,
  412. (long)(uintptr_t)GetForegroundWindow());
  413. os_atomic_set_bool(&gc->deactivate_hook, true);
  414. os_atomic_set_bool(&gc->activate_hook_now, true);
  415. }
  416. return true;
  417. }
  418. static bool hotkey_stop(void *data, obs_hotkey_pair_id id, obs_hotkey_t *hotkey,
  419. bool pressed)
  420. {
  421. UNUSED_PARAMETER(id);
  422. UNUSED_PARAMETER(hotkey);
  423. struct game_capture *gc = data;
  424. if (pressed && gc->config.mode == CAPTURE_MODE_HOTKEY) {
  425. info("Deactivate hotkey pressed");
  426. os_atomic_set_bool(&gc->deactivate_hook, true);
  427. }
  428. return true;
  429. }
  430. static void game_capture_update(void *data, obs_data_t *settings)
  431. {
  432. struct game_capture *gc = data;
  433. struct game_capture_config cfg;
  434. bool reset_capture = false;
  435. const char *window =
  436. obs_data_get_string(settings, SETTING_CAPTURE_WINDOW);
  437. get_config(&cfg, settings, window);
  438. reset_capture = capture_needs_reset(&cfg, &gc->config);
  439. gc->error_acquiring = false;
  440. if (cfg.mode == CAPTURE_MODE_HOTKEY &&
  441. gc->config.mode != CAPTURE_MODE_HOTKEY) {
  442. gc->activate_hook = false;
  443. } else {
  444. gc->activate_hook = !!window && !!*window;
  445. }
  446. free_config(&gc->config);
  447. gc->config = cfg;
  448. gc->retry_interval = DEFAULT_RETRY_INTERVAL *
  449. hook_rate_to_float(gc->config.hook_rate);
  450. gc->wait_for_target_startup = false;
  451. dstr_free(&gc->title);
  452. dstr_free(&gc->class);
  453. dstr_free(&gc->executable);
  454. if (cfg.mode == CAPTURE_MODE_WINDOW) {
  455. dstr_copy(&gc->title, gc->config.title);
  456. dstr_copy(&gc->class, gc->config.class);
  457. dstr_copy(&gc->executable, gc->config.executable);
  458. gc->priority = gc->config.priority;
  459. }
  460. if (!gc->initial_config) {
  461. if (reset_capture) {
  462. stop_capture(gc);
  463. }
  464. } else {
  465. gc->initial_config = false;
  466. }
  467. }
  468. extern void wait_for_hook_initialization(void);
  469. static void *game_capture_create(obs_data_t *settings, obs_source_t *source)
  470. {
  471. struct game_capture *gc = bzalloc(sizeof(*gc));
  472. wait_for_hook_initialization();
  473. gc->source = source;
  474. gc->initial_config = true;
  475. gc->retry_interval = DEFAULT_RETRY_INTERVAL *
  476. hook_rate_to_float(gc->config.hook_rate);
  477. gc->hotkey_pair = obs_hotkey_pair_register_source(
  478. gc->source, HOTKEY_START, TEXT_HOTKEY_START, HOTKEY_STOP,
  479. TEXT_HOTKEY_STOP, hotkey_start, hotkey_stop, gc, gc);
  480. const HMODULE hModuleUser32 = GetModuleHandle(L"User32.dll");
  481. if (hModuleUser32) {
  482. PFN_SetThreadDpiAwarenessContext
  483. set_thread_dpi_awareness_context =
  484. (PFN_SetThreadDpiAwarenessContext)GetProcAddress(
  485. hModuleUser32,
  486. "SetThreadDpiAwarenessContext");
  487. PFN_GetThreadDpiAwarenessContext
  488. get_thread_dpi_awareness_context =
  489. (PFN_GetThreadDpiAwarenessContext)GetProcAddress(
  490. hModuleUser32,
  491. "GetThreadDpiAwarenessContext");
  492. PFN_GetWindowDpiAwarenessContext
  493. get_window_dpi_awareness_context =
  494. (PFN_GetWindowDpiAwarenessContext)GetProcAddress(
  495. hModuleUser32,
  496. "GetWindowDpiAwarenessContext");
  497. if (set_thread_dpi_awareness_context &&
  498. get_thread_dpi_awareness_context &&
  499. get_window_dpi_awareness_context) {
  500. gc->set_thread_dpi_awareness_context =
  501. set_thread_dpi_awareness_context;
  502. gc->get_thread_dpi_awareness_context =
  503. get_thread_dpi_awareness_context;
  504. gc->get_window_dpi_awareness_context =
  505. get_window_dpi_awareness_context;
  506. }
  507. }
  508. game_capture_update(gc, settings);
  509. return gc;
  510. }
  511. #define STOP_BEING_BAD \
  512. " This is most likely due to security software. Please make sure " \
  513. "that the OBS installation folder is excluded/ignored in the " \
  514. "settings of the security software you are using."
  515. static bool check_file_integrity(struct game_capture *gc, const char *file,
  516. const char *name)
  517. {
  518. DWORD error;
  519. HANDLE handle;
  520. wchar_t *w_file = NULL;
  521. if (!file || !*file) {
  522. warn("Game capture %s not found." STOP_BEING_BAD, name);
  523. return false;
  524. }
  525. if (!os_utf8_to_wcs_ptr(file, 0, &w_file)) {
  526. warn("Could not convert file name to wide string");
  527. return false;
  528. }
  529. handle = CreateFileW(w_file, GENERIC_READ | GENERIC_EXECUTE,
  530. FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
  531. bfree(w_file);
  532. if (handle != INVALID_HANDLE_VALUE) {
  533. CloseHandle(handle);
  534. return true;
  535. }
  536. error = GetLastError();
  537. if (error == ERROR_FILE_NOT_FOUND) {
  538. warn("Game capture file '%s' not found." STOP_BEING_BAD, file);
  539. } else if (error == ERROR_ACCESS_DENIED) {
  540. warn("Game capture file '%s' could not be loaded." STOP_BEING_BAD,
  541. file);
  542. } else {
  543. warn("Game capture file '%s' could not be loaded: %lu." STOP_BEING_BAD,
  544. file, error);
  545. }
  546. return false;
  547. }
  548. static inline bool is_64bit_windows(void)
  549. {
  550. #ifdef _WIN64
  551. return true;
  552. #else
  553. BOOL x86 = false;
  554. bool success = !!IsWow64Process(GetCurrentProcess(), &x86);
  555. return success && !!x86;
  556. #endif
  557. }
  558. static inline bool is_64bit_process(HANDLE process)
  559. {
  560. BOOL x86 = true;
  561. if (is_64bit_windows()) {
  562. bool success = !!IsWow64Process(process, &x86);
  563. if (!success) {
  564. return false;
  565. }
  566. }
  567. return !x86;
  568. }
  569. static inline bool open_target_process(struct game_capture *gc)
  570. {
  571. gc->target_process = open_process(
  572. PROCESS_QUERY_INFORMATION | SYNCHRONIZE, false, gc->process_id);
  573. if (!gc->target_process) {
  574. warn("could not open process: %s", gc->config.executable);
  575. return false;
  576. }
  577. gc->process_is_64bit = is_64bit_process(gc->target_process);
  578. gc->is_app = is_app(gc->target_process);
  579. if (gc->is_app) {
  580. gc->app_sid = get_app_sid(gc->target_process);
  581. }
  582. return true;
  583. }
  584. static inline bool init_keepalive(struct game_capture *gc)
  585. {
  586. wchar_t new_name[64];
  587. swprintf(new_name, 64, WINDOW_HOOK_KEEPALIVE L"%lu", gc->process_id);
  588. gc->keepalive_mutex = gc->is_app
  589. ? create_app_mutex(gc->app_sid, new_name)
  590. : CreateMutexW(NULL, false, new_name);
  591. if (!gc->keepalive_mutex) {
  592. warn("Failed to create keepalive mutex: %lu", GetLastError());
  593. return false;
  594. }
  595. return true;
  596. }
  597. static inline bool init_texture_mutexes(struct game_capture *gc)
  598. {
  599. gc->texture_mutexes[0] = open_mutex_gc(gc, MUTEX_TEXTURE1);
  600. gc->texture_mutexes[1] = open_mutex_gc(gc, MUTEX_TEXTURE2);
  601. if (!gc->texture_mutexes[0] || !gc->texture_mutexes[1]) {
  602. DWORD error = GetLastError();
  603. if (error == 2) {
  604. if (!gc->retrying) {
  605. gc->retrying = 2;
  606. info("hook not loaded yet, retrying..");
  607. }
  608. } else {
  609. warn("failed to open texture mutexes: %lu",
  610. GetLastError());
  611. }
  612. return false;
  613. }
  614. return true;
  615. }
  616. /* if there's already a hook in the process, then signal and start */
  617. static inline bool attempt_existing_hook(struct game_capture *gc)
  618. {
  619. gc->hook_restart = open_event_gc(gc, EVENT_CAPTURE_RESTART);
  620. if (gc->hook_restart) {
  621. debug("existing hook found, signaling process: %s",
  622. gc->config.executable);
  623. SetEvent(gc->hook_restart);
  624. return true;
  625. }
  626. return false;
  627. }
  628. static inline void reset_frame_interval(struct game_capture *gc)
  629. {
  630. struct obs_video_info ovi;
  631. uint64_t interval = 0;
  632. if (obs_get_video_info(&ovi)) {
  633. interval =
  634. util_mul_div64(ovi.fps_den, 1000000000ULL, ovi.fps_num);
  635. /* Always limit capture framerate to some extent. If a game
  636. * running at 900 FPS is being captured without some sort of
  637. * limited capture interval, it will dramatically reduce
  638. * performance. */
  639. if (!gc->config.limit_framerate)
  640. interval /= 2;
  641. }
  642. gc->global_hook_info->frame_interval = interval;
  643. }
  644. static inline bool init_hook_info(struct game_capture *gc)
  645. {
  646. gc->global_hook_info_map = open_hook_info(gc);
  647. if (!gc->global_hook_info_map) {
  648. warn("init_hook_info: get_hook_info failed: %lu",
  649. GetLastError());
  650. return false;
  651. }
  652. gc->global_hook_info = MapViewOfFile(gc->global_hook_info_map,
  653. FILE_MAP_ALL_ACCESS, 0, 0,
  654. sizeof(*gc->global_hook_info));
  655. if (!gc->global_hook_info) {
  656. warn("init_hook_info: failed to map data view: %lu",
  657. GetLastError());
  658. return false;
  659. }
  660. if (gc->config.force_shmem) {
  661. warn("init_hook_info: user is forcing shared memory "
  662. "(multi-adapter compatibility mode)");
  663. }
  664. gc->global_hook_info->offsets = gc->process_is_64bit ? offsets64
  665. : offsets32;
  666. gc->global_hook_info->capture_overlay = gc->config.capture_overlays;
  667. gc->global_hook_info->force_shmem = gc->config.force_shmem;
  668. gc->global_hook_info->UNUSED_use_scale = false;
  669. gc->global_hook_info->allow_srgb_alias = true;
  670. reset_frame_interval(gc);
  671. obs_enter_graphics();
  672. if (!gs_shared_texture_available()) {
  673. warn("init_hook_info: shared texture capture unavailable");
  674. gc->global_hook_info->force_shmem = true;
  675. }
  676. obs_leave_graphics();
  677. return true;
  678. }
  679. static void pipe_log(void *param, uint8_t *data, size_t size)
  680. {
  681. struct game_capture *gc = param;
  682. if (data && size)
  683. info("%s", data);
  684. }
  685. static inline bool init_pipe(struct game_capture *gc)
  686. {
  687. char name[64];
  688. sprintf(name, "%s%lu", PIPE_NAME, gc->process_id);
  689. if (!ipc_pipe_server_start(&gc->pipe, name, pipe_log, gc)) {
  690. warn("init_pipe: failed to start pipe");
  691. return false;
  692. }
  693. return true;
  694. }
  695. static inline int inject_library(HANDLE process, const wchar_t *dll)
  696. {
  697. return inject_library_obf(process, dll, "D|hkqkW`kl{k\\osofj",
  698. 0xa178ef3655e5ade7, "[uawaRzbhh{tIdkj~~",
  699. 0x561478dbd824387c, "[fr}pboIe`dlN}",
  700. 0x395bfbc9833590fd, "\\`zs}gmOzhhBq",
  701. 0x12897dd89168789a, "GbfkDaezbp~X",
  702. 0x76aff7238788f7db);
  703. }
  704. static inline bool hook_direct(struct game_capture *gc,
  705. const char *hook_path_rel)
  706. {
  707. wchar_t hook_path_abs_w[MAX_PATH];
  708. wchar_t *hook_path_rel_w;
  709. wchar_t *path_ret;
  710. HANDLE process;
  711. int ret;
  712. os_utf8_to_wcs_ptr(hook_path_rel, 0, &hook_path_rel_w);
  713. if (!hook_path_rel_w) {
  714. warn("hook_direct: could not convert string");
  715. return false;
  716. }
  717. path_ret = _wfullpath(hook_path_abs_w, hook_path_rel_w, MAX_PATH);
  718. bfree(hook_path_rel_w);
  719. if (path_ret == NULL) {
  720. warn("hook_direct: could not make absolute path");
  721. return false;
  722. }
  723. process = open_process(PROCESS_ALL_ACCESS, false, gc->process_id);
  724. if (!process) {
  725. warn("hook_direct: could not open process: %s (%lu)",
  726. gc->config.executable, GetLastError());
  727. return false;
  728. }
  729. ret = inject_library(process, hook_path_abs_w);
  730. CloseHandle(process);
  731. if (ret != 0) {
  732. warn("hook_direct: inject failed: %d", ret);
  733. return false;
  734. }
  735. return true;
  736. }
  737. static inline bool create_inject_process(struct game_capture *gc,
  738. const char *inject_path,
  739. const char *hook_dll)
  740. {
  741. wchar_t *command_line_w = malloc(4096 * sizeof(wchar_t));
  742. wchar_t *inject_path_w;
  743. wchar_t *hook_dll_w;
  744. bool anti_cheat = use_anticheat(gc);
  745. PROCESS_INFORMATION pi = {0};
  746. STARTUPINFO si = {0};
  747. bool success = false;
  748. os_utf8_to_wcs_ptr(inject_path, 0, &inject_path_w);
  749. os_utf8_to_wcs_ptr(hook_dll, 0, &hook_dll_w);
  750. si.cb = sizeof(si);
  751. swprintf(command_line_w, 4096, L"\"%s\" \"%s\" %lu %lu", inject_path_w,
  752. hook_dll_w, (unsigned long)anti_cheat,
  753. anti_cheat ? gc->thread_id : gc->process_id);
  754. success = !!CreateProcessW(inject_path_w, command_line_w, NULL, NULL,
  755. false, CREATE_NO_WINDOW, NULL, NULL, &si,
  756. &pi);
  757. if (success) {
  758. CloseHandle(pi.hThread);
  759. gc->injector_process = pi.hProcess;
  760. } else {
  761. warn("Failed to create inject helper process: %lu",
  762. GetLastError());
  763. }
  764. free(command_line_w);
  765. bfree(inject_path_w);
  766. bfree(hook_dll_w);
  767. return success;
  768. }
  769. extern char *get_hook_path(bool b64);
  770. static inline bool inject_hook(struct game_capture *gc)
  771. {
  772. bool matching_architecture;
  773. bool success = false;
  774. char *inject_path;
  775. char *hook_path;
  776. if (gc->process_is_64bit) {
  777. inject_path = obs_module_file("inject-helper64.exe");
  778. } else {
  779. inject_path = obs_module_file("inject-helper32.exe");
  780. }
  781. hook_path = get_hook_path(gc->process_is_64bit);
  782. if (!check_file_integrity(gc, inject_path, "inject helper")) {
  783. goto cleanup;
  784. }
  785. if (!check_file_integrity(gc, hook_path, "graphics hook")) {
  786. goto cleanup;
  787. }
  788. #ifdef _WIN64
  789. matching_architecture = gc->process_is_64bit;
  790. #else
  791. matching_architecture = !gc->process_is_64bit;
  792. #endif
  793. if (matching_architecture && !use_anticheat(gc)) {
  794. info("using direct hook");
  795. success = hook_direct(gc, hook_path);
  796. } else {
  797. info("using helper (%s hook)",
  798. use_anticheat(gc) ? "compatibility" : "direct");
  799. success = create_inject_process(gc, inject_path, hook_path);
  800. }
  801. cleanup:
  802. bfree(inject_path);
  803. bfree(hook_path);
  804. return success;
  805. }
  806. static const char *blacklisted_exes[] = {
  807. "explorer",
  808. "steam",
  809. "battle.net",
  810. "galaxyclient",
  811. "skype",
  812. "uplay",
  813. "origin",
  814. "devenv",
  815. "taskmgr",
  816. "chrome",
  817. "discord",
  818. "firefox",
  819. "systemsettings",
  820. "applicationframehost",
  821. "cmd",
  822. "shellexperiencehost",
  823. "winstore.app",
  824. "searchui",
  825. "lockapp",
  826. "windowsinternal.composableshell.experiences.textinput.inputapp",
  827. NULL,
  828. };
  829. static bool is_blacklisted_exe(const char *exe)
  830. {
  831. char cur_exe[MAX_PATH];
  832. if (!exe)
  833. return false;
  834. for (const char **vals = blacklisted_exes; *vals; vals++) {
  835. strcpy(cur_exe, *vals);
  836. strcat(cur_exe, ".exe");
  837. if (strcmpi(cur_exe, exe) == 0)
  838. return true;
  839. }
  840. return false;
  841. }
  842. static bool target_suspended(struct game_capture *gc)
  843. {
  844. return thread_is_suspended(gc->process_id, gc->thread_id);
  845. }
  846. static bool init_events(struct game_capture *gc);
  847. static bool init_hook(struct game_capture *gc)
  848. {
  849. struct dstr exe = {0};
  850. bool blacklisted_process = false;
  851. if (gc->config.mode == CAPTURE_MODE_ANY) {
  852. if (get_window_exe(&exe, gc->next_window)) {
  853. info("attempting to hook fullscreen process: %s",
  854. exe.array);
  855. }
  856. } else {
  857. if (get_window_exe(&exe, gc->next_window)) {
  858. info("attempting to hook process: %s", exe.array);
  859. }
  860. }
  861. blacklisted_process = is_blacklisted_exe(exe.array);
  862. if (blacklisted_process)
  863. info("cannot capture %s due to being blacklisted", exe.array);
  864. dstr_free(&exe);
  865. if (blacklisted_process) {
  866. return false;
  867. }
  868. if (target_suspended(gc)) {
  869. return false;
  870. }
  871. if (!open_target_process(gc)) {
  872. return false;
  873. }
  874. if (!init_keepalive(gc)) {
  875. return false;
  876. }
  877. if (!init_pipe(gc)) {
  878. return false;
  879. }
  880. if (!attempt_existing_hook(gc)) {
  881. if (!inject_hook(gc)) {
  882. return false;
  883. }
  884. }
  885. if (!init_texture_mutexes(gc)) {
  886. return false;
  887. }
  888. if (!init_hook_info(gc)) {
  889. return false;
  890. }
  891. if (!init_events(gc)) {
  892. return false;
  893. }
  894. SetEvent(gc->hook_init);
  895. gc->window = gc->next_window;
  896. gc->next_window = NULL;
  897. gc->active = true;
  898. gc->retrying = 0;
  899. return true;
  900. }
  901. static void setup_window(struct game_capture *gc, HWND window)
  902. {
  903. HANDLE hook_restart;
  904. HANDLE process;
  905. GetWindowThreadProcessId(window, &gc->process_id);
  906. if (gc->process_id) {
  907. process = open_process(PROCESS_QUERY_INFORMATION, false,
  908. gc->process_id);
  909. if (process) {
  910. gc->is_app = is_app(process);
  911. if (gc->is_app) {
  912. gc->app_sid = get_app_sid(process);
  913. }
  914. CloseHandle(process);
  915. }
  916. }
  917. /* do not wait if we're re-hooking a process */
  918. hook_restart = open_event_gc(gc, EVENT_CAPTURE_RESTART);
  919. if (hook_restart) {
  920. gc->wait_for_target_startup = false;
  921. CloseHandle(hook_restart);
  922. }
  923. /* otherwise if it's an unhooked process, always wait a bit for the
  924. * target process to start up before starting the hook process;
  925. * sometimes they have important modules to load first or other hooks
  926. * (such as steam) need a little bit of time to load. ultimately this
  927. * helps prevent crashes */
  928. if (gc->wait_for_target_startup) {
  929. gc->retry_interval =
  930. 3.0f * hook_rate_to_float(gc->config.hook_rate);
  931. gc->wait_for_target_startup = false;
  932. } else {
  933. gc->next_window = window;
  934. }
  935. }
  936. static void get_fullscreen_window(struct game_capture *gc)
  937. {
  938. HWND window = GetForegroundWindow();
  939. MONITORINFO mi = {0};
  940. HMONITOR monitor;
  941. DWORD styles;
  942. RECT rect;
  943. gc->next_window = NULL;
  944. if (!window) {
  945. return;
  946. }
  947. if (!GetWindowRect(window, &rect)) {
  948. return;
  949. }
  950. /* ignore regular maximized windows */
  951. styles = (DWORD)GetWindowLongPtr(window, GWL_STYLE);
  952. if ((styles & WS_MAXIMIZE) != 0 && (styles & WS_BORDER) != 0) {
  953. return;
  954. }
  955. monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST);
  956. if (!monitor) {
  957. return;
  958. }
  959. mi.cbSize = sizeof(mi);
  960. if (!GetMonitorInfo(monitor, &mi)) {
  961. return;
  962. }
  963. if (rect.left == mi.rcMonitor.left &&
  964. rect.right == mi.rcMonitor.right &&
  965. rect.bottom == mi.rcMonitor.bottom &&
  966. rect.top == mi.rcMonitor.top) {
  967. setup_window(gc, window);
  968. } else {
  969. gc->wait_for_target_startup = true;
  970. }
  971. }
  972. static void get_selected_window(struct game_capture *gc)
  973. {
  974. HWND window;
  975. if (dstr_cmpi(&gc->class, "dwm") == 0) {
  976. wchar_t class_w[512];
  977. os_utf8_to_wcs(gc->class.array, 0, class_w, 512);
  978. window = FindWindowW(class_w, NULL);
  979. } else {
  980. window = find_window(INCLUDE_MINIMIZED, gc->priority,
  981. gc->class.array, gc->title.array,
  982. gc->executable.array);
  983. }
  984. if (window) {
  985. setup_window(gc, window);
  986. } else {
  987. gc->wait_for_target_startup = true;
  988. }
  989. }
  990. static void try_hook(struct game_capture *gc)
  991. {
  992. if (gc->config.mode == CAPTURE_MODE_ANY) {
  993. get_fullscreen_window(gc);
  994. } else {
  995. get_selected_window(gc);
  996. }
  997. if (gc->next_window) {
  998. gc->thread_id = GetWindowThreadProcessId(gc->next_window,
  999. &gc->process_id);
  1000. // Make sure we never try to hook ourselves (projector)
  1001. if (gc->process_id == GetCurrentProcessId())
  1002. return;
  1003. if (!gc->thread_id && gc->process_id)
  1004. return;
  1005. if (!gc->process_id) {
  1006. warn("error acquiring, failed to get window "
  1007. "thread/process ids: %lu",
  1008. GetLastError());
  1009. gc->error_acquiring = true;
  1010. return;
  1011. }
  1012. if (!init_hook(gc)) {
  1013. stop_capture(gc);
  1014. }
  1015. } else {
  1016. gc->active = false;
  1017. }
  1018. }
  1019. static inline bool init_events(struct game_capture *gc)
  1020. {
  1021. if (!gc->hook_restart) {
  1022. gc->hook_restart = open_event_gc(gc, EVENT_CAPTURE_RESTART);
  1023. if (!gc->hook_restart) {
  1024. warn("init_events: failed to get hook_restart "
  1025. "event: %lu",
  1026. GetLastError());
  1027. return false;
  1028. }
  1029. }
  1030. if (!gc->hook_stop) {
  1031. gc->hook_stop = open_event_gc(gc, EVENT_CAPTURE_STOP);
  1032. if (!gc->hook_stop) {
  1033. warn("init_events: failed to get hook_stop event: %lu",
  1034. GetLastError());
  1035. return false;
  1036. }
  1037. }
  1038. if (!gc->hook_init) {
  1039. gc->hook_init = open_event_gc(gc, EVENT_HOOK_INIT);
  1040. if (!gc->hook_init) {
  1041. warn("init_events: failed to get hook_init event: %lu",
  1042. GetLastError());
  1043. return false;
  1044. }
  1045. }
  1046. if (!gc->hook_ready) {
  1047. gc->hook_ready = open_event_gc(gc, EVENT_HOOK_READY);
  1048. if (!gc->hook_ready) {
  1049. warn("init_events: failed to get hook_ready event: %lu",
  1050. GetLastError());
  1051. return false;
  1052. }
  1053. }
  1054. if (!gc->hook_exit) {
  1055. gc->hook_exit = open_event_gc(gc, EVENT_HOOK_EXIT);
  1056. if (!gc->hook_exit) {
  1057. warn("init_events: failed to get hook_exit event: %lu",
  1058. GetLastError());
  1059. return false;
  1060. }
  1061. }
  1062. return true;
  1063. }
  1064. enum capture_result { CAPTURE_FAIL, CAPTURE_RETRY, CAPTURE_SUCCESS };
  1065. static inline bool init_data_map(struct game_capture *gc, HWND window)
  1066. {
  1067. wchar_t name[64];
  1068. swprintf(name, 64, SHMEM_TEXTURE "_%" PRIu64 "_",
  1069. (uint64_t)(uintptr_t)window);
  1070. gc->hook_data_map =
  1071. open_map_plus_id(gc, name, gc->global_hook_info->map_id);
  1072. return !!gc->hook_data_map;
  1073. }
  1074. static inline enum capture_result init_capture_data(struct game_capture *gc)
  1075. {
  1076. gc->cx = gc->global_hook_info->cx;
  1077. gc->cy = gc->global_hook_info->cy;
  1078. gc->pitch = gc->global_hook_info->pitch;
  1079. if (gc->data) {
  1080. UnmapViewOfFile(gc->data);
  1081. gc->data = NULL;
  1082. }
  1083. CloseHandle(gc->hook_data_map);
  1084. DWORD error = 0;
  1085. if (!init_data_map(gc, gc->window)) {
  1086. HWND retry_hwnd = (HWND)(uintptr_t)gc->global_hook_info->window;
  1087. error = GetLastError();
  1088. /* if there's an error, just override. some windows don't play
  1089. * nice. */
  1090. if (init_data_map(gc, retry_hwnd)) {
  1091. error = 0;
  1092. }
  1093. }
  1094. if (!gc->hook_data_map) {
  1095. if (error == 2) {
  1096. return CAPTURE_RETRY;
  1097. } else {
  1098. warn("init_capture_data: failed to open file "
  1099. "mapping: %lu",
  1100. error);
  1101. }
  1102. return CAPTURE_FAIL;
  1103. }
  1104. gc->data = MapViewOfFile(gc->hook_data_map, FILE_MAP_ALL_ACCESS, 0, 0,
  1105. gc->global_hook_info->map_size);
  1106. if (!gc->data) {
  1107. warn("init_capture_data: failed to map data view: %lu",
  1108. GetLastError());
  1109. return CAPTURE_FAIL;
  1110. }
  1111. return CAPTURE_SUCCESS;
  1112. }
  1113. #define PIXEL_16BIT_SIZE 2
  1114. #define PIXEL_32BIT_SIZE 4
  1115. static inline uint32_t convert_5_to_8bit(uint16_t val)
  1116. {
  1117. return (uint32_t)((double)(val & 0x1F) * (255.0 / 31.0));
  1118. }
  1119. static inline uint32_t convert_6_to_8bit(uint16_t val)
  1120. {
  1121. return (uint32_t)((double)(val & 0x3F) * (255.0 / 63.0));
  1122. }
  1123. static void copy_b5g6r5_tex(struct game_capture *gc, int cur_texture,
  1124. uint8_t *data, uint32_t pitch)
  1125. {
  1126. uint8_t *input = gc->texture_buffers[cur_texture];
  1127. uint32_t gc_cx = gc->cx;
  1128. uint32_t gc_cy = gc->cy;
  1129. uint32_t gc_pitch = gc->pitch;
  1130. for (size_t y = 0; y < gc_cy; y++) {
  1131. uint8_t *row = input + (gc_pitch * y);
  1132. uint8_t *out = data + (pitch * y);
  1133. for (size_t x = 0; x < gc_cx; x += 8) {
  1134. __m128i pixels_blue, pixels_green, pixels_red;
  1135. __m128i pixels_result;
  1136. __m128i *pixels_dest;
  1137. __m128i *pixels_src =
  1138. (__m128i *)(row + x * sizeof(uint16_t));
  1139. __m128i pixels = _mm_load_si128(pixels_src);
  1140. __m128i zero = _mm_setzero_si128();
  1141. __m128i pixels_low = _mm_unpacklo_epi16(pixels, zero);
  1142. __m128i pixels_high = _mm_unpackhi_epi16(pixels, zero);
  1143. __m128i blue_channel_mask = _mm_set1_epi32(0x0000001F);
  1144. __m128i blue_offset = _mm_set1_epi32(0x00000003);
  1145. __m128i green_channel_mask = _mm_set1_epi32(0x000007E0);
  1146. __m128i green_offset = _mm_set1_epi32(0x00000008);
  1147. __m128i red_channel_mask = _mm_set1_epi32(0x0000F800);
  1148. __m128i red_offset = _mm_set1_epi32(0x00000300);
  1149. pixels_blue =
  1150. _mm_and_si128(pixels_low, blue_channel_mask);
  1151. pixels_blue = _mm_slli_epi32(pixels_blue, 3);
  1152. pixels_blue = _mm_add_epi32(pixels_blue, blue_offset);
  1153. pixels_green =
  1154. _mm_and_si128(pixels_low, green_channel_mask);
  1155. pixels_green =
  1156. _mm_add_epi32(pixels_green, green_offset);
  1157. pixels_green = _mm_slli_epi32(pixels_green, 5);
  1158. pixels_red =
  1159. _mm_and_si128(pixels_low, red_channel_mask);
  1160. pixels_red = _mm_add_epi32(pixels_red, red_offset);
  1161. pixels_red = _mm_slli_epi32(pixels_red, 8);
  1162. pixels_result = _mm_set1_epi32(0xFF000000);
  1163. pixels_result =
  1164. _mm_or_si128(pixels_result, pixels_blue);
  1165. pixels_result =
  1166. _mm_or_si128(pixels_result, pixels_green);
  1167. pixels_result = _mm_or_si128(pixels_result, pixels_red);
  1168. pixels_dest = (__m128i *)(out + x * sizeof(uint32_t));
  1169. _mm_store_si128(pixels_dest, pixels_result);
  1170. pixels_blue =
  1171. _mm_and_si128(pixels_high, blue_channel_mask);
  1172. pixels_blue = _mm_slli_epi32(pixels_blue, 3);
  1173. pixels_blue = _mm_add_epi32(pixels_blue, blue_offset);
  1174. pixels_green =
  1175. _mm_and_si128(pixels_high, green_channel_mask);
  1176. pixels_green =
  1177. _mm_add_epi32(pixels_green, green_offset);
  1178. pixels_green = _mm_slli_epi32(pixels_green, 5);
  1179. pixels_red =
  1180. _mm_and_si128(pixels_high, red_channel_mask);
  1181. pixels_red = _mm_add_epi32(pixels_red, red_offset);
  1182. pixels_red = _mm_slli_epi32(pixels_red, 8);
  1183. pixels_result = _mm_set1_epi32(0xFF000000);
  1184. pixels_result =
  1185. _mm_or_si128(pixels_result, pixels_blue);
  1186. pixels_result =
  1187. _mm_or_si128(pixels_result, pixels_green);
  1188. pixels_result = _mm_or_si128(pixels_result, pixels_red);
  1189. pixels_dest =
  1190. (__m128i *)(out + (x + 4) * sizeof(uint32_t));
  1191. _mm_store_si128(pixels_dest, pixels_result);
  1192. }
  1193. }
  1194. }
  1195. static void copy_b5g5r5a1_tex(struct game_capture *gc, int cur_texture,
  1196. uint8_t *data, uint32_t pitch)
  1197. {
  1198. uint8_t *input = gc->texture_buffers[cur_texture];
  1199. uint32_t gc_cx = gc->cx;
  1200. uint32_t gc_cy = gc->cy;
  1201. uint32_t gc_pitch = gc->pitch;
  1202. for (size_t y = 0; y < gc_cy; y++) {
  1203. uint8_t *row = input + (gc_pitch * y);
  1204. uint8_t *out = data + (pitch * y);
  1205. for (size_t x = 0; x < gc_cx; x += 8) {
  1206. __m128i pixels_blue, pixels_green, pixels_red,
  1207. pixels_alpha;
  1208. __m128i pixels_result;
  1209. __m128i *pixels_dest;
  1210. __m128i *pixels_src =
  1211. (__m128i *)(row + x * sizeof(uint16_t));
  1212. __m128i pixels = _mm_load_si128(pixels_src);
  1213. __m128i zero = _mm_setzero_si128();
  1214. __m128i pixels_low = _mm_unpacklo_epi16(pixels, zero);
  1215. __m128i pixels_high = _mm_unpackhi_epi16(pixels, zero);
  1216. __m128i blue_channel_mask = _mm_set1_epi32(0x0000001F);
  1217. __m128i blue_offset = _mm_set1_epi32(0x00000003);
  1218. __m128i green_channel_mask = _mm_set1_epi32(0x000003E0);
  1219. __m128i green_offset = _mm_set1_epi32(0x000000C);
  1220. __m128i red_channel_mask = _mm_set1_epi32(0x00007C00);
  1221. __m128i red_offset = _mm_set1_epi32(0x00000180);
  1222. __m128i alpha_channel_mask = _mm_set1_epi32(0x00008000);
  1223. __m128i alpha_offset = _mm_set1_epi32(0x00000001);
  1224. __m128i alpha_mask32 = _mm_set1_epi32(0xFF000000);
  1225. pixels_blue =
  1226. _mm_and_si128(pixels_low, blue_channel_mask);
  1227. pixels_blue = _mm_slli_epi32(pixels_blue, 3);
  1228. pixels_blue = _mm_add_epi32(pixels_blue, blue_offset);
  1229. pixels_green =
  1230. _mm_and_si128(pixels_low, green_channel_mask);
  1231. pixels_green =
  1232. _mm_add_epi32(pixels_green, green_offset);
  1233. pixels_green = _mm_slli_epi32(pixels_green, 6);
  1234. pixels_red =
  1235. _mm_and_si128(pixels_low, red_channel_mask);
  1236. pixels_red = _mm_add_epi32(pixels_red, red_offset);
  1237. pixels_red = _mm_slli_epi32(pixels_red, 9);
  1238. pixels_alpha =
  1239. _mm_and_si128(pixels_low, alpha_channel_mask);
  1240. pixels_alpha = _mm_srli_epi32(pixels_alpha, 15);
  1241. pixels_alpha =
  1242. _mm_sub_epi32(pixels_alpha, alpha_offset);
  1243. pixels_alpha =
  1244. _mm_andnot_si128(pixels_alpha, alpha_mask32);
  1245. pixels_result = pixels_red;
  1246. pixels_result =
  1247. _mm_or_si128(pixels_result, pixels_alpha);
  1248. pixels_result =
  1249. _mm_or_si128(pixels_result, pixels_blue);
  1250. pixels_result =
  1251. _mm_or_si128(pixels_result, pixels_green);
  1252. pixels_dest = (__m128i *)(out + x * sizeof(uint32_t));
  1253. _mm_store_si128(pixels_dest, pixels_result);
  1254. pixels_blue =
  1255. _mm_and_si128(pixels_high, blue_channel_mask);
  1256. pixels_blue = _mm_slli_epi32(pixels_blue, 3);
  1257. pixels_blue = _mm_add_epi32(pixels_blue, blue_offset);
  1258. pixels_green =
  1259. _mm_and_si128(pixels_high, green_channel_mask);
  1260. pixels_green =
  1261. _mm_add_epi32(pixels_green, green_offset);
  1262. pixels_green = _mm_slli_epi32(pixels_green, 6);
  1263. pixels_red =
  1264. _mm_and_si128(pixels_high, red_channel_mask);
  1265. pixels_red = _mm_add_epi32(pixels_red, red_offset);
  1266. pixels_red = _mm_slli_epi32(pixels_red, 9);
  1267. pixels_alpha =
  1268. _mm_and_si128(pixels_high, alpha_channel_mask);
  1269. pixels_alpha = _mm_srli_epi32(pixels_alpha, 15);
  1270. pixels_alpha =
  1271. _mm_sub_epi32(pixels_alpha, alpha_offset);
  1272. pixels_alpha =
  1273. _mm_andnot_si128(pixels_alpha, alpha_mask32);
  1274. pixels_result = pixels_red;
  1275. pixels_result =
  1276. _mm_or_si128(pixels_result, pixels_alpha);
  1277. pixels_result =
  1278. _mm_or_si128(pixels_result, pixels_blue);
  1279. pixels_result =
  1280. _mm_or_si128(pixels_result, pixels_green);
  1281. pixels_dest =
  1282. (__m128i *)(out + (x + 4) * sizeof(uint32_t));
  1283. _mm_store_si128(pixels_dest, pixels_result);
  1284. }
  1285. }
  1286. }
  1287. static inline void copy_16bit_tex(struct game_capture *gc, int cur_texture,
  1288. uint8_t *data, uint32_t pitch)
  1289. {
  1290. if (gc->global_hook_info->format == DXGI_FORMAT_B5G5R5A1_UNORM) {
  1291. copy_b5g5r5a1_tex(gc, cur_texture, data, pitch);
  1292. } else if (gc->global_hook_info->format == DXGI_FORMAT_B5G6R5_UNORM) {
  1293. copy_b5g6r5_tex(gc, cur_texture, data, pitch);
  1294. }
  1295. }
  1296. static void copy_shmem_tex(struct game_capture *gc)
  1297. {
  1298. int cur_texture;
  1299. HANDLE mutex = NULL;
  1300. uint32_t pitch;
  1301. int next_texture;
  1302. uint8_t *data;
  1303. if (!gc->shmem_data)
  1304. return;
  1305. cur_texture = gc->shmem_data->last_tex;
  1306. if (cur_texture < 0 || cur_texture > 1)
  1307. return;
  1308. next_texture = cur_texture == 1 ? 0 : 1;
  1309. if (object_signalled(gc->texture_mutexes[cur_texture])) {
  1310. mutex = gc->texture_mutexes[cur_texture];
  1311. } else if (object_signalled(gc->texture_mutexes[next_texture])) {
  1312. mutex = gc->texture_mutexes[next_texture];
  1313. cur_texture = next_texture;
  1314. } else {
  1315. return;
  1316. }
  1317. if (gs_texture_map(gc->texture, &data, &pitch)) {
  1318. if (gc->convert_16bit) {
  1319. copy_16bit_tex(gc, cur_texture, data, pitch);
  1320. } else if (pitch == gc->pitch) {
  1321. memcpy(data, gc->texture_buffers[cur_texture],
  1322. (size_t)pitch * (size_t)gc->cy);
  1323. } else {
  1324. uint8_t *input = gc->texture_buffers[cur_texture];
  1325. uint32_t best_pitch = pitch < gc->pitch ? pitch
  1326. : gc->pitch;
  1327. for (size_t y = 0; y < gc->cy; y++) {
  1328. uint8_t *line_in = input + gc->pitch * y;
  1329. uint8_t *line_out = data + pitch * y;
  1330. memcpy(line_out, line_in, best_pitch);
  1331. }
  1332. }
  1333. gs_texture_unmap(gc->texture);
  1334. }
  1335. ReleaseMutex(mutex);
  1336. }
  1337. static inline bool is_16bit_format(uint32_t format)
  1338. {
  1339. return format == DXGI_FORMAT_B5G5R5A1_UNORM ||
  1340. format == DXGI_FORMAT_B5G6R5_UNORM;
  1341. }
  1342. static inline bool init_shmem_capture(struct game_capture *gc)
  1343. {
  1344. const uint32_t dxgi_format = gc->global_hook_info->format;
  1345. const bool convert_16bit = is_16bit_format(dxgi_format);
  1346. const enum gs_color_format format =
  1347. convert_16bit ? GS_BGRA : convert_format(dxgi_format);
  1348. obs_enter_graphics();
  1349. gs_texrender_destroy(gc->extra_texrender);
  1350. gc->extra_texrender = NULL;
  1351. gs_texture_destroy(gc->extra_texture);
  1352. gc->extra_texture = NULL;
  1353. gs_texture_destroy(gc->texture);
  1354. gc->texture = NULL;
  1355. gs_texture_t *const texture =
  1356. gs_texture_create(gc->cx, gc->cy, format, 1, NULL, GS_DYNAMIC);
  1357. obs_leave_graphics();
  1358. bool success = texture != NULL;
  1359. if (success) {
  1360. const bool linear_sample = format != GS_R10G10B10A2;
  1361. gs_texrender_t *extra_texrender = NULL;
  1362. if (!linear_sample) {
  1363. extra_texrender =
  1364. gs_texrender_create(GS_BGRA, GS_ZS_NONE);
  1365. success = extra_texrender != NULL;
  1366. if (!success)
  1367. warn("init_shmem_capture: failed to create extra texrender");
  1368. }
  1369. if (success) {
  1370. gc->texture_buffers[0] = (uint8_t *)gc->data +
  1371. gc->shmem_data->tex1_offset;
  1372. gc->texture_buffers[1] = (uint8_t *)gc->data +
  1373. gc->shmem_data->tex2_offset;
  1374. gc->convert_16bit = convert_16bit;
  1375. gc->texture = texture;
  1376. gc->extra_texture = NULL;
  1377. gc->extra_texrender = extra_texrender;
  1378. gc->linear_sample = linear_sample;
  1379. gc->copy_texture = copy_shmem_tex;
  1380. } else {
  1381. gs_texture_destroy(texture);
  1382. }
  1383. } else {
  1384. warn("init_shmem_capture: failed to create texture");
  1385. }
  1386. return success;
  1387. }
  1388. static inline bool init_shtex_capture(struct game_capture *gc)
  1389. {
  1390. obs_enter_graphics();
  1391. gs_texrender_destroy(gc->extra_texrender);
  1392. gc->extra_texrender = NULL;
  1393. gs_texture_destroy(gc->extra_texture);
  1394. gc->extra_texture = NULL;
  1395. gs_texture_destroy(gc->texture);
  1396. gc->texture = NULL;
  1397. gs_texture_t *const texture =
  1398. gs_texture_open_shared(gc->shtex_data->tex_handle);
  1399. bool success = texture != NULL;
  1400. if (success) {
  1401. enum gs_color_format format =
  1402. gs_texture_get_color_format(texture);
  1403. const bool ten_bit_srgb = (format == GS_R10G10B10A2);
  1404. enum gs_color_format linear_format =
  1405. ten_bit_srgb ? GS_BGRA : gs_generalize_format(format);
  1406. const bool linear_sample = (linear_format == format);
  1407. gs_texture_t *extra_texture = NULL;
  1408. gs_texrender_t *extra_texrender = NULL;
  1409. if (!linear_sample) {
  1410. if (ten_bit_srgb) {
  1411. extra_texrender = gs_texrender_create(
  1412. linear_format, GS_ZS_NONE);
  1413. success = extra_texrender != NULL;
  1414. if (!success)
  1415. warn("init_shtex_capture: failed to create extra texrender");
  1416. } else {
  1417. extra_texture = gs_texture_create(
  1418. gs_texture_get_width(texture),
  1419. gs_texture_get_height(texture),
  1420. linear_format, 1, NULL, 0);
  1421. success = extra_texture != NULL;
  1422. if (!success)
  1423. warn("init_shtex_capture: failed to create extra texture");
  1424. }
  1425. }
  1426. if (success) {
  1427. gc->texture = texture;
  1428. gc->linear_sample = linear_sample;
  1429. gc->extra_texture = extra_texture;
  1430. gc->extra_texrender = extra_texrender;
  1431. } else {
  1432. gs_texture_destroy(texture);
  1433. }
  1434. } else {
  1435. warn("init_shtex_capture: failed to open shared handle");
  1436. }
  1437. obs_leave_graphics();
  1438. return success;
  1439. }
  1440. static bool start_capture(struct game_capture *gc)
  1441. {
  1442. debug("Starting capture");
  1443. /* prevent from using a DLL version that's higher than current */
  1444. if (gc->global_hook_info->hook_ver_major > HOOK_VER_MAJOR) {
  1445. warn("cannot initialize hook, DLL hook version is "
  1446. "%" PRIu32 ".%" PRIu32
  1447. ", current plugin hook major version is %d.%d",
  1448. gc->global_hook_info->hook_ver_major,
  1449. gc->global_hook_info->hook_ver_minor, HOOK_VER_MAJOR,
  1450. HOOK_VER_MINOR);
  1451. return false;
  1452. }
  1453. if (gc->global_hook_info->type == CAPTURE_TYPE_MEMORY) {
  1454. if (!init_shmem_capture(gc)) {
  1455. return false;
  1456. }
  1457. info("memory capture successful");
  1458. } else {
  1459. if (!init_shtex_capture(gc)) {
  1460. return false;
  1461. }
  1462. info("shared texture capture successful");
  1463. }
  1464. return true;
  1465. }
  1466. static inline bool capture_valid(struct game_capture *gc)
  1467. {
  1468. if (!gc->dwm_capture && !IsWindow(gc->window))
  1469. return false;
  1470. return !object_signalled(gc->target_process);
  1471. }
  1472. static void check_foreground_window(struct game_capture *gc, float seconds)
  1473. {
  1474. // Hides the cursor if the user isn't actively in the game
  1475. gc->cursor_check_time += seconds;
  1476. if (gc->cursor_check_time >= 0.1f) {
  1477. DWORD foreground_process_id;
  1478. GetWindowThreadProcessId(GetForegroundWindow(),
  1479. &foreground_process_id);
  1480. if (gc->process_id != foreground_process_id)
  1481. gc->cursor_hidden = true;
  1482. else
  1483. gc->cursor_hidden = false;
  1484. gc->cursor_check_time = 0.0f;
  1485. }
  1486. }
  1487. static void game_capture_tick(void *data, float seconds)
  1488. {
  1489. struct game_capture *gc = data;
  1490. bool deactivate = os_atomic_set_bool(&gc->deactivate_hook, false);
  1491. bool activate_now = os_atomic_set_bool(&gc->activate_hook_now, false);
  1492. if (activate_now) {
  1493. HWND hwnd = (HWND)(uintptr_t)os_atomic_load_long(
  1494. &gc->hotkey_window);
  1495. if (is_uwp_window(hwnd))
  1496. hwnd = get_uwp_actual_window(hwnd);
  1497. if (get_window_exe(&gc->executable, hwnd)) {
  1498. get_window_title(&gc->title, hwnd);
  1499. get_window_class(&gc->class, hwnd);
  1500. gc->priority = WINDOW_PRIORITY_CLASS;
  1501. gc->retry_time = 10.0f * hook_rate_to_float(
  1502. gc->config.hook_rate);
  1503. gc->activate_hook = true;
  1504. } else {
  1505. deactivate = false;
  1506. activate_now = false;
  1507. }
  1508. } else if (deactivate) {
  1509. gc->activate_hook = false;
  1510. }
  1511. if (!obs_source_showing(gc->source)) {
  1512. if (gc->showing) {
  1513. if (gc->active)
  1514. stop_capture(gc);
  1515. gc->showing = false;
  1516. }
  1517. return;
  1518. } else if (!gc->showing) {
  1519. gc->retry_time =
  1520. 10.0f * hook_rate_to_float(gc->config.hook_rate);
  1521. }
  1522. if (gc->hook_stop && object_signalled(gc->hook_stop)) {
  1523. debug("hook stop signal received");
  1524. stop_capture(gc);
  1525. }
  1526. if (gc->active && deactivate) {
  1527. stop_capture(gc);
  1528. }
  1529. if (gc->active && !gc->hook_ready && gc->process_id) {
  1530. gc->hook_ready = open_event_gc(gc, EVENT_HOOK_READY);
  1531. }
  1532. if (gc->injector_process && object_signalled(gc->injector_process)) {
  1533. DWORD exit_code = 0;
  1534. GetExitCodeProcess(gc->injector_process, &exit_code);
  1535. close_handle(&gc->injector_process);
  1536. if (exit_code != 0) {
  1537. warn("inject process failed: %ld", (long)exit_code);
  1538. gc->error_acquiring = true;
  1539. } else if (!gc->capturing) {
  1540. gc->retry_interval =
  1541. ERROR_RETRY_INTERVAL *
  1542. hook_rate_to_float(gc->config.hook_rate);
  1543. stop_capture(gc);
  1544. }
  1545. }
  1546. if (gc->hook_ready && object_signalled(gc->hook_ready)) {
  1547. debug("capture initializing!");
  1548. enum capture_result result = init_capture_data(gc);
  1549. if (result == CAPTURE_SUCCESS)
  1550. gc->capturing = start_capture(gc);
  1551. else
  1552. debug("init_capture_data failed");
  1553. if (result != CAPTURE_RETRY && !gc->capturing) {
  1554. gc->retry_interval =
  1555. ERROR_RETRY_INTERVAL *
  1556. hook_rate_to_float(gc->config.hook_rate);
  1557. stop_capture(gc);
  1558. }
  1559. }
  1560. gc->retry_time += seconds;
  1561. if (!gc->active) {
  1562. if (!gc->error_acquiring &&
  1563. gc->retry_time > gc->retry_interval) {
  1564. if (gc->config.mode == CAPTURE_MODE_ANY ||
  1565. gc->activate_hook) {
  1566. try_hook(gc);
  1567. gc->retry_time = 0.0f;
  1568. }
  1569. }
  1570. } else {
  1571. if (!capture_valid(gc)) {
  1572. info("capture window no longer exists, "
  1573. "terminating capture");
  1574. stop_capture(gc);
  1575. } else {
  1576. if (gc->copy_texture) {
  1577. obs_enter_graphics();
  1578. gc->copy_texture(gc);
  1579. obs_leave_graphics();
  1580. }
  1581. if (gc->config.cursor) {
  1582. DPI_AWARENESS_CONTEXT previous = NULL;
  1583. if (gc->get_window_dpi_awareness_context !=
  1584. NULL) {
  1585. const DPI_AWARENESS_CONTEXT context =
  1586. gc->get_window_dpi_awareness_context(
  1587. gc->window);
  1588. previous =
  1589. gc->set_thread_dpi_awareness_context(
  1590. context);
  1591. }
  1592. check_foreground_window(gc, seconds);
  1593. obs_enter_graphics();
  1594. cursor_capture(&gc->cursor_data);
  1595. obs_leave_graphics();
  1596. if (previous) {
  1597. gc->set_thread_dpi_awareness_context(
  1598. previous);
  1599. }
  1600. }
  1601. gc->fps_reset_time += seconds;
  1602. if (gc->fps_reset_time >= gc->retry_interval) {
  1603. reset_frame_interval(gc);
  1604. gc->fps_reset_time = 0.0f;
  1605. }
  1606. }
  1607. }
  1608. if (!gc->showing)
  1609. gc->showing = true;
  1610. }
  1611. static inline void game_capture_render_cursor(struct game_capture *gc)
  1612. {
  1613. POINT p = {0};
  1614. HWND window;
  1615. if (!gc->global_hook_info->cx || !gc->global_hook_info->cy)
  1616. return;
  1617. window = !!gc->global_hook_info->window
  1618. ? (HWND)(uintptr_t)gc->global_hook_info->window
  1619. : gc->window;
  1620. DPI_AWARENESS_CONTEXT previous = NULL;
  1621. if (gc->get_window_dpi_awareness_context != NULL) {
  1622. const DPI_AWARENESS_CONTEXT context =
  1623. gc->get_window_dpi_awareness_context(gc->window);
  1624. previous = gc->set_thread_dpi_awareness_context(context);
  1625. }
  1626. ClientToScreen(window, &p);
  1627. if (previous)
  1628. gc->set_thread_dpi_awareness_context(previous);
  1629. cursor_draw(&gc->cursor_data, -p.x, -p.y, gc->global_hook_info->cx,
  1630. gc->global_hook_info->cy);
  1631. }
  1632. static void game_capture_render(void *data, gs_effect_t *unused)
  1633. {
  1634. UNUSED_PARAMETER(unused);
  1635. struct game_capture *gc = data;
  1636. if (!gc->texture || !gc->active)
  1637. return;
  1638. const bool allow_transparency = gc->config.allow_transparency;
  1639. gs_effect_t *const effect = obs_get_base_effect(
  1640. allow_transparency ? OBS_EFFECT_DEFAULT : OBS_EFFECT_OPAQUE);
  1641. bool linear_sample = gc->linear_sample;
  1642. gs_texture_t *texture = gc->texture;
  1643. if (!linear_sample && !obs_source_get_texcoords_centered(gc->source)) {
  1644. gs_texture_t *const extra_texture = gc->extra_texture;
  1645. if (extra_texture) {
  1646. gs_copy_texture(extra_texture, texture);
  1647. texture = extra_texture;
  1648. } else {
  1649. gs_texrender_t *const texrender = gc->extra_texrender;
  1650. gs_texrender_reset(texrender);
  1651. const uint32_t cx = gs_texture_get_width(texture);
  1652. const uint32_t cy = gs_texture_get_height(texture);
  1653. if (gs_texrender_begin(texrender, cx, cy)) {
  1654. gs_effect_t *const default_effect =
  1655. obs_get_base_effect(OBS_EFFECT_DEFAULT);
  1656. const bool previous =
  1657. gs_framebuffer_srgb_enabled();
  1658. gs_enable_framebuffer_srgb(false);
  1659. gs_enable_blending(false);
  1660. gs_ortho(0.0f, (float)cx, 0.0f, (float)cy,
  1661. -100.0f, 100.0f);
  1662. gs_eparam_t *const image =
  1663. gs_effect_get_param_by_name(
  1664. default_effect, "image");
  1665. gs_effect_set_texture(image, texture);
  1666. while (gs_effect_loop(default_effect, "Draw")) {
  1667. gs_draw_sprite(texture, 0, 0, 0);
  1668. }
  1669. gs_enable_blending(true);
  1670. gs_enable_framebuffer_srgb(previous);
  1671. gs_texrender_end(texrender);
  1672. texture = gs_texrender_get_texture(texrender);
  1673. }
  1674. }
  1675. linear_sample = true;
  1676. }
  1677. gs_eparam_t *const image = gs_effect_get_param_by_name(effect, "image");
  1678. const uint32_t flip = gc->global_hook_info->flip ? GS_FLIP_V : 0;
  1679. const char *tech_name = allow_transparency && !linear_sample
  1680. ? "DrawSrgbDecompress"
  1681. : "Draw";
  1682. while (gs_effect_loop(effect, tech_name)) {
  1683. const bool previous = gs_framebuffer_srgb_enabled();
  1684. gs_enable_framebuffer_srgb(allow_transparency || linear_sample);
  1685. gs_enable_blending(allow_transparency);
  1686. if (linear_sample)
  1687. gs_effect_set_texture_srgb(image, texture);
  1688. else
  1689. gs_effect_set_texture(image, texture);
  1690. gs_draw_sprite(texture, flip, 0, 0);
  1691. gs_enable_blending(true);
  1692. gs_enable_framebuffer_srgb(previous);
  1693. if (allow_transparency && gc->config.cursor &&
  1694. !gc->cursor_hidden) {
  1695. game_capture_render_cursor(gc);
  1696. }
  1697. }
  1698. if (!allow_transparency && gc->config.cursor && !gc->cursor_hidden) {
  1699. gs_effect_t *const default_effect =
  1700. obs_get_base_effect(OBS_EFFECT_DEFAULT);
  1701. while (gs_effect_loop(default_effect, "Draw")) {
  1702. game_capture_render_cursor(gc);
  1703. }
  1704. }
  1705. }
  1706. static uint32_t game_capture_width(void *data)
  1707. {
  1708. struct game_capture *gc = data;
  1709. return gc->active ? gc->cx : 0;
  1710. }
  1711. static uint32_t game_capture_height(void *data)
  1712. {
  1713. struct game_capture *gc = data;
  1714. return gc->active ? gc->cy : 0;
  1715. }
  1716. static const char *game_capture_name(void *unused)
  1717. {
  1718. UNUSED_PARAMETER(unused);
  1719. return TEXT_GAME_CAPTURE;
  1720. }
  1721. static void game_capture_defaults(obs_data_t *settings)
  1722. {
  1723. obs_data_set_default_string(settings, SETTING_MODE, SETTING_MODE_ANY);
  1724. obs_data_set_default_int(settings, SETTING_WINDOW_PRIORITY,
  1725. (int)WINDOW_PRIORITY_EXE);
  1726. obs_data_set_default_bool(settings, SETTING_COMPATIBILITY, false);
  1727. obs_data_set_default_bool(settings, SETTING_CURSOR, true);
  1728. obs_data_set_default_bool(settings, SETTING_TRANSPARENCY, false);
  1729. obs_data_set_default_bool(settings, SETTING_LIMIT_FRAMERATE, false);
  1730. obs_data_set_default_bool(settings, SETTING_CAPTURE_OVERLAYS, false);
  1731. obs_data_set_default_bool(settings, SETTING_ANTI_CHEAT_HOOK, true);
  1732. obs_data_set_default_int(settings, SETTING_HOOK_RATE,
  1733. (int)HOOK_RATE_NORMAL);
  1734. }
  1735. static bool mode_callback(obs_properties_t *ppts, obs_property_t *p,
  1736. obs_data_t *settings)
  1737. {
  1738. bool capture_window;
  1739. if (using_older_non_mode_format(settings)) {
  1740. capture_window =
  1741. !obs_data_get_bool(settings, SETTING_ANY_FULLSCREEN);
  1742. } else {
  1743. const char *mode = obs_data_get_string(settings, SETTING_MODE);
  1744. capture_window = strcmp(mode, SETTING_MODE_WINDOW) == 0;
  1745. }
  1746. p = obs_properties_get(ppts, SETTING_CAPTURE_WINDOW);
  1747. obs_property_set_visible(p, capture_window);
  1748. p = obs_properties_get(ppts, SETTING_WINDOW_PRIORITY);
  1749. obs_property_set_visible(p, capture_window);
  1750. return true;
  1751. }
  1752. static void insert_preserved_val(obs_property_t *p, const char *val, size_t idx)
  1753. {
  1754. char *class = NULL;
  1755. char *title = NULL;
  1756. char *executable = NULL;
  1757. struct dstr desc = {0};
  1758. build_window_strings(val, &class, &title, &executable);
  1759. dstr_printf(&desc, "[%s]: %s", executable, title);
  1760. obs_property_list_insert_string(p, idx, desc.array, val);
  1761. obs_property_list_item_disable(p, idx, true);
  1762. dstr_free(&desc);
  1763. bfree(class);
  1764. bfree(title);
  1765. bfree(executable);
  1766. }
  1767. bool check_window_property_setting(obs_properties_t *ppts, obs_property_t *p,
  1768. obs_data_t *settings, const char *val,
  1769. size_t idx)
  1770. {
  1771. const char *cur_val;
  1772. bool match = false;
  1773. size_t i = 0;
  1774. cur_val = obs_data_get_string(settings, val);
  1775. if (!cur_val) {
  1776. return false;
  1777. }
  1778. for (;;) {
  1779. const char *val = obs_property_list_item_string(p, i++);
  1780. if (!val)
  1781. break;
  1782. if (strcmp(val, cur_val) == 0) {
  1783. match = true;
  1784. break;
  1785. }
  1786. }
  1787. if (cur_val && *cur_val && !match) {
  1788. insert_preserved_val(p, cur_val, idx);
  1789. return true;
  1790. }
  1791. UNUSED_PARAMETER(ppts);
  1792. return false;
  1793. }
  1794. static bool window_changed_callback(obs_properties_t *ppts, obs_property_t *p,
  1795. obs_data_t *settings)
  1796. {
  1797. return check_window_property_setting(ppts, p, settings,
  1798. SETTING_CAPTURE_WINDOW, 1);
  1799. }
  1800. static BOOL CALLBACK EnumFirstMonitor(HMONITOR monitor, HDC hdc, LPRECT rc,
  1801. LPARAM data)
  1802. {
  1803. *(HMONITOR *)data = monitor;
  1804. UNUSED_PARAMETER(hdc);
  1805. UNUSED_PARAMETER(rc);
  1806. return false;
  1807. }
  1808. static bool window_not_blacklisted(const char *title, const char *class,
  1809. const char *exe)
  1810. {
  1811. UNUSED_PARAMETER(title);
  1812. UNUSED_PARAMETER(class);
  1813. return !is_blacklisted_exe(exe);
  1814. }
  1815. static obs_properties_t *game_capture_properties(void *data)
  1816. {
  1817. HMONITOR monitor;
  1818. uint32_t cx = 1920;
  1819. uint32_t cy = 1080;
  1820. /* scaling is free form, this is mostly just to provide some common
  1821. * values */
  1822. bool success = !!EnumDisplayMonitors(NULL, NULL, EnumFirstMonitor,
  1823. (LPARAM)&monitor);
  1824. if (success) {
  1825. MONITORINFO mi = {0};
  1826. mi.cbSize = sizeof(mi);
  1827. if (!!GetMonitorInfo(monitor, &mi)) {
  1828. cx = (uint32_t)(mi.rcMonitor.right - mi.rcMonitor.left);
  1829. cy = (uint32_t)(mi.rcMonitor.bottom - mi.rcMonitor.top);
  1830. }
  1831. }
  1832. /* update from deprecated settings */
  1833. if (data) {
  1834. struct game_capture *gc = data;
  1835. obs_data_t *settings = obs_source_get_settings(gc->source);
  1836. if (using_older_non_mode_format(settings)) {
  1837. bool any = obs_data_get_bool(settings,
  1838. SETTING_ANY_FULLSCREEN);
  1839. const char *mode = any ? SETTING_MODE_ANY
  1840. : SETTING_MODE_WINDOW;
  1841. obs_data_set_string(settings, SETTING_MODE, mode);
  1842. }
  1843. obs_data_release(settings);
  1844. }
  1845. obs_properties_t *ppts = obs_properties_create();
  1846. obs_property_t *p;
  1847. p = obs_properties_add_list(ppts, SETTING_MODE, TEXT_MODE,
  1848. OBS_COMBO_TYPE_LIST,
  1849. OBS_COMBO_FORMAT_STRING);
  1850. obs_property_list_add_string(p, TEXT_MODE_ANY, SETTING_MODE_ANY);
  1851. obs_property_list_add_string(p, TEXT_MODE_WINDOW, SETTING_MODE_WINDOW);
  1852. obs_property_list_add_string(p, TEXT_MODE_HOTKEY, SETTING_MODE_HOTKEY);
  1853. obs_property_set_modified_callback(p, mode_callback);
  1854. p = obs_properties_add_list(ppts, SETTING_CAPTURE_WINDOW, TEXT_WINDOW,
  1855. OBS_COMBO_TYPE_LIST,
  1856. OBS_COMBO_FORMAT_STRING);
  1857. obs_property_list_add_string(p, "", "");
  1858. fill_window_list(p, INCLUDE_MINIMIZED, window_not_blacklisted);
  1859. obs_property_set_modified_callback(p, window_changed_callback);
  1860. p = obs_properties_add_list(ppts, SETTING_WINDOW_PRIORITY,
  1861. TEXT_MATCH_PRIORITY, OBS_COMBO_TYPE_LIST,
  1862. OBS_COMBO_FORMAT_INT);
  1863. obs_property_list_add_int(p, TEXT_MATCH_TITLE, WINDOW_PRIORITY_TITLE);
  1864. obs_property_list_add_int(p, TEXT_MATCH_CLASS, WINDOW_PRIORITY_CLASS);
  1865. obs_property_list_add_int(p, TEXT_MATCH_EXE, WINDOW_PRIORITY_EXE);
  1866. obs_properties_add_bool(ppts, SETTING_COMPATIBILITY,
  1867. TEXT_SLI_COMPATIBILITY);
  1868. obs_properties_add_bool(ppts, SETTING_TRANSPARENCY,
  1869. TEXT_ALLOW_TRANSPARENCY);
  1870. obs_properties_add_bool(ppts, SETTING_LIMIT_FRAMERATE,
  1871. TEXT_LIMIT_FRAMERATE);
  1872. obs_properties_add_bool(ppts, SETTING_CURSOR, TEXT_CAPTURE_CURSOR);
  1873. obs_properties_add_bool(ppts, SETTING_ANTI_CHEAT_HOOK,
  1874. TEXT_ANTI_CHEAT_HOOK);
  1875. obs_properties_add_bool(ppts, SETTING_CAPTURE_OVERLAYS,
  1876. TEXT_CAPTURE_OVERLAYS);
  1877. p = obs_properties_add_list(ppts, SETTING_HOOK_RATE, TEXT_HOOK_RATE,
  1878. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1879. obs_property_list_add_int(p, TEXT_HOOK_RATE_SLOW, HOOK_RATE_SLOW);
  1880. obs_property_list_add_int(p, TEXT_HOOK_RATE_NORMAL, HOOK_RATE_NORMAL);
  1881. obs_property_list_add_int(p, TEXT_HOOK_RATE_FAST, HOOK_RATE_FAST);
  1882. obs_property_list_add_int(p, TEXT_HOOK_RATE_FASTEST, HOOK_RATE_FASTEST);
  1883. UNUSED_PARAMETER(data);
  1884. return ppts;
  1885. }
  1886. struct obs_source_info game_capture_info = {
  1887. .id = "game_capture",
  1888. .type = OBS_SOURCE_TYPE_INPUT,
  1889. .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW |
  1890. OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_SRGB,
  1891. .get_name = game_capture_name,
  1892. .create = game_capture_create,
  1893. .destroy = game_capture_destroy,
  1894. .get_width = game_capture_width,
  1895. .get_height = game_capture_height,
  1896. .get_defaults = game_capture_defaults,
  1897. .get_properties = game_capture_properties,
  1898. .update = game_capture_update,
  1899. .video_tick = game_capture_tick,
  1900. .video_render = game_capture_render,
  1901. .icon_type = OBS_ICON_TYPE_GAME_CAPTURE,
  1902. };