winrt-capture.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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 on_closed(
  121. winrt::Windows::Graphics::Capture::GraphicsCaptureItem const &,
  122. winrt::Windows::Foundation::IInspectable const &)
  123. {
  124. active = FALSE;
  125. }
  126. void on_frame_arrived(winrt::Windows::Graphics::Capture::
  127. Direct3D11CaptureFramePool const &sender,
  128. winrt::Windows::Foundation::IInspectable const &)
  129. {
  130. obs_enter_graphics();
  131. const winrt::Windows::Graphics::Capture::Direct3D11CaptureFrame
  132. frame = sender.TryGetNextFrame();
  133. const winrt::Windows::Graphics::SizeInt32 frame_content_size =
  134. frame.ContentSize();
  135. winrt::com_ptr<ID3D11Texture2D> frame_surface =
  136. GetDXGIInterfaceFromObject<ID3D11Texture2D>(
  137. frame.Surface());
  138. /* need GetDesc because ContentSize is not reliable */
  139. D3D11_TEXTURE2D_DESC desc;
  140. frame_surface->GetDesc(&desc);
  141. if (!client_area || get_client_box(window, desc.Width,
  142. desc.Height, &client_box)) {
  143. if (client_area) {
  144. texture_width =
  145. client_box.right - client_box.left;
  146. texture_height =
  147. client_box.bottom - client_box.top;
  148. } else {
  149. texture_width = desc.Width;
  150. texture_height = desc.Height;
  151. }
  152. if (texture) {
  153. if (texture_width !=
  154. gs_texture_get_width(texture) ||
  155. texture_height !=
  156. gs_texture_get_height(texture)) {
  157. gs_texture_destroy(texture);
  158. texture = nullptr;
  159. }
  160. }
  161. if (!texture) {
  162. texture = gs_texture_create(texture_width,
  163. texture_height,
  164. GS_BGRA, 1, NULL,
  165. 0);
  166. }
  167. if (client_area) {
  168. context->CopySubresourceRegion(
  169. (ID3D11Texture2D *)gs_texture_get_obj(
  170. texture),
  171. 0, 0, 0, 0, frame_surface.get(), 0,
  172. &client_box);
  173. } else {
  174. /* if they gave an SRV, we could avoid this copy */
  175. context->CopyResource(
  176. (ID3D11Texture2D *)gs_texture_get_obj(
  177. texture),
  178. frame_surface.get());
  179. }
  180. texture_written = true;
  181. }
  182. if (frame_content_size.Width != last_size.Width ||
  183. frame_content_size.Height != last_size.Height) {
  184. frame_pool.Recreate(
  185. device,
  186. winrt::Windows::Graphics::DirectX::
  187. DirectXPixelFormat::B8G8R8A8UIntNormalized,
  188. 2, frame_content_size);
  189. last_size = frame_content_size;
  190. }
  191. obs_leave_graphics();
  192. }
  193. };
  194. static struct winrt_capture *capture_list;
  195. static void winrt_capture_device_loss_release(void *data)
  196. {
  197. winrt_capture *capture = static_cast<winrt_capture *>(data);
  198. capture->active = FALSE;
  199. capture->frame_arrived.revoke();
  200. capture->frame_pool.Close();
  201. capture->session.Close();
  202. capture->session = nullptr;
  203. capture->frame_pool = nullptr;
  204. capture->context = nullptr;
  205. capture->device = nullptr;
  206. capture->item = nullptr;
  207. }
  208. #ifdef NTDDI_WIN10_FE
  209. static bool winrt_capture_border_toggle_supported()
  210. try {
  211. return winrt::Windows::Foundation::Metadata::ApiInformation::
  212. IsPropertyPresent(
  213. L"Windows.Graphics.Capture.GraphicsCaptureSession",
  214. L"IsBorderRequired");
  215. } catch (const winrt::hresult_error &err) {
  216. blog(LOG_ERROR, "winrt_capture_border_toggle_supported (0x%08X): %ls",
  217. err.to_abi(), err.message().c_str());
  218. return false;
  219. } catch (...) {
  220. blog(LOG_ERROR, "winrt_capture_border_toggle_supported (0x%08X)",
  221. winrt::to_hresult());
  222. return false;
  223. }
  224. #endif
  225. static void winrt_capture_device_loss_rebuild(void *device_void, void *data)
  226. {
  227. winrt_capture *capture = static_cast<winrt_capture *>(data);
  228. auto activation_factory = winrt::get_activation_factory<
  229. winrt::Windows::Graphics::Capture::GraphicsCaptureItem>();
  230. auto interop_factory =
  231. activation_factory.as<IGraphicsCaptureItemInterop>();
  232. winrt::Windows::Graphics::Capture::GraphicsCaptureItem item = {nullptr};
  233. try {
  234. interop_factory->CreateForWindow(
  235. capture->window,
  236. winrt::guid_of<ABI::Windows::Graphics::Capture::
  237. IGraphicsCaptureItem>(),
  238. reinterpret_cast<void **>(winrt::put_abi(item)));
  239. } catch (winrt::hresult_error &err) {
  240. blog(LOG_ERROR, "CreateForWindow (0x%08X): %ls", err.to_abi(),
  241. err.message().c_str());
  242. } catch (...) {
  243. blog(LOG_ERROR, "CreateForWindow (0x%08X)",
  244. winrt::to_hresult());
  245. }
  246. ID3D11Device *const d3d_device = (ID3D11Device *)device_void;
  247. ComPtr<IDXGIDevice> dxgi_device;
  248. if (FAILED(d3d_device->QueryInterface(&dxgi_device)))
  249. blog(LOG_ERROR, "Failed to get DXGI device");
  250. winrt::com_ptr<IInspectable> inspectable;
  251. if (FAILED(CreateDirect3D11DeviceFromDXGIDevice(dxgi_device.Get(),
  252. inspectable.put())))
  253. blog(LOG_ERROR, "Failed to get WinRT device");
  254. const winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice
  255. device = inspectable.as<winrt::Windows::Graphics::DirectX::
  256. Direct3D11::IDirect3DDevice>();
  257. const winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool
  258. frame_pool = winrt::Windows::Graphics::Capture::
  259. Direct3D11CaptureFramePool::Create(
  260. device,
  261. winrt::Windows::Graphics::DirectX::
  262. DirectXPixelFormat::B8G8R8A8UIntNormalized,
  263. 2, capture->last_size);
  264. const winrt::Windows::Graphics::Capture::GraphicsCaptureSession session =
  265. frame_pool.CreateCaptureSession(item);
  266. #ifdef NTDDI_WIN10_FE
  267. if (winrt_capture_border_toggle_supported()) {
  268. winrt::Windows::Graphics::Capture::GraphicsCaptureAccess::
  269. RequestAccessAsync(
  270. winrt::Windows::Graphics::Capture::
  271. GraphicsCaptureAccessKind::Borderless)
  272. .get();
  273. session.IsBorderRequired(false);
  274. }
  275. #endif
  276. if (winrt_capture_cursor_toggle_supported())
  277. session.IsCursorCaptureEnabled(capture->capture_cursor &&
  278. capture->cursor_visible);
  279. capture->item = item;
  280. capture->device = device;
  281. d3d_device->GetImmediateContext(&capture->context);
  282. capture->frame_pool = frame_pool;
  283. capture->session = session;
  284. capture->frame_arrived = frame_pool.FrameArrived(
  285. winrt::auto_revoke,
  286. {capture, &winrt_capture::on_frame_arrived});
  287. try {
  288. session.StartCapture();
  289. capture->active = TRUE;
  290. } catch (winrt::hresult_error &err) {
  291. blog(LOG_ERROR, "StartCapture (0x%08X): %ls", err.to_abi(),
  292. err.message().c_str());
  293. } catch (...) {
  294. blog(LOG_ERROR, "StartCapture (0x%08X)", winrt::to_hresult());
  295. }
  296. }
  297. extern "C" EXPORT struct winrt_capture *
  298. winrt_capture_init(BOOL cursor, HWND window, BOOL client_area)
  299. try {
  300. ID3D11Device *const d3d_device = (ID3D11Device *)gs_get_device_obj();
  301. ComPtr<IDXGIDevice> dxgi_device;
  302. HRESULT hr = d3d_device->QueryInterface(&dxgi_device);
  303. if (FAILED(hr)) {
  304. blog(LOG_ERROR, "Failed to get DXGI device");
  305. return nullptr;
  306. }
  307. winrt::com_ptr<IInspectable> inspectable;
  308. hr = CreateDirect3D11DeviceFromDXGIDevice(dxgi_device.Get(),
  309. inspectable.put());
  310. if (FAILED(hr)) {
  311. blog(LOG_ERROR, "Failed to get WinRT device");
  312. return nullptr;
  313. }
  314. auto activation_factory = winrt::get_activation_factory<
  315. winrt::Windows::Graphics::Capture::GraphicsCaptureItem>();
  316. auto interop_factory =
  317. activation_factory.as<IGraphicsCaptureItemInterop>();
  318. winrt::Windows::Graphics::Capture::GraphicsCaptureItem item = {nullptr};
  319. try {
  320. hr = interop_factory->CreateForWindow(
  321. window,
  322. winrt::guid_of<ABI::Windows::Graphics::Capture::
  323. IGraphicsCaptureItem>(),
  324. reinterpret_cast<void **>(winrt::put_abi(item)));
  325. if (FAILED(hr)) {
  326. blog(LOG_ERROR, "CreateForWindow (0x%08X)", hr);
  327. return nullptr;
  328. }
  329. } catch (winrt::hresult_error &err) {
  330. blog(LOG_ERROR, "CreateForWindow (0x%08X): %ls", err.to_abi(),
  331. err.message().c_str());
  332. return nullptr;
  333. } catch (...) {
  334. blog(LOG_ERROR, "CreateForWindow (0x%08X)",
  335. winrt::to_hresult());
  336. return nullptr;
  337. }
  338. const winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice
  339. device = inspectable.as<winrt::Windows::Graphics::DirectX::
  340. Direct3D11::IDirect3DDevice>();
  341. const winrt::Windows::Graphics::SizeInt32 size = item.Size();
  342. const winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool
  343. frame_pool = winrt::Windows::Graphics::Capture::
  344. Direct3D11CaptureFramePool::Create(
  345. device,
  346. winrt::Windows::Graphics::DirectX::
  347. DirectXPixelFormat::B8G8R8A8UIntNormalized,
  348. 2, size);
  349. const winrt::Windows::Graphics::Capture::GraphicsCaptureSession session =
  350. frame_pool.CreateCaptureSession(item);
  351. #ifdef NTDDI_WIN10_FE
  352. if (winrt_capture_border_toggle_supported()) {
  353. winrt::Windows::Graphics::Capture::GraphicsCaptureAccess::
  354. RequestAccessAsync(
  355. winrt::Windows::Graphics::Capture::
  356. GraphicsCaptureAccessKind::Borderless)
  357. .get();
  358. session.IsBorderRequired(false);
  359. }
  360. #endif
  361. /* disable cursor capture if possible since ours performs better */
  362. const BOOL cursor_toggle_supported =
  363. winrt_capture_cursor_toggle_supported();
  364. if (cursor_toggle_supported)
  365. session.IsCursorCaptureEnabled(cursor);
  366. struct winrt_capture *capture = new winrt_capture{};
  367. capture->window = window;
  368. capture->client_area = client_area;
  369. capture->capture_cursor = cursor && cursor_toggle_supported;
  370. capture->cursor_visible = cursor;
  371. capture->item = item;
  372. capture->device = device;
  373. d3d_device->GetImmediateContext(&capture->context);
  374. capture->frame_pool = frame_pool;
  375. capture->session = session;
  376. capture->last_size = size;
  377. capture->closed = item.Closed(winrt::auto_revoke,
  378. {capture, &winrt_capture::on_closed});
  379. capture->frame_arrived = frame_pool.FrameArrived(
  380. winrt::auto_revoke,
  381. {capture, &winrt_capture::on_frame_arrived});
  382. capture->next = capture_list;
  383. capture_list = capture;
  384. session.StartCapture();
  385. capture->active = TRUE;
  386. gs_device_loss callbacks;
  387. callbacks.device_loss_release = winrt_capture_device_loss_release;
  388. callbacks.device_loss_rebuild = winrt_capture_device_loss_rebuild;
  389. callbacks.data = capture;
  390. gs_register_loss_callbacks(&callbacks);
  391. return capture;
  392. } catch (const winrt::hresult_error &err) {
  393. blog(LOG_ERROR, "winrt_capture_init (0x%08X): %ls", err.to_abi(),
  394. err.message().c_str());
  395. return nullptr;
  396. } catch (...) {
  397. blog(LOG_ERROR, "winrt_capture_init (0x%08X)", winrt::to_hresult());
  398. return nullptr;
  399. }
  400. extern "C" EXPORT void winrt_capture_free(struct winrt_capture *capture)
  401. {
  402. if (capture) {
  403. struct winrt_capture *current = capture_list;
  404. if (current == capture) {
  405. capture_list = capture->next;
  406. } else {
  407. struct winrt_capture *previous;
  408. do {
  409. previous = current;
  410. current = current->next;
  411. } while (current != capture);
  412. previous->next = current->next;
  413. }
  414. obs_enter_graphics();
  415. gs_unregister_loss_callbacks(capture);
  416. gs_texture_destroy(capture->texture);
  417. obs_leave_graphics();
  418. capture->frame_arrived.revoke();
  419. capture->closed.revoke();
  420. capture->frame_pool.Close();
  421. capture->session.Close();
  422. delete capture;
  423. }
  424. }
  425. static void draw_texture(struct winrt_capture *capture, gs_effect_t *effect)
  426. {
  427. gs_texture_t *const texture = capture->texture;
  428. gs_technique_t *tech = gs_effect_get_technique(effect, "Draw");
  429. gs_eparam_t *image = gs_effect_get_param_by_name(effect, "image");
  430. size_t passes;
  431. const bool linear_srgb = gs_get_linear_srgb();
  432. const bool previous = gs_framebuffer_srgb_enabled();
  433. gs_enable_framebuffer_srgb(linear_srgb);
  434. if (linear_srgb)
  435. gs_effect_set_texture_srgb(image, texture);
  436. else
  437. gs_effect_set_texture(image, texture);
  438. passes = gs_technique_begin(tech);
  439. for (size_t i = 0; i < passes; i++) {
  440. if (gs_technique_begin_pass(tech, i)) {
  441. gs_draw_sprite(texture, 0, 0, 0);
  442. gs_technique_end_pass(tech);
  443. }
  444. }
  445. gs_technique_end(tech);
  446. gs_enable_framebuffer_srgb(previous);
  447. }
  448. extern "C" EXPORT BOOL winrt_capture_active(const struct winrt_capture *capture)
  449. {
  450. return capture->active;
  451. }
  452. extern "C" EXPORT void winrt_capture_show_cursor(struct winrt_capture *capture,
  453. BOOL visible)
  454. {
  455. if (capture->capture_cursor) {
  456. if (capture->cursor_visible != visible) {
  457. capture->session.IsCursorCaptureEnabled(visible);
  458. capture->cursor_visible = visible;
  459. }
  460. }
  461. }
  462. extern "C" EXPORT void winrt_capture_render(struct winrt_capture *capture,
  463. gs_effect_t *effect)
  464. {
  465. if (capture->texture_written)
  466. draw_texture(capture, effect);
  467. }
  468. extern "C" EXPORT uint32_t
  469. winrt_capture_width(const struct winrt_capture *capture)
  470. {
  471. return capture ? capture->texture_width : 0;
  472. }
  473. extern "C" EXPORT uint32_t
  474. winrt_capture_height(const struct winrt_capture *capture)
  475. {
  476. return capture ? capture->texture_height : 0;
  477. }
  478. extern "C" EXPORT void winrt_capture_thread_start()
  479. {
  480. struct winrt_capture *capture = capture_list;
  481. void *const device = gs_get_device_obj();
  482. while (capture) {
  483. winrt_capture_device_loss_rebuild(device, capture);
  484. capture = capture->next;
  485. }
  486. }
  487. extern "C" EXPORT void winrt_capture_thread_stop()
  488. {
  489. struct winrt_capture *capture = capture_list;
  490. while (capture) {
  491. winrt_capture_device_loss_release(capture);
  492. capture = capture->next;
  493. }
  494. }