-
Notifications
You must be signed in to change notification settings - Fork 0
/
Capture.cpp
330 lines (271 loc) · 10.4 KB
/
Capture.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#include "pch.h"
#include "libWSAController.h"
using namespace libWSAController;
#include "Capture.h"
#include "CallbackLogger.h"
bool WGCCapture::Attach(HWND hwnd)
{
LogTraceFunction;
Release();
m_hwnd = hwnd;
m_locker = std::make_unique<std::mutex>();
m_recieved = std::make_unique<std::atomic_bool>();
HRESULT result = S_OK;
result = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_VIDEO_SUPPORT, nullptr, 0,
D3D11_SDK_VERSION, m_native_device.put(), nullptr, m_context.put());
if (FAILED(result)) {
callback("D3D11CreateDevice", "ERR", std::format("GetLastError() = ", GetLastError()));
return false;
}
auto fill_error = [](std::string_view fn_name) {
callback(fn_name, "ERR", std::format("GetLastError() = {}", fn_name, GetLastError()));
};
if (hwnd == NULL) {
fill_error("FindWindow");
return false;
}
if (IsIconic(hwnd)) {
callbackfw("WSA window is iconic. Try to show WSA window.");
if (!ShowWindow(hwnd, SW_SHOW)) return false;
}
SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
auto wndStyle = GetWindowLong(hwnd, GWL_STYLE);
auto wndExStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
auto dpi = GetDpiForWindow(hwnd);
RECT wantedSize = { .left = 0, .top = 0, .right = WindowWidthDefault, .bottom = WindowHeightDefault };
RECT wantedClient = wantedSize;
GetClientRect(hwnd, &wantedClient);
RECT testCaption = { 0, 0, 100, 100 };
AdjustWindowRectExForDpi(&testCaption, wndStyle, false, wndExStyle, dpi);
m_caption_height = -testCaption.top;
wantedSize.right = wantedClient.right;
wantedSize.bottom = wantedClient.bottom - m_caption_height;
m_arknights_roi = cv::Rect{ 0, m_caption_height, wantedSize.right, wantedSize.bottom };
auto factory = winrt::get_activation_factory<winrt::Windows::Graphics::Capture::GraphicsCaptureItem,
IGraphicsCaptureItemInterop>();
result = factory->CreateForWindow(
hwnd, winrt::guid_of<winrt::Windows::Graphics::Capture::GraphicsCaptureItem>(), winrt::put_abi(m_item));
if (FAILED(result)) {
fill_error("IGraphicsCaptureItem::CreateForWindow");
return false;
}
auto dxgiDevice = m_native_device.as<IDXGIDevice>();
result = CreateDirect3D11DeviceFromDXGIDevice(dxgiDevice.get(),
reinterpret_cast<IInspectable**>(winrt::put_abi(m_device)));
if (FAILED(result)) {
fill_error("CreateDirect3D11DeviceFromDXGIDevice");
return false;
}
m_inputSize = m_item.Size();
//m_cache.create(m_inputSize.Height, m_inputSize.Width, CV_8UC3);
{
D3D11_TEXTURE2D_DESC desc = { .Width = (UINT)m_inputSize.Width,
.Height = (UINT)m_inputSize.Height,
.MipLevels = 1,
.ArraySize = 1,
.Format = DXGI_FORMAT_B8G8R8A8_UNORM,
.SampleDesc = {.Count = 1, .Quality = 0 },
.Usage = D3D11_USAGE_STAGING,
.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE,
.MiscFlags = 0 };
result = m_native_device->CreateTexture2D(&desc, nullptr, m_staging_texture.put());
}
if (FAILED(result)) {
fill_error("ID3D11Device::CreateTexture2D");
return false;
}
m_frame_pool = winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool::CreateFreeThreaded(
m_device, winrt::Windows::Graphics::DirectX::DirectXPixelFormat::B8G8R8A8UIntNormalized, 1, m_inputSize);
if (m_frame_pool == nullptr) {
fill_error("winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool::CreateFreeThreaded");
return false;
}
return SUCCEEDED(result);
}
void WGCCapture::Release()
{
LogTraceFunction;
if (m_session) {
m_locker->lock();
m_session = nullptr;
if (m_frame_arrived)
m_frame_pool.FrameArrived(m_frame_arrived);
m_locker->unlock();
m_locker->lock();
m_locker->unlock();
m_locker = nullptr;
m_recieved = nullptr;
}
m_frame_pool = nullptr;
m_item = nullptr;
m_device = nullptr;
m_staging_texture = nullptr;
m_context = nullptr;
m_native_device = nullptr;
}
bool WGCCapture::StartSession()
{
LogTraceFunction;
if (EndSession()) return false;
if (!IsWindow(m_hwnd)) {
m_frame_pool = nullptr;
m_session = nullptr;
return false;
}
if (m_contiguous)
m_frame_arrived = m_frame_pool.FrameArrived({ this, &WGCCapture::process_frame });
m_session = m_frame_pool.CreateCaptureSession(m_item);
m_session.IsBorderRequired(m_golden_border);
m_session.IsCursorCaptureEnabled(false);
m_session.StartCapture();
return true;
}
bool WGCCapture::EndSession()
{
LogTraceFunction;
if (m_session) {
m_locker->lock();
m_session = nullptr;
if (m_frame_arrived)
m_frame_pool.FrameArrived(m_frame_arrived);
m_locker->unlock();
return true;
}
return false;
}
cv::Mat WGCCapture::Get(bool c3u8)
{
if (m_contiguous)
{
m_locker->lock();
if (!m_session)
{
if (m_locker) m_locker->unlock();
return {};
}
while (!m_recieved->load())
;
if (m_cache.empty()) [[unlikely]] {
m_locker->unlock();
return {};
}
cv::Mat payload = m_cache(m_arknights_roi).clone();
m_recieved->store(false);
m_locker->unlock();
if (c3u8) cv::cvtColor(payload, payload, cv::COLOR_BGRA2BGR);
return payload;
}
else
{
winrt::Windows::Graphics::Capture::Direct3D11CaptureFrame frame = nullptr;
// Clear cache
do { frame = m_frame_pool.TryGetNextFrame(); } while (frame != nullptr);
// Up-to-date
do { frame = m_frame_pool.TryGetNextFrame(); } while (frame != nullptr);
CopyFromFrameCV(frame);
cv::Mat payload = m_cache(m_arknights_roi).clone();
if (c3u8) cv::cvtColor(payload, payload, cv::COLOR_BGRA2BGR);
return payload;
}
}
cv::Mat WGCCapture::Peek(bool c3u8)
{
if (m_contiguous)
{
m_locker->lock();
if (!m_session)
{
if (m_locker) m_locker->unlock();
return {};
}
if (m_cache.empty()) [[unlikely]] {
m_locker->unlock();
return {};
}
cv::Mat payload = m_cache(m_arknights_roi).clone();
m_locker->unlock();
if (c3u8) cv::cvtColor(payload, payload, cv::COLOR_BGRA2BGR);
return payload;
}
else
{
winrt::Windows::Graphics::Capture::Direct3D11CaptureFrame frame = nullptr;
// Clear cache
do { frame = m_frame_pool.TryGetNextFrame(); } while (frame != nullptr);
// Up-to-date
do { frame = m_frame_pool.TryGetNextFrame(); } while (frame != nullptr);
CopyFromFrameCV(frame);
cv::Mat payload = m_cache(m_arknights_roi).clone();
if (c3u8) cv::cvtColor(payload, payload, cv::COLOR_BGRA2BGR);
return payload;
}
}
void WGCCapture::SetGoldenBorder(bool enable)
{
m_golden_border = enable;
if (EndSession()) StartSession();
}
void WGCCapture::SetContiguousGettingImgs(bool enable)
{
m_contiguous = enable;
if (EndSession()) StartSession();
}
void WGCCapture::CopyFromFrameCV(winrt::Windows::Graphics::Capture::Direct3D11CaptureFrame const& frame)
{
winrt::com_ptr<Windows::Graphics::DirectX::Direct3D11::IDirect3DDxgiInterfaceAccess> dxgiAccess = {
frame.Surface().as<Windows::Graphics::DirectX::Direct3D11::IDirect3DDxgiInterfaceAccess>()
};
winrt::com_ptr<::ID3D11Resource> resource;
winrt::check_hresult(dxgiAccess->GetInterface(__uuidof(resource), resource.put_void()));
m_context->CopyResource(m_staging_texture.get(), resource.get());
D3D11_MAPPED_SUBRESOURCE field;
UINT subresource = D3D11CalcSubresource(0, 0, 0);
m_context->Map(m_staging_texture.get(), subresource, D3D11_MAP_READ, 0, &field);
//const auto pitch = m_inputSize.Width * 3ull;
//uchar* data = m_cache.ptr();
//uchar* source = (uchar*)field.pData;
//for (size_t i = 0; i < m_inputSize.Height; i++) {
// for (size_t j = 0; j < m_inputSize.Width; j++) {
// data[i * pitch + j * 3] = source[i * field.RowPitch + j * 4];
// data[i * pitch + j * 3 + 1] = source[i * field.RowPitch + j * 4 + 1];
// data[i * pitch + j * 3 + 2] = source[i * field.RowPitch + j * 4 + 2];
// }
//}
//m_recieved.store(true);
//m_locker.unlock();
m_cache = cv::Mat(m_inputSize.Height, m_inputSize.Width, CV_8UC4, field.pData, field.RowPitch);
m_context->Unmap(m_staging_texture.get(), subresource);
}
void WGCCapture::CopyFromFrameCImage(winrt::Windows::Graphics::Capture::Direct3D11CaptureFrame const& frame, CImage& img)
{
winrt::com_ptr<Windows::Graphics::DirectX::Direct3D11::IDirect3DDxgiInterfaceAccess> dxgiAccess = {
frame.Surface().as<Windows::Graphics::DirectX::Direct3D11::IDirect3DDxgiInterfaceAccess>()
};
winrt::com_ptr<::ID3D11Resource> resource;
winrt::check_hresult(dxgiAccess->GetInterface(__uuidof(resource), resource.put_void()));
m_context->CopyResource(m_staging_texture.get(), resource.get());
D3D11_MAPPED_SUBRESOURCE field;
UINT subresource = D3D11CalcSubresource(0, 0, 0);
m_context->Map(m_staging_texture.get(), subresource, D3D11_MAP_READ, 0, &field);
memcpy(img.GetBits(), field.pData, img.GetHeight() * img.GetPitch());
m_context->Unmap(m_staging_texture.get(), subresource);
}
void WGCCapture::process_frame(winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool const& framePool, winrt::Windows::Foundation::IInspectable const& object)
{
m_locker->lock();
if (!m_session) {
if (m_locker) m_locker->unlock();
return;
}
winrt::Windows::Graphics::Capture::Direct3D11CaptureFrame frame = framePool.TryGetNextFrame();
auto size = frame.ContentSize();
if (size != m_inputSize) {
framePool.Recreate(
m_device, winrt::Windows::Graphics::DirectX::DirectXPixelFormat::B8G8R8A8UIntNormalized, 1, m_inputSize);
m_locker->unlock();
return;
}
CopyFromFrameCV(frame);
m_recieved->store(true);
m_locker->unlock();
}