24 #include <d3dcompiler.h>
25 #include <dispatcherqueue.h>
26 #include <windows.foundation.h>
27 #include <windows.graphics.capture.h>
28 #include <windows.graphics.capture.interop.h>
29 #include <windows.graphics.directx.direct3d11.h>
30 #if HAVE_IDIRECT3DDXGIINTERFACEACCESS
31 #include <windows.graphics.directx.direct3d11.interop.h>
51 #include <condition_variable>
57 #include <system_error>
59 #include <type_traits>
62 using namespace ABI::Windows::Foundation;
63 using namespace ABI::Windows::Graphics::Capture;
64 using namespace ABI::Windows::Graphics::DirectX::Direct3D11;
66 using Microsoft::WRL::ComPtr;
67 using ABI::Windows::Graphics::SizeInt32;
68 using ABI::Windows::Foundation::TimeSpan;
69 using ABI::Windows::Graphics::DirectX::DirectXPixelFormat;
71 #define TIMESPAN_RES 10000000
72 #define TIMESPAN_RES64 INT64_C(10000000)
74 #define CAPTURE_POOL_SIZE 2
80 #define CCTX(ctx) static_cast<GfxCaptureContext*>(ctx)
86 HRESULT (WINAPI *RoInitialize)(RO_INIT_TYPE initType);
87 void (WINAPI *RoUninitialize)(void);
88 HRESULT (WINAPI *RoGetActivationFactory)(HSTRING activatableClassId, REFIID
iid,
void **factory);
89 HRESULT (WINAPI *WindowsCreateStringReference)(PCWSTR sourceString, UINT32 length, HSTRING_HEADER *hstringHeader, HSTRING *
string);
92 HRESULT (WINAPI *DwmGetWindowAttribute)(HWND hwnd, DWORD dwAttribute, PVOID
pvAttribute, DWORD cbAttribute);
95 HRESULT (WINAPI *CreateDirect3D11DeviceFromDXGIDevice)(IDXGIDevice *dxgiDevice, IInspectable **
graphicsDevice);
101 DPI_AWARENESS_CONTEXT (WINAPI *SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT dpiContext);
107 HRESULT (WINAPI *D3DCompile)(LPCVOID pSrcData, SIZE_T
SrcDataSize, LPCSTR pSourceName,
const D3D10_SHADER_MACRO *pDefines, ID3DInclude *pInclude,
108 LPCSTR pEntrypoint, LPCSTR
pTarget, UINT Flags1, UINT Flags2, ID3DBlob **ppCode, ID3DBlob **ppErrorMsgs);
121 EventRegistrationToken frame_arrived_token { 0 };
122 EventRegistrationToken closed_token { 0 };
126 bool window_closed {
false };
127 uint64_t frame_seq { 0 };
129 SizeInt32 cap_size { 0, 0 };
130 RECT client_area_offsets { 0, 0, 0, 0 };
143 std::unique_ptr<GfxCaptureContextWgc>
wgc;
144 std::unique_ptr<GfxCaptureContextD3D>
d3d;
147 DWORD wgc_thread_id { 0 };
150 volatile int wgc_thread_init_res { INT_MAX };
152 volatile int wgc_thread_res { 0 };
155 HWND capture_hwnd {
nullptr };
156 HMONITOR capture_hmonitor {
nullptr };
170 template <
typename T>
172 HSTRING_HEADER hsheader = { 0 };
175 HRESULT hr =
ctx->fn.WindowsCreateStringReference(clsid, (UINT32)wcslen(clsid), &hsheader, &hs);
179 return ctx->fn.RoGetActivationFactory(hs, IID_PPV_ARGS(factory));
182 #define CHECK_HR(fcall, action) \
184 HRESULT fhr = fcall; \
186 av_log(avctx, AV_LOG_ERROR, #fcall " failed: 0x%08lX\n", fhr); \
190 #define CHECK_HR_RET(...) CHECK_HR((__VA_ARGS__), return AVERROR_EXTERNAL)
191 #define CHECK_HR_FAIL(...) CHECK_HR((__VA_ARGS__), ret = AVERROR_EXTERNAL; goto fail)
192 #define CHECK_HR_LOG(...) CHECK_HR((__VA_ARGS__), (void)0)
201 std::lock_guard
lock(wgctx->frame_arrived_mutex);
202 wgctx->frame_seq += 1;
204 wgctx->frame_arrived_cond.notify_one();
209 std::lock_guard
lock(wgctx->frame_arrived_mutex);
210 wgctx->window_closed =
true;
212 wgctx->frame_arrived_cond.notify_one();
219 std::unique_ptr<GfxCaptureContextWgc> &wgctx =
ctx->wgc;
221 if (wgctx->closed_token.value && wgctx->capture_item) {
222 CHECK_HR_LOG(wgctx->capture_item->remove_Closed(wgctx->closed_token));
223 wgctx->closed_token.value = 0;
226 if (wgctx->frame_arrived_token.value && wgctx->frame_pool) {
227 CHECK_HR_LOG(wgctx->frame_pool->remove_FrameArrived(wgctx->frame_arrived_token));
228 wgctx->frame_arrived_token.value = 0;
231 if (wgctx->capture_session) {
232 ComPtr<IClosable> closable;
233 if (SUCCEEDED(wgctx->capture_session.As(&closable))) {
240 if (wgctx->frame_pool) {
241 ComPtr<IClosable> closable;
242 if (SUCCEEDED(wgctx->frame_pool.As(&closable))) {
249 wgctx->capture_session.Reset();
250 wgctx->frame_pool.Reset();
251 wgctx->capture_item.Reset();
252 wgctx->d3d_device.Reset();
259 std::unique_ptr<GfxCaptureContextWgc> &wgctx =
ctx->wgc;
261 if (!
ctx->capture_hwnd) {
262 wgctx->client_area_offsets.left = 0;
263 wgctx->client_area_offsets.top = 0;
264 wgctx->client_area_offsets.right = 0;
265 wgctx->client_area_offsets.bottom = 0;
269 RECT client_rect = {};
270 RECT frame_bounds = {};
271 RECT window_rect = {};
273 if (IsIconic(
ctx->capture_hwnd)) {
278 if (!GetClientRect(
ctx->capture_hwnd, &client_rect)) {
284 if (!MapWindowPoints(
ctx->capture_hwnd,
nullptr, (POINT*)&client_rect, 2) && GetLastError()) {
289 if (FAILED(
ctx->fn.DwmGetWindowAttribute(
ctx->capture_hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, &frame_bounds,
sizeof(window_rect))))
292 if (!GetWindowRect(
ctx->capture_hwnd, &window_rect))
295 if (wgctx->cap_size.Width == frame_bounds.right - frame_bounds.left ||
296 wgctx->cap_size.Height == frame_bounds.bottom - frame_bounds.top) {
298 }
else if (wgctx->cap_size.Width == window_rect.right - window_rect.left ||
299 wgctx->cap_size.Height == window_rect.bottom - window_rect.top) {
301 frame_bounds = window_rect;
303 if ((frame_bounds.top == frame_bounds.bottom || frame_bounds.left == frame_bounds.right) &&
304 (window_rect.top == window_rect.bottom || window_rect.left == window_rect.right))
309 av_log(avctx,
AV_LOG_VERBOSE,
"Failed to get valid window rect, client area may be inaccurate\n");
313 wgctx->client_area_offsets.left =
FFMAX(client_rect.left - frame_bounds.left, 0);
314 wgctx->client_area_offsets.top =
FFMAX(client_rect.top - frame_bounds.top, 0);
315 wgctx->client_area_offsets.right =
FFMAX(frame_bounds.right - client_rect.right, 0);
316 wgctx->client_area_offsets.bottom =
FFMAX(frame_bounds.bottom - client_rect.bottom, 0);
318 av_log(avctx,
AV_LOG_DEBUG,
"Client area offsets: left=%ld top=%ld right=%ld bottom=%ld\n",
319 wgctx->client_area_offsets.left, wgctx->client_area_offsets.top,
320 wgctx->client_area_offsets.right, wgctx->client_area_offsets.bottom);
329 std::unique_ptr<GfxCaptureContextWgc> &wgctx =
ctx->wgc;
332 ComPtr<IDirect3D11CaptureFramePoolStatics2> frame_pool_statics;
333 ComPtr<ID3D11Device> d3d11_device =
ctx->device_hwctx->device;
334 ComPtr<ID3D10Multithread> d3d10_multithread;
335 ComPtr<IDXGIDevice> dxgi_device;
336 ComPtr<IGraphicsCaptureSession2> session2;
337 ComPtr<IGraphicsCaptureSession3> session3;
338 ComPtr<IGraphicsCaptureSession5> session5;
340 DirectXPixelFormat fmt = DirectXPixelFormat::DirectXPixelFormat_B8G8R8A8UIntNormalized;
342 fmt = DirectXPixelFormat::DirectXPixelFormat_R16G16B16A16Float;
344 CHECK_HR_RET(wgctx->capture_item->get_Size(&wgctx->cap_size));
350 d3d10_multithread->SetMultithreadProtected(TRUE);
353 CHECK_HR_RET(
ctx->fn.CreateDirect3D11DeviceFromDXGIDevice(dxgi_device.Get(), &wgctx->d3d_device));
355 CHECK_HR_RET(get_activation_factory<IDirect3D11CaptureFramePoolStatics2>(
ctx, RuntimeClass_Windows_Graphics_Capture_Direct3D11CaptureFramePool, &frame_pool_statics));
357 CHECK_HR_RET(wgctx->frame_pool->CreateCaptureSession(wgctx->capture_item.Get(), &wgctx->capture_session));
359 if (SUCCEEDED(wgctx->capture_session.As(&session2))) {
360 if (FAILED(session2->put_IsCursorCaptureEnabled(cctx->
capture_cursor))) {
367 if (SUCCEEDED(wgctx->capture_session.As(&session3))) {
369 if (FAILED(session3->put_IsBorderRequired(cctx->
display_border))) {
376 if (SUCCEEDED(wgctx->capture_session.As(&session5))) {
378 if (FAILED(session5->put_MinUpdateInterval(ivl))) {
379 av_log(avctx,
AV_LOG_WARNING,
"Failed setting minimum update interval, framerate may be limited\n");
382 av_log(avctx,
AV_LOG_WARNING,
"Setting minimum update interval unavailable, framerate may be limited\n");
385 wgctx->window_closed = 0;
388 create_cb_handler<ITypedEventHandler<GraphicsCaptureItem*,IInspectable*>, IGraphicsCaptureItem*, IInspectable*>(
389 [avctx,
ctx](
auto,
auto) {
390 av_log(avctx, AV_LOG_INFO,
"Capture item closed\n");
391 wgc_closed_handler(ctx->wgc);
393 }).Get(), &wgctx->closed_token));
396 create_cb_handler<ITypedEventHandler<Direct3D11CaptureFramePool*,IInspectable*>, IDirect3D11CaptureFramePool*, IInspectable*>(
397 [avctx,
ctx](
auto,
auto) {
398 av_log(avctx, AV_LOG_TRACE,
"Frame arrived\n");
399 wgc_frame_arrived_handler(ctx->wgc);
401 }).Get(), &wgctx->frame_arrived_token));
410 std::unique_ptr<GfxCaptureContextWgc> &wgctx =
ctx->wgc;
414 ComPtr<IGraphicsCaptureItemInterop> capture_item_interop;
415 CHECK_HR_RET(get_activation_factory<IGraphicsCaptureItemInterop>(
ctx, RuntimeClass_Windows_Graphics_Capture_GraphicsCaptureItem, &capture_item_interop));
417 if (
ctx->capture_hmonitor) {
418 hr = capture_item_interop->CreateForMonitor(
ctx->capture_hmonitor, IID_PPV_ARGS(&wgctx->capture_item));
420 av_log(avctx,
AV_LOG_ERROR,
"Failed to setup graphics capture for monitor (0x%08lX)\n", hr);
423 }
else if (
ctx->capture_hwnd) {
424 hr = capture_item_interop->CreateForWindow(
ctx->capture_hwnd, IID_PPV_ARGS(&wgctx->capture_item));
426 av_log(avctx,
AV_LOG_ERROR,
"Failed to setup graphics capture for window (0x%08lX)\n", hr);
437 hr =
ctx->wgc->capture_session->StartCapture();
439 av_log(avctx,
AV_LOG_ERROR,
"Failed to start graphics capture session (0x%08lX)\n", hr);
450 std::unique_ptr<GfxCaptureContextWgc> &wgctx =
ctx->wgc;
452 ComPtr<IDirect3DSurface> capture_surface;
453 ComPtr<IDirect3DDxgiInterfaceAccess> dxgi_interface_access;
454 ComPtr<ID3D11Texture2D> frame_texture;
457 CHECK_HR_RET(wgctx->frame_pool->TryGetNextFrame(&capture_frame));
465 DirectXPixelFormat fmt = DirectXPixelFormat::DirectXPixelFormat_B8G8R8A8UIntNormalized;
467 fmt = DirectXPixelFormat::DirectXPixelFormat_R16G16B16A16Float;
484 std::unique_ptr<GfxCaptureContextWgc> &wgctx =
ctx->wgc;
488 PeekMessage(&msg,
nullptr, 0, 0, PM_NOREMOVE);
490 DispatcherQueueOptions
options = { 0 };
491 options.dwSize =
sizeof(DispatcherQueueOptions);
492 options.threadType = DISPATCHERQUEUE_THREAD_TYPE::DQTYPE_THREAD_CURRENT;
493 options.apartmentType = DISPATCHERQUEUE_THREAD_APARTMENTTYPE::DQTAT_COM_NONE;
496 CHECK_HR_RET(wgctx->dispatcher_queue_controller->get_DispatcherQueue(&wgctx->dispatcher_queue));
509 ctx->fn.RoUninitialize();
519 ctx->wgc = std::make_unique<GfxCaptureContextWgc>();
521 ctx->fn.SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
523 hr =
ctx->fn.RoInitialize(RO_INIT_MULTITHREADED);
553 std::unique_ptr<GfxCaptureContextWgc> &wgctx =
ctx->wgc;
554 ComPtr<IAsyncAction> async;
559 while (BOOL res = GetMessage(&msg,
NULL, 0, 0)) {
570 if (FAILED(wgctx->dispatcher_queue_controller->ShutdownQueueAsync(&async))) {
574 async->put_Completed(create_cb_handler<IAsyncActionCompletedHandler, IAsyncAction*, AsyncStatus>(
576 PostThreadMessage(
ctx->wgc_thread_id, WM_QUIT, 0, 0);
585 TranslateMessage(&msg);
586 DispatchMessage(&msg);
590 av_log(avctx,
AV_LOG_ERROR,
"WGC Thread message loop ended without proper shutdown\n");
605 static const wchar_t name_prefix[] =
L"wgc_winrt@0x";
606 wchar_t thread_name[
FF_ARRAY_ELEMS(name_prefix) +
sizeof(
void*) * 2] = { 0 };
607 swprintf(thread_name,
FF_ARRAY_ELEMS(thread_name),
L"%ls%" PRIxPTR, name_prefix, (uintptr_t)avctx);
608 ctx->fn.SetThreadDescription(GetCurrentThread(), thread_name);
610 std::lock_guard init_lock(
ctx->wgc_thread_init_mutex);
611 ctx->wgc_thread_id = GetCurrentThreadId();
615 }
catch (
const std::bad_alloc &) {
617 }
catch (
const std::exception &e) {
618 av_log(avctx,
AV_LOG_ERROR,
"unhandled exception in WGC thread init: %s\n", e.what());
625 ctx->wgc_thread_init_cond.notify_all();
626 if (
ctx->wgc_thread_init_res < 0) {
627 ctx->wgc_thread_res =
ctx->wgc_thread_init_res;
636 }
catch (
const std::bad_alloc &) {
638 }
catch (
const std::exception &e) {
639 av_log(avctx,
AV_LOG_ERROR,
"unhandled exception in WGC thread worker: %s\n", e.what());
646 std::lock_guard uninit_lock(
ctx->wgc_thread_uninit_mutex);
649 ctx->wgc_thread_res =
ret;
662 if (
ctx->wgc_thread.joinable()) {
666 ctx->wgc_thread.join();
667 ret =
ctx->wgc_thread_res;
669 ctx->wgc_thread_id = 0;
680 if (
ctx->wgc_thread.joinable() ||
ctx->wgc_thread_id) {
685 std::unique_lock wgc_lock(
ctx->wgc_thread_init_mutex);
686 ctx->wgc_thread_init_res = INT_MAX;
690 }
catch (
const std::system_error &e) {
695 if (!
ctx->wgc_thread_init_cond.wait_for(wgc_lock, std::chrono::seconds(1), [&]() {
696 return ctx->wgc_thread_init_res != INT_MAX;
702 return ctx->wgc_thread_init_res;
705 template <
typename F>
710 std::unique_ptr<GfxCaptureContextWgc> &wgctx =
ctx->wgc;
712 std::lock_guard uninit_lock(
ctx->wgc_thread_uninit_mutex);
720 std::condition_variable
cond;
725 auto cbdata =
ctx->wgc_thread_cb_data ?
726 std::static_pointer_cast<CBData>(
ctx->wgc_thread_cb_data) :
727 std::make_shared<CBData>();
728 ctx->wgc_thread_cb_data = cbdata;
730 cbdata->done = cbdata->cancel =
false;
735 create_cb_handler<IDispatcherQueueHandler>(
736 [
cb = std::forward<F>(
cb), cbdata]() {
738 std::lock_guard lock(cbdata->mutex);
744 } catch (const std::bad_alloc &) {
745 cbdata->ret = AVERROR(ENOMEM);
747 cbdata->ret = AVERROR_BUG;
753 cbdata->cond.notify_one();
761 std::unique_lock cblock(cbdata->mutex);
762 if (!cbdata->cond.wait_for(cblock, std::chrono::seconds(1), [&]() { return cbdata->done; })) {
763 cbdata->cancel =
true;
780 std::string pat(pattern);
782 auto flags = std::regex::ECMAScript | std::regex::optimize;
783 if (pat.rfind(
"(?i)", 0) == 0 || pat.rfind(
"(?I)", 0) == 0) {
785 flags |= std::regex::icase;
786 }
else if(pat.rfind(
"(?c)", 0) == 0 || pat.rfind(
"(?C)", 0) == 0) {
792 }
catch (
const std::regex_error &e) {
793 av_log(avctx,
AV_LOG_ERROR,
"Failed to compile regex '%s': %s\n", pat.c_str(), e.what());
804 int utf8size = WideCharToMultiByte(CP_UTF8, 0, in, -1,
nullptr, 0,
nullptr,
nullptr);
809 out->resize(utf8size - 1);
811 if (WideCharToMultiByte(CP_UTF8, 0, in, -1,
out->data(), utf8size,
nullptr,
nullptr) != utf8size)
822 if (!GetWindowThreadProcessId(hwnd, &pid))
825 handle_ptr_t proc(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid));
829 std::wstring image_name;
830 DWORD image_name_size = 512;
833 DWORD
len = image_name_size;
834 image_name.resize(
len);
835 if (QueryFullProcessImageNameW(proc.get(), 0, image_name.data(), &
len)) {
836 image_name.resize(
len);
839 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
840 image_name_size *= 2;
846 if (image_name.empty())
849 const wchar_t *
base = image_name.c_str();
850 size_t pos = image_name.find_last_of(
L"\\/");
851 if (
pos != std::string::npos)
875 av_log(avctx, AV_LOG_DEBUG,
"Found capture monitor: %d\n", cctx->monitor_idx);
876 ctx->capture_hmonitor = hmonitor;
881 if (EnumDisplayMonitors(
NULL,
NULL,
cb->proc,
cb->lparam) || !
ctx->capture_hmonitor)
885 std::regex text_regex;
889 std::regex class_regex;
893 std::regex exe_regex;
897 std::string window_text;
898 std::wstring window_text_w;
899 std::string window_class;
900 std::wstring window_class_w;
901 std::string window_exe;
904 if (!GetWindowRect(hwnd, &
r) ||
r.right <=
r.left ||
r.bottom <=
r.top || !IsWindowVisible(hwnd))
907 window_text_w.resize(GetWindowTextLengthW(hwnd) + 1);
908 int len = GetWindowTextW(hwnd, window_text_w.data(), (
int)window_text_w.size());
910 window_text_w.resize(
len);
917 window_class_w.resize(256);
918 len = GetClassNameW(hwnd, window_class_w.data(), (
int)window_class_w.size());
920 window_class_w.resize(
len);
922 window_class.clear();
924 window_class.clear();
930 hwnd, window_text.c_str(), window_class.c_str(), window_exe.c_str());
933 if (window_text.empty() || !std::regex_search(window_text, text_regex))
938 if (window_class.empty() || !std::regex_search(window_class, class_regex))
943 if (window_exe.empty() || !std::regex_search(window_exe, exe_regex))
948 window_text.c_str(), window_class.c_str(), window_exe.c_str());
949 ctx->capture_hwnd = hwnd;
952 if (EnumWindows(
cb->proc,
cb->lparam) || !
ctx->capture_hwnd)
956 ctx->capture_hmonitor = MonitorFromWindow(
ctx->capture_hwnd, MONITOR_DEFAULTTONEAREST);
958 if (!
ctx->capture_hmonitor) {
992 *
out =
reinterpret_cast<T>(GetProcAddress(hModule.get(), lpProcName));
1000 #define LOAD_DLL(handle, name) \
1001 handle = hmodule_ptr_t(LoadLibraryExW(L##name, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32)); \
1003 av_log(avctx, AV_LOG_ERROR, "Failed opening " #name "\n"); \
1004 return AVERROR(ENOSYS); \
1007 #define LOAD_FUNC(handle, name) \
1008 GetProcAddressTyped(handle, #name, &ctx->fn.name); \
1009 if (!ctx->fn.name) { \
1010 av_log(avctx, AV_LOG_ERROR, "Failed loading " #name "\n"); \
1011 return AVERROR(ENOSYS); \
1015 LOAD_DLL(
ctx->fn.graphicscapture_handle,
"graphicscapture.dll");
1020 LOAD_DLL(
ctx->fn.coremsg_handle,
"coremessaging.dll");
1022 LOAD_DLL(
ctx->fn.kernel32_handle,
"kernel32.dll");
1023 LOAD_DLL(
ctx->fn.d3dcompiler_handle,
"d3dcompiler_47.dll");
1027 LOAD_FUNC(
ctx->fn.combase_handle, RoGetActivationFactory);
1028 LOAD_FUNC(
ctx->fn.combase_handle, WindowsCreateStringReference);
1030 LOAD_FUNC(
ctx->fn.dwmapi_handle, DwmGetWindowAttribute);
1032 LOAD_FUNC(
ctx->fn.d3d11_handle, CreateDirect3D11DeviceFromDXGIDevice);
1034 LOAD_FUNC(
ctx->fn.coremsg_handle, CreateDispatcherQueueController);
1036 LOAD_FUNC(
ctx->fn.user32_handle, SetThreadDpiAwarenessContext);
1038 LOAD_FUNC(
ctx->fn.kernel32_handle, SetThreadDescription);
1053 ctx->d3d = std::make_unique<GfxCaptureContextD3D>();
1057 ctx->fn.RoUninitialize =
nullptr;
1075 if (!
ctx->frames_ref)
1087 ctx->frames_hwctx->BindFlags = D3D11_BIND_RENDER_TARGET;
1105 std::unique_ptr<GfxCaptureContextWgc> &wgctx =
ctx->wgc;
1126 cap_w -= wgctx->client_area_offsets.left + wgctx->client_area_offsets.right;
1127 cap_h -= wgctx->client_area_offsets.top + wgctx->client_area_offsets.bottom;
1147 std::unique_ptr<GfxCaptureContextD3D> &d3dctx =
ctx->d3d;
1150 ComPtr<ID3DBlob> vs_blob, ps_blob, err_blob;
1151 CD3D11_SAMPLER_DESC sampler_desc(CD3D11_DEFAULT{});
1152 UINT
flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
1154 hr =
ctx->fn.D3DCompile(
render_shader_src,
sizeof(
render_shader_src) - 1,
NULL,
NULL,
NULL,
"main_vs",
"vs_4_0",
flags, 0, &vs_blob, &err_blob);
1157 av_log(avctx,
AV_LOG_ERROR,
"Failed compiling vertex shader: %.*s\n", (
int)err_blob->GetBufferSize(), (
char*)err_blob->GetBufferPointer());
1164 const char *ps_entry =
"main_ps_bicubic";
1166 ps_entry =
"main_ps";
1167 sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
1170 hr =
ctx->fn.D3DCompile(
render_shader_src,
sizeof(
render_shader_src) - 1,
NULL,
NULL,
NULL, ps_entry,
"ps_4_0",
flags, 0, &ps_blob, &err_blob);
1173 av_log(avctx,
AV_LOG_ERROR,
"Failed compiling pixel shader: %.*s\n", (
int)err_blob->GetBufferSize(), (
char*)err_blob->GetBufferPointer());
1180 CHECK_HR_RET(
ctx->device_hwctx->device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(),
NULL, &d3dctx->vertex_shader));
1181 CHECK_HR_RET(
ctx->device_hwctx->device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(),
NULL, &d3dctx->pixel_shader));
1183 CHECK_HR_RET(
ctx->device_hwctx->device->CreateSamplerState(&sampler_desc, &d3dctx->sampler_state));
1185 D3D11_BUFFER_DESC cb_desc = { 0 };
1186 cb_desc.ByteWidth = 48;
1187 cb_desc.Usage = D3D11_USAGE_DYNAMIC;
1188 cb_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
1189 cb_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
1191 CHECK_HR_RET(
ctx->device_hwctx->device->CreateBuffer(&cb_desc,
NULL, &d3dctx->shader_cb));
1193 CHECK_HR_RET(
ctx->device_hwctx->device->CreateDeferredContext(0, &d3dctx->deferred_ctx));
1216 if (!
ctx->device_ref)
1254 std::lock_guard wgc_lock(
ctx->wgc_thread_uninit_mutex);
1260 outlink->
w =
ctx->frames_ctx->width;
1261 outlink->
h =
ctx->frames_ctx->height;
1275 std::unique_ptr<GfxCaptureContextD3D> &d3dctx =
ctx->d3d;
1276 std::unique_ptr<GfxCaptureContextWgc> &wgctx =
ctx->wgc;
1279 ID3D11DeviceContext *dev_ctx =
ctx->device_hwctx->device_context;
1280 ComPtr<ID3D11DeviceContext> &def_ctx = d3dctx->deferred_ctx;
1282 D3D11_TEXTURE2D_DESC dst_tex_desc;
1283 reinterpret_cast<ID3D11Texture2D*
>(
frame->data[0])->GetDesc(&dst_tex_desc);
1285 D3D11_TEXTURE2D_DESC src_tex_desc;
1286 src_tex->GetDesc(&src_tex_desc);
1288 D3D11_RENDER_TARGET_VIEW_DESC target_desc = {};
1289 target_desc.Format = dst_tex_desc.Format;
1291 if (dst_tex_desc.ArraySize > 1) {
1292 target_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
1293 target_desc.Texture2DArray.ArraySize = 1;
1294 target_desc.Texture2DArray.FirstArraySlice = (uintptr_t)
frame->data[1];
1295 target_desc.Texture2DArray.MipSlice = 0;
1297 target_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
1298 target_desc.Texture2D.MipSlice = 0;
1301 ComPtr<ID3D11RenderTargetView> rtv;
1303 reinterpret_cast<ID3D11Resource*
>(
frame->data[0]), &target_desc, &rtv));
1305 ComPtr<ID3D11ShaderResourceView> srv;
1306 CHECK_HR_RET(dev->CreateShaderResourceView(src_tex.Get(),
nullptr, &srv));
1314 crop_left += wgctx->client_area_offsets.left;
1315 crop_top += wgctx->client_area_offsets.top;
1316 crop_right += wgctx->client_area_offsets.right;
1317 crop_bottom += wgctx->client_area_offsets.bottom;
1326 int cropped_w = wgctx->cap_size.Width - crop_left - crop_right;
1327 int cropped_h = wgctx->cap_size.Height - crop_top - crop_bottom;
1329 D3D11_VIEWPORT viewport = { 0 };
1330 viewport.MinDepth = 0.f;
1331 viewport.MaxDepth = 1.f;
1335 viewport.Width = (
float)cropped_w;
1336 viewport.Height = (
float)cropped_h;
1339 viewport.Width = dst_tex_desc.Width;
1340 viewport.Height = dst_tex_desc.Height;
1343 float scale =
FFMIN(dst_tex_desc.Width / (
float)cropped_w,
1344 dst_tex_desc.Height / (
float)cropped_h);
1345 viewport.Width = cropped_w *
scale;
1346 viewport.Height = cropped_h *
scale;
1354 def_ctx->RSSetViewports(1, &viewport);
1356 D3D11_MAPPED_SUBRESOURCE
map;
1357 CHECK_HR_RET(def_ctx->Map(d3dctx->shader_cb.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &
map));
1359 float *cb_f =
static_cast<float*
>(
map.pData);
1360 uint32_t *cb_u =
static_cast<uint32_t*
>(
map.pData);
1361 cb_f[0] = (
float)cropped_w;
1362 cb_f[1] = (
float)cropped_h;
1363 cb_f[2] = viewport.Width;
1364 cb_f[3] = viewport.Height;
1365 cb_f[4] = crop_left / (
float)src_tex_desc.Width;
1366 cb_f[5] = crop_top / (
float)src_tex_desc.Height;
1367 cb_f[6] = (crop_left + cropped_w) / (
float)src_tex_desc.Width;
1368 cb_f[7] = (crop_top + cropped_h) / (
float)src_tex_desc.Height;
1373 def_ctx->Unmap(d3dctx->shader_cb.Get(), 0);
1375 def_ctx->OMSetRenderTargets(1, rtv.GetAddressOf(),
nullptr);
1377 const float clear_color[4] = {0.f, 0.f, 0.f, 1.f};
1378 def_ctx->ClearRenderTargetView(rtv.Get(), clear_color);
1380 def_ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
1381 def_ctx->VSSetShader(d3dctx->vertex_shader.Get(),
nullptr, 0);
1382 def_ctx->VSSetConstantBuffers(0, 1, d3dctx->shader_cb.GetAddressOf());
1383 def_ctx->PSSetShader(d3dctx->pixel_shader.Get(),
nullptr, 0);
1384 def_ctx->PSSetSamplers(0, 1, d3dctx->sampler_state.GetAddressOf());
1385 def_ctx->PSSetShaderResources(0, 1, srv.GetAddressOf());
1386 def_ctx->PSSetConstantBuffers(0, 1, d3dctx->shader_cb.GetAddressOf());
1388 def_ctx->Draw(3, 0);
1390 ComPtr<ID3D11CommandList> cmd_list;
1391 CHECK_HR_RET(def_ctx->FinishCommandList(FALSE, &cmd_list));
1392 dev_ctx->ExecuteCommandList(cmd_list.Get(), FALSE);
1407 ComPtr<IDirect3D11CaptureFrame> capture_frame;
1408 ComPtr<IDirect3DSurface> capture_surface;
1409 ComPtr<IDirect3DDxgiInterfaceAccess> dxgi_interface_access;
1410 ComPtr<ID3D11Texture2D> frame_texture;
1411 TimeSpan frame_time = { 0 };
1417 CHECK_HR_RET(capture_frame->get_SystemRelativeTime(&frame_time));
1419 CHECK_HR_RET(capture_frame->get_Surface(&capture_surface));
1420 CHECK_HR_RET(capture_surface.As(&dxgi_interface_access));
1421 CHECK_HR_RET(dxgi_interface_access->GetInterface(IID_PPV_ARGS(&frame_texture)));
1430 frame->pts = frame_time.Duration;
1455 if (!
ctx->first_pts)
1467 std::unique_ptr<GfxCaptureContextWgc> &wgctx =
ctx->wgc;
1469 std::lock_guard wgc_lock(
ctx->wgc_thread_uninit_mutex);
1479 uint64_t last_seq = wgctx->frame_seq;
1485 std::unique_lock
frame_lock(wgctx->frame_arrived_mutex);
1487 if (wgctx->window_closed && wgctx->frame_seq == last_seq) {
1492 if (!wgctx->frame_arrived_cond.wait_for(
frame_lock, std::chrono::seconds(1), [&]() {
1493 return wgctx->frame_seq != last_seq || wgctx->window_closed;
1505 }
catch (
const std::exception &e) {
1516 }
catch (
const std::bad_alloc&) {
1518 }
catch (
const std::exception &e) {
1531 }
catch (
const std::bad_alloc&) {
1533 }
catch (
const std::exception &e) {
1548 }
catch (
const std::bad_alloc&) {
1550 }
catch (
const std::exception &e) {
1551 av_log(avctx,
AV_LOG_ERROR,
"unhandled exception during config_props: %s\n", e.what());