winrt-capture.cpp 14 KB

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