winrt-capture.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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::Direct3D11CaptureFramePool::
  111. FrameArrived_revoker frame_arrived;
  112. uint32_t texture_width;
  113. uint32_t texture_height;
  114. D3D11_BOX client_box;
  115. bool client_box_available;
  116. bool thread_changed;
  117. struct winrt_capture *next;
  118. void draw_cursor()
  119. {
  120. CURSORINFO ci{};
  121. ci.cbSize = sizeof(CURSORINFO);
  122. if (!GetCursorInfo(&ci))
  123. return;
  124. if (!(ci.flags & CURSOR_SHOWING))
  125. return;
  126. HICON icon = CopyIcon(ci.hCursor);
  127. if (!icon)
  128. return;
  129. ICONINFO ii;
  130. if (GetIconInfo(icon, &ii)) {
  131. POINT win_pos{};
  132. if (window) {
  133. if (client_area) {
  134. ClientToScreen(window, &win_pos);
  135. } else {
  136. RECT window_rect;
  137. if (DwmGetWindowAttribute(
  138. window,
  139. DWMWA_EXTENDED_FRAME_BOUNDS,
  140. &window_rect,
  141. sizeof(window_rect)) ==
  142. S_OK) {
  143. win_pos.x = window_rect.left;
  144. win_pos.y = window_rect.top;
  145. }
  146. }
  147. }
  148. POINT pos;
  149. pos.x = ci.ptScreenPos.x - (int)ii.xHotspot - win_pos.x;
  150. pos.y = ci.ptScreenPos.y - (int)ii.yHotspot - win_pos.y;
  151. HDC hdc = (HDC)gs_texture_get_dc(texture);
  152. DrawIconEx(hdc, pos.x, pos.y, icon, 0, 0, 0, NULL,
  153. DI_NORMAL);
  154. gs_texture_release_dc(texture);
  155. DeleteObject(ii.hbmColor);
  156. DeleteObject(ii.hbmMask);
  157. }
  158. DestroyIcon(icon);
  159. }
  160. void on_frame_arrived(winrt::Windows::Graphics::Capture::
  161. Direct3D11CaptureFramePool const &sender,
  162. winrt::Windows::Foundation::IInspectable const &)
  163. {
  164. obs_enter_graphics();
  165. const winrt::Windows::Graphics::Capture::Direct3D11CaptureFrame
  166. frame = sender.TryGetNextFrame();
  167. const winrt::Windows::Graphics::SizeInt32 frame_content_size =
  168. frame.ContentSize();
  169. winrt::com_ptr<ID3D11Texture2D> frame_surface =
  170. GetDXGIInterfaceFromObject<ID3D11Texture2D>(
  171. frame.Surface());
  172. /* need GetDesc because ContentSize is not reliable */
  173. D3D11_TEXTURE2D_DESC desc;
  174. frame_surface->GetDesc(&desc);
  175. client_box_available = false;
  176. if (client_area) {
  177. client_box_available = get_client_box(
  178. window, desc.Width, desc.Height, &client_box);
  179. }
  180. if (client_box_available) {
  181. texture_width = client_box.right - client_box.left;
  182. texture_height = client_box.bottom - client_box.top;
  183. } else {
  184. texture_width = desc.Width;
  185. texture_height = desc.Height;
  186. }
  187. if (texture) {
  188. if (texture_width != gs_texture_get_width(texture) ||
  189. texture_height != gs_texture_get_height(texture)) {
  190. gs_texture_destroy(texture);
  191. texture = nullptr;
  192. }
  193. }
  194. if (!texture) {
  195. texture = gs_texture_create_gdi(texture_width,
  196. texture_height);
  197. }
  198. if (client_box_available) {
  199. context->CopySubresourceRegion(
  200. (ID3D11Texture2D *)gs_texture_get_obj(texture),
  201. 0, 0, 0, 0, frame_surface.get(), 0,
  202. &client_box);
  203. } else {
  204. /* if they gave an SRV, we could avoid this copy */
  205. context->CopyResource(
  206. (ID3D11Texture2D *)gs_texture_get_obj(texture),
  207. frame_surface.get());
  208. }
  209. if (capture_cursor && cursor_visible) {
  210. draw_cursor();
  211. }
  212. texture_written = true;
  213. if (frame_content_size.Width != last_size.Width ||
  214. frame_content_size.Height != last_size.Height) {
  215. frame_pool.Recreate(
  216. device,
  217. winrt::Windows::Graphics::DirectX::
  218. DirectXPixelFormat::B8G8R8A8UIntNormalized,
  219. 2, frame_content_size);
  220. last_size = frame_content_size;
  221. }
  222. obs_leave_graphics();
  223. }
  224. };
  225. struct winrt_capture *capture_list;
  226. static void winrt_capture_device_loss_release(void *data)
  227. {
  228. winrt_capture *capture = static_cast<winrt_capture *>(data);
  229. capture->frame_arrived.revoke();
  230. capture->frame_pool.Close();
  231. capture->session.Close();
  232. capture->session = nullptr;
  233. capture->frame_pool = nullptr;
  234. capture->context = nullptr;
  235. capture->device = nullptr;
  236. }
  237. static void winrt_capture_device_loss_rebuild(void *device_void, void *data)
  238. {
  239. winrt_capture *capture = static_cast<winrt_capture *>(data);
  240. ID3D11Device *const d3d_device = (ID3D11Device *)device_void;
  241. ComPtr<IDXGIDevice> dxgi_device;
  242. if (FAILED(d3d_device->QueryInterface(&dxgi_device)))
  243. blog(LOG_ERROR, "Failed to get DXGI device");
  244. winrt::com_ptr<IInspectable> inspectable;
  245. if (FAILED(CreateDirect3D11DeviceFromDXGIDevice(dxgi_device.Get(),
  246. inspectable.put())))
  247. blog(LOG_ERROR, "Failed to get WinRT device");
  248. const winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice
  249. device = inspectable.as<winrt::Windows::Graphics::DirectX::
  250. Direct3D11::IDirect3DDevice>();
  251. const winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool
  252. frame_pool = winrt::Windows::Graphics::Capture::
  253. Direct3D11CaptureFramePool::Create(
  254. device,
  255. winrt::Windows::Graphics::DirectX::
  256. DirectXPixelFormat::B8G8R8A8UIntNormalized,
  257. 2, capture->last_size);
  258. const winrt::Windows::Graphics::Capture::GraphicsCaptureSession session =
  259. frame_pool.CreateCaptureSession(capture->item);
  260. /* disable cursor capture if possible since ours performs better */
  261. #ifdef NTDDI_WIN10_VB
  262. if (winrt_capture_cursor_toggle_supported())
  263. session.IsCursorCaptureEnabled(false);
  264. #endif
  265. capture->device = device;
  266. d3d_device->GetImmediateContext(&capture->context);
  267. capture->frame_pool = frame_pool;
  268. capture->session = session;
  269. capture->frame_arrived = frame_pool.FrameArrived(
  270. winrt::auto_revoke,
  271. {capture, &winrt_capture::on_frame_arrived});
  272. session.StartCapture();
  273. }
  274. thread_local bool initialized_tls;
  275. extern "C" EXPORT struct winrt_capture *
  276. winrt_capture_init(BOOL cursor, HWND window, BOOL client_area)
  277. try {
  278. ID3D11Device *const d3d_device = (ID3D11Device *)gs_get_device_obj();
  279. ComPtr<IDXGIDevice> dxgi_device;
  280. HRESULT hr = d3d_device->QueryInterface(&dxgi_device);
  281. if (FAILED(hr)) {
  282. blog(LOG_ERROR, "Failed to get DXGI device");
  283. return nullptr;
  284. }
  285. winrt::com_ptr<IInspectable> inspectable;
  286. hr = CreateDirect3D11DeviceFromDXGIDevice(dxgi_device.Get(),
  287. inspectable.put());
  288. if (FAILED(hr)) {
  289. blog(LOG_ERROR, "Failed to get WinRT device");
  290. return nullptr;
  291. }
  292. auto activation_factory = winrt::get_activation_factory<
  293. winrt::Windows::Graphics::Capture::GraphicsCaptureItem>();
  294. auto interop_factory =
  295. activation_factory.as<IGraphicsCaptureItemInterop>();
  296. winrt::Windows::Graphics::Capture::GraphicsCaptureItem item = {nullptr};
  297. try {
  298. interop_factory->CreateForWindow(
  299. window,
  300. winrt::guid_of<ABI::Windows::Graphics::Capture::
  301. IGraphicsCaptureItem>(),
  302. reinterpret_cast<void **>(winrt::put_abi(item)));
  303. } catch (winrt::hresult_error &err) {
  304. blog(LOG_ERROR, "CreateForWindow (0x%08X): %ls", err.to_abi(),
  305. err.message().c_str());
  306. return nullptr;
  307. } catch (...) {
  308. blog(LOG_ERROR, "CreateForWindow (0x%08X)",
  309. winrt::to_hresult());
  310. return nullptr;
  311. }
  312. const winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice
  313. device = inspectable.as<winrt::Windows::Graphics::DirectX::
  314. Direct3D11::IDirect3DDevice>();
  315. const winrt::Windows::Graphics::SizeInt32 size = item.Size();
  316. const winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool
  317. frame_pool = winrt::Windows::Graphics::Capture::
  318. Direct3D11CaptureFramePool::Create(
  319. device,
  320. winrt::Windows::Graphics::DirectX::
  321. DirectXPixelFormat::B8G8R8A8UIntNormalized,
  322. 2, size);
  323. const winrt::Windows::Graphics::Capture::GraphicsCaptureSession session =
  324. frame_pool.CreateCaptureSession(item);
  325. /* disable cursor capture if possible since ours performs better */
  326. const BOOL cursor_toggle_supported =
  327. winrt_capture_cursor_toggle_supported();
  328. #ifdef NTDDI_WIN10_VB
  329. if (cursor_toggle_supported)
  330. session.IsCursorCaptureEnabled(false);
  331. #endif
  332. if (capture_list == nullptr)
  333. initialized_tls = true;
  334. struct winrt_capture *capture = new winrt_capture{};
  335. capture->window = window;
  336. capture->client_area = client_area;
  337. capture->capture_cursor = cursor && cursor_toggle_supported;
  338. capture->item = item;
  339. capture->device = device;
  340. d3d_device->GetImmediateContext(&capture->context);
  341. capture->frame_pool = frame_pool;
  342. capture->session = session;
  343. capture->last_size = size;
  344. capture->frame_arrived = frame_pool.FrameArrived(
  345. winrt::auto_revoke,
  346. {capture, &winrt_capture::on_frame_arrived});
  347. capture->next = capture_list;
  348. capture_list = capture;
  349. session.StartCapture();
  350. gs_device_loss callbacks;
  351. callbacks.device_loss_release = winrt_capture_device_loss_release;
  352. callbacks.device_loss_rebuild = winrt_capture_device_loss_rebuild;
  353. callbacks.data = capture;
  354. gs_register_loss_callbacks(&callbacks);
  355. return capture;
  356. } catch (const winrt::hresult_error &err) {
  357. blog(LOG_ERROR, "winrt_capture_init (0x%08X): %ls", err.to_abi(),
  358. err.message().c_str());
  359. return nullptr;
  360. } catch (...) {
  361. blog(LOG_ERROR, "winrt_capture_init (0x%08X)", winrt::to_hresult());
  362. return nullptr;
  363. }
  364. extern "C" EXPORT void winrt_capture_free(struct winrt_capture *capture)
  365. {
  366. if (capture) {
  367. struct winrt_capture *current = capture_list;
  368. if (current == capture) {
  369. capture_list = capture->next;
  370. } else {
  371. struct winrt_capture *previous;
  372. do {
  373. previous = current;
  374. current = current->next;
  375. } while (current != capture);
  376. previous->next = current->next;
  377. }
  378. obs_enter_graphics();
  379. gs_unregister_loss_callbacks(capture);
  380. gs_texture_destroy(capture->texture);
  381. obs_leave_graphics();
  382. capture->frame_arrived.revoke();
  383. capture->frame_pool.Close();
  384. capture->session.Close();
  385. delete capture;
  386. }
  387. }
  388. static void draw_texture(struct winrt_capture *capture, gs_effect_t *effect)
  389. {
  390. gs_texture_t *const texture = capture->texture;
  391. gs_technique_t *tech = gs_effect_get_technique(effect, "Draw");
  392. gs_eparam_t *image = gs_effect_get_param_by_name(effect, "image");
  393. size_t passes;
  394. gs_effect_set_texture(image, texture);
  395. passes = gs_technique_begin(tech);
  396. for (size_t i = 0; i < passes; i++) {
  397. if (gs_technique_begin_pass(tech, i)) {
  398. gs_draw_sprite(texture, 0, 0, 0);
  399. gs_technique_end_pass(tech);
  400. }
  401. }
  402. gs_technique_end(tech);
  403. }
  404. extern "C" EXPORT void winrt_capture_show_cursor(struct winrt_capture *capture,
  405. BOOL visible)
  406. {
  407. capture->cursor_visible = visible;
  408. }
  409. extern "C" EXPORT void winrt_capture_render(struct winrt_capture *capture,
  410. gs_effect_t *effect)
  411. {
  412. if (capture && capture->texture_written) {
  413. if (!initialized_tls) {
  414. struct winrt_capture *current = capture_list;
  415. while (current) {
  416. current->thread_changed = true;
  417. current = current->next;
  418. }
  419. initialized_tls = true;
  420. }
  421. if (capture->thread_changed) {
  422. /* new graphics thread. treat like device loss. */
  423. winrt_capture_device_loss_release(capture);
  424. winrt_capture_device_loss_rebuild(gs_get_device_obj(),
  425. capture);
  426. capture->thread_changed = false;
  427. }
  428. draw_texture(capture, effect);
  429. }
  430. }
  431. extern "C" EXPORT uint32_t
  432. winrt_capture_width(const struct winrt_capture *capture)
  433. {
  434. return capture ? capture->texture_width : 0;
  435. }
  436. extern "C" EXPORT uint32_t
  437. winrt_capture_height(const struct winrt_capture *capture)
  438. {
  439. return capture ? capture->texture_height : 0;
  440. }