winrt-capture.cpp 16 KB

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