winrt-capture.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. extern "C" {
  2. HRESULT __stdcall CreateDirect3D11DeviceFromDXGIDevice(
  3. ::IDXGIDevice *dxgiDevice, ::IInspectable **graphicsDevice);
  4. HRESULT __stdcall CreateDirect3D11SurfaceFromDXGISurface(
  5. ::IDXGISurface *dgxiSurface, ::IInspectable **graphicsSurface);
  6. }
  7. struct __declspec(uuid("A9B3D012-3DF2-4EE3-B8D1-8695F457D3C1"))
  8. IDirect3DDxgiInterfaceAccess : ::IUnknown {
  9. virtual HRESULT __stdcall GetInterface(GUID const &id,
  10. void **object) = 0;
  11. };
  12. extern "C" EXPORT BOOL winrt_capture_supported()
  13. try {
  14. /* no contract for IGraphicsCaptureItemInterop, verify 10.0.18362.0 */
  15. return winrt::Windows::Foundation::Metadata::ApiInformation::
  16. IsApiContractPresent(L"Windows.Foundation.UniversalApiContract",
  17. 8);
  18. } catch (const winrt::hresult_error &err) {
  19. blog(LOG_ERROR, "winrt_capture_supported (0x%08X): %ls", err.to_abi(),
  20. err.message().c_str());
  21. return false;
  22. } catch (...) {
  23. blog(LOG_ERROR, "winrt_capture_supported (0x%08X)",
  24. winrt::to_hresult());
  25. return false;
  26. }
  27. extern "C" EXPORT BOOL winrt_capture_cursor_toggle_supported()
  28. try {
  29. #ifdef NTDDI_WIN10_VB
  30. return winrt::Windows::Foundation::Metadata::ApiInformation::
  31. IsPropertyPresent(
  32. L"Windows.Graphics.Capture.GraphicsCaptureSession",
  33. L"IsCursorCaptureEnabled");
  34. #else
  35. return false;
  36. #endif
  37. } catch (const winrt::hresult_error &err) {
  38. blog(LOG_ERROR, "winrt_capture_cursor_toggle_supported (0x%08X): %ls",
  39. err.to_abi(), err.message().c_str());
  40. return false;
  41. } catch (...) {
  42. blog(LOG_ERROR, "winrt_capture_cursor_toggle_supported (0x%08X)",
  43. winrt::to_hresult());
  44. return false;
  45. }
  46. template<typename T>
  47. static winrt::com_ptr<T> GetDXGIInterfaceFromObject(
  48. winrt::Windows::Foundation::IInspectable const &object)
  49. {
  50. auto access = object.as<IDirect3DDxgiInterfaceAccess>();
  51. winrt::com_ptr<T> result;
  52. winrt::check_hresult(
  53. access->GetInterface(winrt::guid_of<T>(), result.put_void()));
  54. return result;
  55. }
  56. static bool get_client_box(HWND window, uint32_t width, uint32_t height,
  57. D3D11_BOX *client_box)
  58. {
  59. RECT client_rect, window_rect{};
  60. POINT upper_left{};
  61. const bool client_box_available =
  62. GetClientRect(window, &client_rect) &&
  63. (DwmGetWindowAttribute(window, DWMWA_EXTENDED_FRAME_BOUNDS,
  64. &window_rect,
  65. sizeof(window_rect)) == S_OK) &&
  66. ClientToScreen(window, &upper_left);
  67. if (client_box_available) {
  68. const uint32_t left =
  69. (upper_left.x > window_rect.left)
  70. ? (upper_left.x - window_rect.left)
  71. : 0;
  72. client_box->left = left;
  73. const uint32_t top = (upper_left.y > window_rect.top)
  74. ? (upper_left.y - window_rect.top)
  75. : 0;
  76. client_box->top = top;
  77. uint32_t texture_width = 1;
  78. if (width > left) {
  79. texture_width =
  80. min(width - left, (uint32_t)client_rect.right);
  81. }
  82. uint32_t texture_height = 1;
  83. if (height > top) {
  84. texture_height =
  85. min(height - top, (uint32_t)client_rect.bottom);
  86. }
  87. client_box->right = left + texture_width;
  88. client_box->bottom = top + texture_height;
  89. client_box->front = 0;
  90. client_box->back = 1;
  91. }
  92. return client_box_available;
  93. }
  94. struct winrt_capture {
  95. HWND window;
  96. bool client_area;
  97. bool capture_cursor;
  98. bool cursor_visible;
  99. gs_texture_t *texture;
  100. bool texture_written;
  101. winrt::Windows::Graphics::Capture::GraphicsCaptureItem item{nullptr};
  102. winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice device{
  103. nullptr};
  104. ComPtr<ID3D11DeviceContext> context;
  105. winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool frame_pool{
  106. nullptr};
  107. winrt::Windows::Graphics::Capture::GraphicsCaptureSession session{
  108. nullptr};
  109. winrt::Windows::Graphics::SizeInt32 last_size;
  110. winrt::Windows::Graphics::Capture::GraphicsCaptureItem::Closed_revoker
  111. closed;
  112. winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool::
  113. FrameArrived_revoker frame_arrived;
  114. uint32_t texture_width;
  115. uint32_t texture_height;
  116. D3D11_BOX client_box;
  117. bool client_box_available;
  118. bool thread_changed;
  119. bool active;
  120. struct winrt_capture *next;
  121. void draw_cursor()
  122. {
  123. CURSORINFO ci{};
  124. ci.cbSize = sizeof(CURSORINFO);
  125. if (!GetCursorInfo(&ci))
  126. return;
  127. if (!(ci.flags & CURSOR_SHOWING))
  128. return;
  129. HICON icon = CopyIcon(ci.hCursor);
  130. if (!icon)
  131. return;
  132. ICONINFO ii;
  133. if (GetIconInfo(icon, &ii)) {
  134. POINT win_pos{};
  135. if (window) {
  136. if (client_area) {
  137. ClientToScreen(window, &win_pos);
  138. } else {
  139. RECT window_rect;
  140. if (DwmGetWindowAttribute(
  141. window,
  142. DWMWA_EXTENDED_FRAME_BOUNDS,
  143. &window_rect,
  144. sizeof(window_rect)) ==
  145. S_OK) {
  146. win_pos.x = window_rect.left;
  147. win_pos.y = window_rect.top;
  148. }
  149. }
  150. }
  151. POINT pos;
  152. pos.x = ci.ptScreenPos.x - (int)ii.xHotspot - win_pos.x;
  153. pos.y = ci.ptScreenPos.y - (int)ii.yHotspot - win_pos.y;
  154. HDC hdc = (HDC)gs_texture_get_dc(texture);
  155. DrawIconEx(hdc, pos.x, pos.y, icon, 0, 0, 0, NULL,
  156. DI_NORMAL);
  157. gs_texture_release_dc(texture);
  158. DeleteObject(ii.hbmColor);
  159. DeleteObject(ii.hbmMask);
  160. }
  161. DestroyIcon(icon);
  162. }
  163. void
  164. on_closed(winrt::Windows::Graphics::Capture::GraphicsCaptureItem const
  165. &sender,
  166. winrt::Windows::Foundation::IInspectable const &)
  167. {
  168. active = FALSE;
  169. }
  170. void on_frame_arrived(winrt::Windows::Graphics::Capture::
  171. Direct3D11CaptureFramePool const &sender,
  172. winrt::Windows::Foundation::IInspectable const &)
  173. {
  174. obs_enter_graphics();
  175. const winrt::Windows::Graphics::Capture::Direct3D11CaptureFrame
  176. frame = sender.TryGetNextFrame();
  177. const winrt::Windows::Graphics::SizeInt32 frame_content_size =
  178. frame.ContentSize();
  179. winrt::com_ptr<ID3D11Texture2D> frame_surface =
  180. GetDXGIInterfaceFromObject<ID3D11Texture2D>(
  181. frame.Surface());
  182. /* need GetDesc because ContentSize is not reliable */
  183. D3D11_TEXTURE2D_DESC desc;
  184. frame_surface->GetDesc(&desc);
  185. client_box_available = false;
  186. if (client_area) {
  187. client_box_available = get_client_box(
  188. window, desc.Width, desc.Height, &client_box);
  189. }
  190. if (client_box_available) {
  191. texture_width = client_box.right - client_box.left;
  192. texture_height = client_box.bottom - client_box.top;
  193. } else {
  194. texture_width = desc.Width;
  195. texture_height = desc.Height;
  196. }
  197. if (texture) {
  198. if (texture_width != gs_texture_get_width(texture) ||
  199. texture_height != gs_texture_get_height(texture)) {
  200. gs_texture_destroy(texture);
  201. texture = nullptr;
  202. }
  203. }
  204. if (!texture) {
  205. texture = gs_texture_create_gdi(texture_width,
  206. texture_height);
  207. }
  208. if (client_box_available) {
  209. context->CopySubresourceRegion(
  210. (ID3D11Texture2D *)gs_texture_get_obj(texture),
  211. 0, 0, 0, 0, frame_surface.get(), 0,
  212. &client_box);
  213. } else {
  214. /* if they gave an SRV, we could avoid this copy */
  215. context->CopyResource(
  216. (ID3D11Texture2D *)gs_texture_get_obj(texture),
  217. frame_surface.get());
  218. }
  219. if (capture_cursor && cursor_visible) {
  220. draw_cursor();
  221. }
  222. texture_written = true;
  223. if (frame_content_size.Width != last_size.Width ||
  224. frame_content_size.Height != last_size.Height) {
  225. frame_pool.Recreate(
  226. device,
  227. winrt::Windows::Graphics::DirectX::
  228. DirectXPixelFormat::B8G8R8A8UIntNormalized,
  229. 2, frame_content_size);
  230. last_size = frame_content_size;
  231. }
  232. obs_leave_graphics();
  233. }
  234. };
  235. struct winrt_capture *capture_list;
  236. static void winrt_capture_device_loss_release(void *data)
  237. {
  238. winrt_capture *capture = static_cast<winrt_capture *>(data);
  239. capture->frame_arrived.revoke();
  240. capture->frame_pool.Close();
  241. capture->session.Close();
  242. capture->session = nullptr;
  243. capture->frame_pool = nullptr;
  244. capture->context = nullptr;
  245. capture->device = nullptr;
  246. }
  247. static void winrt_capture_device_loss_rebuild(void *device_void, void *data)
  248. {
  249. winrt_capture *capture = static_cast<winrt_capture *>(data);
  250. ID3D11Device *const d3d_device = (ID3D11Device *)device_void;
  251. ComPtr<IDXGIDevice> dxgi_device;
  252. if (FAILED(d3d_device->QueryInterface(&dxgi_device)))
  253. blog(LOG_ERROR, "Failed to get DXGI device");
  254. winrt::com_ptr<IInspectable> inspectable;
  255. if (FAILED(CreateDirect3D11DeviceFromDXGIDevice(dxgi_device.Get(),
  256. inspectable.put())))
  257. blog(LOG_ERROR, "Failed to get WinRT device");
  258. const winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice
  259. device = inspectable.as<winrt::Windows::Graphics::DirectX::
  260. Direct3D11::IDirect3DDevice>();
  261. const winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool
  262. frame_pool = winrt::Windows::Graphics::Capture::
  263. Direct3D11CaptureFramePool::Create(
  264. device,
  265. winrt::Windows::Graphics::DirectX::
  266. DirectXPixelFormat::B8G8R8A8UIntNormalized,
  267. 2, capture->last_size);
  268. const winrt::Windows::Graphics::Capture::GraphicsCaptureSession session =
  269. frame_pool.CreateCaptureSession(capture->item);
  270. /* disable cursor capture if possible since ours performs better */
  271. #ifdef NTDDI_WIN10_VB
  272. if (winrt_capture_cursor_toggle_supported())
  273. session.IsCursorCaptureEnabled(false);
  274. #endif
  275. capture->device = device;
  276. d3d_device->GetImmediateContext(&capture->context);
  277. capture->frame_pool = frame_pool;
  278. capture->session = session;
  279. capture->frame_arrived = frame_pool.FrameArrived(
  280. winrt::auto_revoke,
  281. {capture, &winrt_capture::on_frame_arrived});
  282. session.StartCapture();
  283. }
  284. thread_local bool initialized_tls;
  285. extern "C" EXPORT struct winrt_capture *
  286. winrt_capture_init(BOOL cursor, HWND window, BOOL client_area)
  287. try {
  288. ID3D11Device *const d3d_device = (ID3D11Device *)gs_get_device_obj();
  289. ComPtr<IDXGIDevice> dxgi_device;
  290. HRESULT hr = d3d_device->QueryInterface(&dxgi_device);
  291. if (FAILED(hr)) {
  292. blog(LOG_ERROR, "Failed to get DXGI device");
  293. return nullptr;
  294. }
  295. winrt::com_ptr<IInspectable> inspectable;
  296. hr = CreateDirect3D11DeviceFromDXGIDevice(dxgi_device.Get(),
  297. inspectable.put());
  298. if (FAILED(hr)) {
  299. blog(LOG_ERROR, "Failed to get WinRT device");
  300. return nullptr;
  301. }
  302. auto activation_factory = winrt::get_activation_factory<
  303. winrt::Windows::Graphics::Capture::GraphicsCaptureItem>();
  304. auto interop_factory =
  305. activation_factory.as<IGraphicsCaptureItemInterop>();
  306. winrt::Windows::Graphics::Capture::GraphicsCaptureItem item = {nullptr};
  307. try {
  308. interop_factory->CreateForWindow(
  309. window,
  310. winrt::guid_of<ABI::Windows::Graphics::Capture::
  311. IGraphicsCaptureItem>(),
  312. reinterpret_cast<void **>(winrt::put_abi(item)));
  313. } catch (winrt::hresult_error &err) {
  314. blog(LOG_ERROR, "CreateForWindow (0x%08X): %ls", err.to_abi(),
  315. err.message().c_str());
  316. return nullptr;
  317. } catch (...) {
  318. blog(LOG_ERROR, "CreateForWindow (0x%08X)",
  319. winrt::to_hresult());
  320. return nullptr;
  321. }
  322. const winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice
  323. device = inspectable.as<winrt::Windows::Graphics::DirectX::
  324. Direct3D11::IDirect3DDevice>();
  325. const winrt::Windows::Graphics::SizeInt32 size = item.Size();
  326. const winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool
  327. frame_pool = winrt::Windows::Graphics::Capture::
  328. Direct3D11CaptureFramePool::Create(
  329. device,
  330. winrt::Windows::Graphics::DirectX::
  331. DirectXPixelFormat::B8G8R8A8UIntNormalized,
  332. 2, size);
  333. const winrt::Windows::Graphics::Capture::GraphicsCaptureSession session =
  334. frame_pool.CreateCaptureSession(item);
  335. /* disable cursor capture if possible since ours performs better */
  336. const BOOL cursor_toggle_supported =
  337. winrt_capture_cursor_toggle_supported();
  338. #ifdef NTDDI_WIN10_VB
  339. if (cursor_toggle_supported)
  340. session.IsCursorCaptureEnabled(false);
  341. #endif
  342. if (capture_list == nullptr)
  343. initialized_tls = true;
  344. struct winrt_capture *capture = new winrt_capture{};
  345. capture->window = window;
  346. capture->client_area = client_area;
  347. capture->capture_cursor = cursor && cursor_toggle_supported;
  348. capture->item = item;
  349. capture->device = device;
  350. d3d_device->GetImmediateContext(&capture->context);
  351. capture->frame_pool = frame_pool;
  352. capture->session = session;
  353. capture->last_size = size;
  354. capture->closed = item.Closed(winrt::auto_revoke,
  355. {capture, &winrt_capture::on_closed});
  356. capture->frame_arrived = frame_pool.FrameArrived(
  357. winrt::auto_revoke,
  358. {capture, &winrt_capture::on_frame_arrived});
  359. capture->active = TRUE;
  360. capture->next = capture_list;
  361. capture_list = capture;
  362. session.StartCapture();
  363. gs_device_loss callbacks;
  364. callbacks.device_loss_release = winrt_capture_device_loss_release;
  365. callbacks.device_loss_rebuild = winrt_capture_device_loss_rebuild;
  366. callbacks.data = capture;
  367. gs_register_loss_callbacks(&callbacks);
  368. return capture;
  369. } catch (const winrt::hresult_error &err) {
  370. blog(LOG_ERROR, "winrt_capture_init (0x%08X): %ls", err.to_abi(),
  371. err.message().c_str());
  372. return nullptr;
  373. } catch (...) {
  374. blog(LOG_ERROR, "winrt_capture_init (0x%08X)", winrt::to_hresult());
  375. return nullptr;
  376. }
  377. extern "C" EXPORT void winrt_capture_free(struct winrt_capture *capture)
  378. {
  379. if (capture) {
  380. struct winrt_capture *current = capture_list;
  381. if (current == capture) {
  382. capture_list = capture->next;
  383. } else {
  384. struct winrt_capture *previous;
  385. do {
  386. previous = current;
  387. current = current->next;
  388. } while (current != capture);
  389. previous->next = current->next;
  390. }
  391. obs_enter_graphics();
  392. gs_unregister_loss_callbacks(capture);
  393. gs_texture_destroy(capture->texture);
  394. obs_leave_graphics();
  395. capture->frame_arrived.revoke();
  396. capture->closed.revoke();
  397. capture->frame_pool.Close();
  398. capture->session.Close();
  399. delete capture;
  400. }
  401. }
  402. static void draw_texture(struct winrt_capture *capture, gs_effect_t *effect)
  403. {
  404. gs_texture_t *const texture = capture->texture;
  405. gs_technique_t *tech = gs_effect_get_technique(effect, "Draw");
  406. gs_eparam_t *image = gs_effect_get_param_by_name(effect, "image");
  407. size_t passes;
  408. gs_effect_set_texture(image, texture);
  409. passes = gs_technique_begin(tech);
  410. for (size_t i = 0; i < passes; i++) {
  411. if (gs_technique_begin_pass(tech, i)) {
  412. gs_draw_sprite(texture, 0, 0, 0);
  413. gs_technique_end_pass(tech);
  414. }
  415. }
  416. gs_technique_end(tech);
  417. }
  418. extern "C" EXPORT BOOL winrt_capture_active(const struct winrt_capture *capture)
  419. {
  420. return capture->active;
  421. }
  422. extern "C" EXPORT void winrt_capture_show_cursor(struct winrt_capture *capture,
  423. BOOL visible)
  424. {
  425. capture->cursor_visible = visible;
  426. }
  427. extern "C" EXPORT void winrt_capture_render(struct winrt_capture *capture,
  428. gs_effect_t *effect)
  429. {
  430. if (capture->texture_written) {
  431. if (!initialized_tls) {
  432. struct winrt_capture *current = capture_list;
  433. while (current) {
  434. current->thread_changed = true;
  435. current = current->next;
  436. }
  437. initialized_tls = true;
  438. }
  439. if (capture->thread_changed) {
  440. /* new graphics thread. treat like device loss. */
  441. winrt_capture_device_loss_release(capture);
  442. winrt_capture_device_loss_rebuild(gs_get_device_obj(),
  443. capture);
  444. capture->thread_changed = false;
  445. }
  446. draw_texture(capture, effect);
  447. }
  448. }
  449. extern "C" EXPORT uint32_t
  450. winrt_capture_width(const struct winrt_capture *capture)
  451. {
  452. return capture ? capture->texture_width : 0;
  453. }
  454. extern "C" EXPORT uint32_t
  455. winrt_capture_height(const struct winrt_capture *capture)
  456. {
  457. return capture ? capture->texture_height : 0;
  458. }