DxgiCapturer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. #include "DxgiCapturer.h"
  2. #include "basic/basic.h"
  3. #include "basic/frame.h"
  4. #include "d3d/buffer_filler.h"
  5. #include "d3d/convert.h"
  6. #include "d3d/gen_frame.h"
  7. #include "../finder.h"
  8. #include <cassert>
  9. #include <d3d11.h>
  10. #include <dxgi1_2.h>
  11. namespace avrecorder {
  12. namespace video {
  13. // --- DxgiCapturerPrivate 实现 ---
  14. bool DxgiCapturerPrivate::Open(int left, int top, int width, int height) {
  15. Close();
  16. HRESULT hr = S_OK;
  17. _isAttached = false;
  18. if (_bInit) return false;
  19. // Driver types supported
  20. D3D_DRIVER_TYPE DriverTypes[] = {
  21. D3D_DRIVER_TYPE_HARDWARE,
  22. D3D_DRIVER_TYPE_WARP,
  23. D3D_DRIVER_TYPE_REFERENCE,
  24. };
  25. UINT NumDriverTypes = ARRAYSIZE(DriverTypes);
  26. // Feature levels supported
  27. D3D_FEATURE_LEVEL FeatureLevels[] = {
  28. D3D_FEATURE_LEVEL_11_0,
  29. D3D_FEATURE_LEVEL_10_1,
  30. D3D_FEATURE_LEVEL_10_0,
  31. D3D_FEATURE_LEVEL_9_1};
  32. UINT NumFeatureLevels = ARRAYSIZE(FeatureLevels);
  33. D3D_FEATURE_LEVEL FeatureLevel;
  34. // Create D3D device
  35. for (UINT DriverTypeIndex = 0; DriverTypeIndex < NumDriverTypes; ++DriverTypeIndex) {
  36. hr = D3D11CreateDevice(nullptr,
  37. DriverTypes[DriverTypeIndex],
  38. nullptr,
  39. 0,
  40. FeatureLevels,
  41. NumFeatureLevels,
  42. D3D11_SDK_VERSION,
  43. &_hDevice,
  44. &FeatureLevel,
  45. &_hContext);
  46. if (SUCCEEDED(hr)) {
  47. break;
  48. }
  49. }
  50. if (FAILED(hr)) {
  51. __DebugPrint("D3D11CreateDevice failed: 0x%08lx", (unsigned long)hr);
  52. return false;
  53. }
  54. // Get DXGI device
  55. IDXGIDevice* hDxgiDevice = nullptr;
  56. hr = _hDevice->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&hDxgiDevice));
  57. if (FAILED(hr)) {
  58. __DebugPrint("QueryInterface IDXGIDevice failed: 0x%08lx", (unsigned long)hr);
  59. Free(_hContext, [this]{ _hContext->Release(); });
  60. Free(_hDevice, [this]{ _hDevice->Release(); });
  61. return false;
  62. }
  63. // Get DXGI adapter
  64. IDXGIAdapter* hDxgiAdapter = nullptr;
  65. hr = hDxgiDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&hDxgiAdapter));
  66. Free(hDxgiDevice, [=] { hDxgiDevice->Release(); });
  67. if (FAILED(hr)) {
  68. __DebugPrint("GetParent IDXGIAdapter failed: 0x%08lx", (unsigned long)hr);
  69. Free(_hContext, [this]{ _hContext->Release(); });
  70. Free(_hDevice, [this]{ _hDevice->Release(); });
  71. return false;
  72. }
  73. // Get output
  74. IDXGIOutput* hDxgiOutput = nullptr;
  75. DXGI_OUTPUT_DESC dxgiOutDesc;
  76. ZeroMemory(&dxgiOutDesc, sizeof(dxgiOutDesc));
  77. for (int idx = 0; SUCCEEDED(hr = hDxgiAdapter->EnumOutputs(idx, &hDxgiOutput)); ++idx) {
  78. hDxgiOutput->GetDesc(&dxgiOutDesc);
  79. if (dxgiOutDesc.DesktopCoordinates.left == left && dxgiOutDesc.DesktopCoordinates.top == top) {
  80. break;
  81. }
  82. }
  83. Free(hDxgiAdapter, [=] { hDxgiAdapter->Release(); });
  84. if (FAILED(hr)) {
  85. __DebugPrint("EnumOutputs failed: 0x%08lx", (unsigned long)hr);
  86. Free(hDxgiOutput, [=]{ hDxgiOutput->Release(); });
  87. Free(_hContext, [this]{ _hContext->Release(); });
  88. Free(_hDevice, [this]{ _hDevice->Release(); });
  89. return false;
  90. }
  91. // QI for Output 1
  92. IDXGIOutput1* hDxgiOutput1 = nullptr;
  93. hr = hDxgiOutput->QueryInterface(__uuidof(hDxgiOutput1), reinterpret_cast<void**>(&hDxgiOutput1));
  94. Free(hDxgiOutput, [=] { hDxgiOutput->Release(); });
  95. if (FAILED(hr)) {
  96. __DebugPrint("QueryInterface IDXGIOutput1 failed: 0x%08lx", (unsigned long)hr);
  97. Free(_hContext, [this]{ _hContext->Release(); });
  98. Free(_hDevice, [this]{ _hDevice->Release(); });
  99. return false;
  100. }
  101. // Create desktop duplication
  102. hr = hDxgiOutput1->DuplicateOutput(_hDevice, &_hDeskDupl);
  103. Free(hDxgiOutput1, [=] { hDxgiOutput1->Release(); });
  104. if (FAILED(hr)) {
  105. __DebugPrint("DuplicateOutput failed: 0x%08lx", (unsigned long)hr);
  106. Free(_hContext, [this]{ _hContext->Release(); });
  107. Free(_hDevice, [this]{ _hDevice->Release(); });
  108. return false;
  109. }
  110. // Set ColorSpace
  111. D3D11_VIDEO_PROCESSOR_COLOR_SPACE inputColorSpace;
  112. inputColorSpace.Usage = 1;
  113. inputColorSpace.RGB_Range = 0;
  114. inputColorSpace.YCbCr_Matrix = 1;
  115. inputColorSpace.YCbCr_xvYCC = 0;
  116. inputColorSpace.Nominal_Range = D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE_0_255;
  117. D3D11_VIDEO_PROCESSOR_COLOR_SPACE outputColorSpace;
  118. outputColorSpace.Usage = 0;
  119. outputColorSpace.RGB_Range = 0;
  120. outputColorSpace.YCbCr_Matrix = 1;
  121. outputColorSpace.YCbCr_xvYCC = 0;
  122. outputColorSpace.Nominal_Range = D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE_16_235;
  123. _rgbToNv12.Open(_hDevice, _hContext, inputColorSpace, outputColorSpace);
  124. _nv12Frame = Frame<MediaType::VIDEO>::Alloc(AV_PIX_FMT_NV12, width, height);
  125. _xrgbFrame = Frame<MediaType::VIDEO>::Alloc(AV_PIX_FMT_BGR0, width, height);
  126. if (!_nv12Frame) {
  127. __DebugPrint("Alloc NV12 frame failed");
  128. Free(_hDeskDupl, [this]{ _hDeskDupl->Release(); });
  129. Free(_hContext, [this]{ _hContext->Release(); });
  130. Free(_hDevice, [this]{ _hDevice->Release(); });
  131. return false;
  132. }
  133. if (!_xrgbFrame) {
  134. __DebugPrint("Alloc XRGB frame failed");
  135. Free(_nv12Frame, [this]{ av_frame_free(&_nv12Frame); });
  136. Free(_hDeskDupl, [this]{ _hDeskDupl->Release(); });
  137. Free(_hContext, [this]{ _hContext->Release(); });
  138. Free(_hDevice, [this]{ _hDevice->Release(); });
  139. return false;
  140. }
  141. _bInit = true;
  142. return true;
  143. }
  144. AVFrame* DxgiCapturerPrivate::GetFrame(
  145. bool shouldDrawCursor, int left, int top, int right, int bottom)
  146. {
  147. if (!_bInit) return nullptr;
  148. _isCaptureSuccess = false;
  149. IDXGIResource* hDesktopResource = nullptr;
  150. DXGI_OUTDUPL_FRAME_INFO FrameInfo;
  151. HRESULT hr = _hDeskDupl->AcquireNextFrame(0, &FrameInfo, &hDesktopResource);
  152. if (FAILED(hr)) {
  153. if (hr == DXGI_ERROR_WAIT_TIMEOUT) return nullptr;
  154. return nullptr;
  155. }
  156. // query next frame staging buffer
  157. ID3D11Texture2D* srcImage = nullptr;
  158. hr = hDesktopResource->QueryInterface(__uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&srcImage));
  159. Free(hDesktopResource, [=] { hDesktopResource->Release(); });
  160. if (FAILED(hr)) {
  161. __DebugPrint("QueryInterface ID3D11Texture2D failed: 0x%08lx", (unsigned long)hr);
  162. _hDeskDupl->ReleaseFrame();
  163. return nullptr;
  164. }
  165. srcImage->GetDesc(&_desc);
  166. // create a new staging buffer for fill frame image
  167. auto desc = _desc;
  168. desc.ArraySize = 1;
  169. desc.BindFlags = D3D11_BIND_FLAG::D3D11_BIND_RENDER_TARGET;
  170. desc.MiscFlags = D3D11_RESOURCE_MISC_GDI_COMPATIBLE;
  171. desc.SampleDesc.Count = 1;
  172. desc.SampleDesc.Quality = 0;
  173. desc.MipLevels = 1;
  174. desc.CPUAccessFlags = 0;
  175. desc.Usage = D3D11_USAGE_DEFAULT;
  176. hr = _hDevice->CreateTexture2D(&desc, nullptr, &_gdiImage);
  177. if (FAILED(hr)) {
  178. __DebugPrint("Create _gdiImage failed");
  179. Free(srcImage, [=] { srcImage->Release(); });
  180. _hDeskDupl->ReleaseFrame();
  181. return nullptr;
  182. }
  183. // copy next staging buffer to new staging buffer
  184. _hContext->CopyResource(_gdiImage, srcImage);
  185. Free(srcImage, [=] { srcImage->Release(); });
  186. _hDeskDupl->ReleaseFrame();
  187. // create staging buffer for map bits
  188. _hStagingSurf = nullptr;
  189. hr = _gdiImage->QueryInterface(__uuidof(IDXGISurface), (void**) (&_hStagingSurf));
  190. if (FAILED(hr)) {
  191. __DebugPrint("_gdiImage->QueryInterface failed");
  192. Free(_gdiImage, [this] { _gdiImage->Release(); });
  193. return nullptr;
  194. }
  195. _isCaptureSuccess = true;
  196. HDC hdc = nullptr;
  197. _hStagingSurf->GetDC(FALSE, &hdc);
  198. // 合成鼠标指针
  199. if (hdc && shouldDrawCursor) {
  200. drawCursor(hdc, left, top, right, bottom);
  201. }
  202. // 释放 DC 并转换为 AVFrame
  203. if (_isCaptureSuccess) {
  204. _isCaptureSuccess = false;
  205. _hStagingSurf->ReleaseDC(nullptr);
  206. // 创建一个临时的纹理
  207. ID3D11Texture2D* tmpImage = nullptr;
  208. _desc.MiscFlags = 2050;
  209. hr = _hDevice->CreateTexture2D(&_desc, nullptr, &tmpImage);
  210. if (FAILED(hr)) {
  211. __DebugPrint("CreateTexture2D tmpImage failed: 0x%08lx", (unsigned long)hr);
  212. Free(_hStagingSurf, [this] { _hStagingSurf->Release(); });
  213. Free(_gdiImage, [this] { _gdiImage->Release(); });
  214. return nullptr;
  215. }
  216. _hContext->CopyResource(tmpImage, _gdiImage);
  217. // 首先尝试创建 NV12 纹理
  218. AVFrame* frame = nullptr;
  219. auto tmpFormat = _desc.Format;
  220. _desc.Format = DXGI_FORMAT_NV12;
  221. if (GenNv12Frame(_hDevice, _hContext, _desc, tmpImage, _nv12Buffers, _nv12Frame, _rgbToNv12)) {
  222. frame = _nv12Frame;
  223. } else {
  224. _desc.Format = tmpFormat;
  225. GenRgbFrame(_hDevice, _hContext, _desc, _gdiImage, _xrgbBuffers, _xrgbFrame);
  226. frame = _xrgbFrame;
  227. }
  228. Free(_hStagingSurf, [this] { _hStagingSurf->Release(); });
  229. Free(tmpImage, [&tmpImage] { tmpImage->Release(); });
  230. Free(_gdiImage, [this] { _gdiImage->Release(); });
  231. return frame;
  232. }
  233. return nullptr;
  234. }
  235. void DxgiCapturerPrivate::drawCursor(HDC hdc, int left, int top, int right, int bottom)
  236. {
  237. CURSORINFO ci;
  238. ci.cbSize = sizeof(CURSORINFO);
  239. if (!GetCursorInfo(&ci)) {
  240. __DebugPrint("GetCursorInfo failed");
  241. return;
  242. }
  243. int cursorX = ci.ptScreenPos.x;
  244. int cursorY = ci.ptScreenPos.y;
  245. if (cursorX > right || cursorX < left || cursorY > bottom || cursorY < top) {
  246. return; // 超出显示范围
  247. }
  248. if (ci.flags == CURSOR_SHOWING) {
  249. // 将光标画到屏幕所在位置
  250. int x = cursorX - left;
  251. int y = cursorY - top;
  252. DrawIconEx(hdc, x, y, ci.hCursor, 0, 0, 0, NULL, DI_NORMAL | DI_COMPAT);
  253. }
  254. }
  255. // --- DxgiCapturer 实现 ---
  256. DxgiCapturer::DxgiCapturer() : d(new DxgiCapturerPrivate) {}
  257. DxgiCapturer::~DxgiCapturer() { close(); delete d; }
  258. bool DxgiCapturer::open(const CaptureTarget& target, int width, int height) {
  259. #ifdef PLATFORM_WINDOWS
  260. close();
  261. if (target.type != CaptureTargetType::Monitor) return false;
  262. auto monitors = MonitorFinder::GetList();
  263. if (target.monitorIdx < 0 || target.monitorIdx >= (int)monitors.size()) return false;
  264. auto& monitorInfo = monitors[target.monitorIdx];
  265. m_left = monitorInfo.rect.left;
  266. m_top = monitorInfo.rect.top;
  267. m_width = monitorInfo.rect.right - monitorInfo.rect.left;
  268. m_height = monitorInfo.rect.bottom - monitorInfo.rect.top;
  269. m_right = monitorInfo.rect.right;
  270. m_bottom = monitorInfo.rect.bottom;
  271. return d->Open(m_left, m_top, m_width, m_height);
  272. #else
  273. return false;
  274. #endif
  275. }
  276. void DxgiCapturerPrivate::Close() {
  277. if (!_bInit) return;
  278. _bInit = false;
  279. _nv12Buffers.Clear();
  280. _xrgbBuffers.Clear();
  281. _rgbToNv12.Close();
  282. Free(_nv12Frame, [this] { av_frame_free(&_nv12Frame); });
  283. Free(_xrgbFrame, [this] { av_frame_free(&_xrgbFrame); });
  284. Free(_hDeskDupl, [this] { _hDeskDupl->Release(); });
  285. Free(_hDevice, [this] { _hDevice->Release(); });
  286. Free(_hContext, [this] { _hContext->Release(); });
  287. }
  288. void DxgiCapturer::close() {
  289. #ifdef PLATFORM_WINDOWS
  290. d->Close();
  291. #endif
  292. }
  293. AVFrame* DxgiCapturer::getFrame() {
  294. #ifdef PLATFORM_WINDOWS
  295. return d->GetFrame(m_drawCursor, m_left, m_top, m_right, m_bottom);
  296. #else
  297. return nullptr;
  298. #endif
  299. }
  300. } // namespace video
  301. } // namespace avrecorder