winrt-capture.cpp 13 KB

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