d3d11_interop.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /*
  2. // A sample program demonstrating interoperability of OpenCV cv::UMat with Direct X surface
  3. // At first, the data obtained from video file or camera and placed onto Direct X surface,
  4. // following mapping of this Direct X surface to OpenCV cv::UMat and call cv::Blur function.
  5. // The result is mapped back to Direct X surface and rendered through Direct X API.
  6. */
  7. #define WIN32_LEAN_AND_MEAN
  8. #include <windows.h>
  9. #include <d3d11.h>
  10. #include "opencv2/core.hpp"
  11. #include "opencv2/core/directx.hpp"
  12. #include "opencv2/core/ocl.hpp"
  13. #include "opencv2/imgproc.hpp"
  14. #include "opencv2/videoio.hpp"
  15. #include "d3dsample.hpp"
  16. class D3D11WinApp : public D3DSample
  17. {
  18. public:
  19. D3D11WinApp(int width, int height, std::string& window_name, cv::VideoCapture& cap)
  20. : D3DSample(width, height, window_name, cap),
  21. m_nv12_available(false)
  22. {}
  23. ~D3D11WinApp() {}
  24. int create(void)
  25. {
  26. // base initialization
  27. D3DSample::create();
  28. // initialize DirectX
  29. HRESULT r;
  30. DXGI_SWAP_CHAIN_DESC scd;
  31. ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));
  32. scd.BufferCount = 1; // one back buffer
  33. scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // use 32-bit color
  34. scd.BufferDesc.Width = m_width; // set the back buffer width
  35. scd.BufferDesc.Height = m_height; // set the back buffer height
  36. scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // how swap chain is to be used
  37. scd.OutputWindow = m_hWnd; // the window to be used
  38. scd.SampleDesc.Count = 1; // how many multisamples
  39. scd.Windowed = TRUE; // windowed/full-screen mode
  40. scd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  41. scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; // allow full-screen switching
  42. r = ::D3D11CreateDeviceAndSwapChain(
  43. NULL,
  44. D3D_DRIVER_TYPE_HARDWARE,
  45. NULL,
  46. 0,
  47. NULL,
  48. 0,
  49. D3D11_SDK_VERSION,
  50. &scd,
  51. &m_pD3D11SwapChain,
  52. &m_pD3D11Dev,
  53. NULL,
  54. &m_pD3D11Ctx);
  55. if (FAILED(r))
  56. {
  57. throw std::runtime_error("D3D11CreateDeviceAndSwapChain() failed!");
  58. }
  59. #if defined(_WIN32_WINNT_WIN8) && _WIN32_WINNT >= _WIN32_WINNT_WIN8
  60. UINT fmt = 0;
  61. r = m_pD3D11Dev->CheckFormatSupport(DXGI_FORMAT_NV12, &fmt);
  62. if (SUCCEEDED(r))
  63. {
  64. m_nv12_available = true;
  65. }
  66. #endif
  67. r = m_pD3D11SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&m_pBackBuffer);
  68. if (FAILED(r))
  69. {
  70. throw std::runtime_error("GetBuffer() failed!");
  71. }
  72. r = m_pD3D11Dev->CreateRenderTargetView(m_pBackBuffer, NULL, &m_pRenderTarget);
  73. if (FAILED(r))
  74. {
  75. throw std::runtime_error("CreateRenderTargetView() failed!");
  76. }
  77. m_pD3D11Ctx->OMSetRenderTargets(1, &m_pRenderTarget, NULL);
  78. D3D11_VIEWPORT viewport;
  79. ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
  80. viewport.Width = (float)m_width;
  81. viewport.Height = (float)m_height;
  82. viewport.MinDepth = 0.0f;
  83. viewport.MaxDepth = 0.0f;
  84. m_pD3D11Ctx->RSSetViewports(1, &viewport);
  85. m_pSurfaceRGBA = 0;
  86. m_pSurfaceNV12 = 0;
  87. m_pSurfaceNV12_cpu_copy = 0;
  88. D3D11_TEXTURE2D_DESC desc_rgba;
  89. desc_rgba.Width = m_width;
  90. desc_rgba.Height = m_height;
  91. desc_rgba.MipLevels = 1;
  92. desc_rgba.ArraySize = 1;
  93. desc_rgba.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  94. desc_rgba.SampleDesc.Count = 1;
  95. desc_rgba.SampleDesc.Quality = 0;
  96. desc_rgba.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  97. desc_rgba.Usage = D3D11_USAGE_DYNAMIC;
  98. desc_rgba.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  99. desc_rgba.MiscFlags = 0;
  100. r = m_pD3D11Dev->CreateTexture2D(&desc_rgba, 0, &m_pSurfaceRGBA);
  101. if (FAILED(r))
  102. {
  103. throw std::runtime_error("Can't create DX texture");
  104. }
  105. #if defined(_WIN32_WINNT_WIN8) && _WIN32_WINNT >= _WIN32_WINNT_WIN8
  106. if(m_nv12_available)
  107. {
  108. D3D11_TEXTURE2D_DESC desc_nv12;
  109. desc_nv12.Width = m_width;
  110. desc_nv12.Height = m_height;
  111. desc_nv12.MipLevels = 1;
  112. desc_nv12.ArraySize = 1;
  113. desc_nv12.Format = DXGI_FORMAT_NV12;
  114. desc_nv12.SampleDesc.Count = 1;
  115. desc_nv12.SampleDesc.Quality = 0;
  116. desc_nv12.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  117. desc_nv12.Usage = D3D11_USAGE_DEFAULT;
  118. desc_nv12.CPUAccessFlags = 0;
  119. desc_nv12.MiscFlags = D3D11_RESOURCE_MISC_SHARED;
  120. r = m_pD3D11Dev->CreateTexture2D(&desc_nv12, 0, &m_pSurfaceNV12);
  121. if (FAILED(r))
  122. {
  123. throw std::runtime_error("Can't create DX NV12 texture");
  124. }
  125. D3D11_TEXTURE2D_DESC desc_nv12_cpu_copy;
  126. desc_nv12_cpu_copy.Width = m_width;
  127. desc_nv12_cpu_copy.Height = m_height;
  128. desc_nv12_cpu_copy.MipLevels = 1;
  129. desc_nv12_cpu_copy.ArraySize = 1;
  130. desc_nv12_cpu_copy.Format = DXGI_FORMAT_NV12;
  131. desc_nv12_cpu_copy.SampleDesc.Count = 1;
  132. desc_nv12_cpu_copy.SampleDesc.Quality = 0;
  133. desc_nv12_cpu_copy.BindFlags = 0;
  134. desc_nv12_cpu_copy.Usage = D3D11_USAGE_STAGING;
  135. desc_nv12_cpu_copy.CPUAccessFlags = /*D3D11_CPU_ACCESS_WRITE | */D3D11_CPU_ACCESS_READ;
  136. desc_nv12_cpu_copy.MiscFlags = 0;
  137. r = m_pD3D11Dev->CreateTexture2D(&desc_nv12_cpu_copy, 0, &m_pSurfaceNV12_cpu_copy);
  138. if (FAILED(r))
  139. {
  140. throw std::runtime_error("Can't create DX NV12 texture");
  141. }
  142. }
  143. #endif
  144. // initialize OpenCL context of OpenCV lib from DirectX
  145. if (cv::ocl::haveOpenCL())
  146. {
  147. m_oclCtx = cv::directx::ocl::initializeContextFromD3D11Device(m_pD3D11Dev);
  148. }
  149. m_oclDevName = cv::ocl::useOpenCL() ?
  150. cv::ocl::Context::getDefault().device(0).name() :
  151. "No OpenCL device";
  152. return EXIT_SUCCESS;
  153. } // create()
  154. // get media data on DX surface for further processing
  155. int get_surface(ID3D11Texture2D** ppSurface, bool use_nv12)
  156. {
  157. HRESULT r;
  158. if (!m_cap.read(m_frame_bgr))
  159. return EXIT_FAILURE;
  160. if (use_nv12)
  161. {
  162. cv::cvtColor(m_frame_bgr, m_frame_i420, cv::COLOR_BGR2YUV_I420);
  163. convert_I420_to_NV12(m_frame_i420, m_frame_nv12, m_width, m_height);
  164. m_pD3D11Ctx->UpdateSubresource(m_pSurfaceNV12, 0, 0, m_frame_nv12.data, (UINT)m_frame_nv12.step[0], (UINT)m_frame_nv12.total());
  165. }
  166. else
  167. {
  168. cv::cvtColor(m_frame_bgr, m_frame_rgba, cv::COLOR_BGR2RGBA);
  169. // process video frame on CPU
  170. UINT subResource = ::D3D11CalcSubresource(0, 0, 1);
  171. D3D11_MAPPED_SUBRESOURCE mappedTex;
  172. r = m_pD3D11Ctx->Map(m_pSurfaceRGBA, subResource, D3D11_MAP_WRITE_DISCARD, 0, &mappedTex);
  173. if (FAILED(r))
  174. {
  175. throw std::runtime_error("surface mapping failed!");
  176. }
  177. cv::Mat m(m_height, m_width, CV_8UC4, mappedTex.pData, mappedTex.RowPitch);
  178. m_frame_rgba.copyTo(m);
  179. m_pD3D11Ctx->Unmap(m_pSurfaceRGBA, subResource);
  180. }
  181. *ppSurface = use_nv12 ? m_pSurfaceNV12 : m_pSurfaceRGBA;
  182. return EXIT_SUCCESS;
  183. } // get_surface()
  184. // process and render media data
  185. int render()
  186. {
  187. try
  188. {
  189. if (m_shutdown)
  190. return EXIT_SUCCESS;
  191. // capture user input once
  192. MODE mode = (m_mode == MODE_GPU_NV12 && !m_nv12_available) ? MODE_GPU_RGBA : m_mode;
  193. HRESULT r;
  194. ID3D11Texture2D* pSurface = 0;
  195. r = get_surface(&pSurface, mode == MODE_GPU_NV12);
  196. if (FAILED(r))
  197. {
  198. throw std::runtime_error("get_surface() failed!");
  199. }
  200. m_timer.reset();
  201. m_timer.start();
  202. switch (mode)
  203. {
  204. case MODE_CPU:
  205. {
  206. // process video frame on CPU
  207. UINT subResource = ::D3D11CalcSubresource(0, 0, 1);
  208. D3D11_MAPPED_SUBRESOURCE mappedTex;
  209. r = m_pD3D11Ctx->Map(pSurface, subResource, D3D11_MAP_WRITE_DISCARD, 0, &mappedTex);
  210. if (FAILED(r))
  211. {
  212. throw std::runtime_error("surface mapping failed!");
  213. }
  214. cv::Mat m(m_height, m_width, CV_8UC4, mappedTex.pData, (int)mappedTex.RowPitch);
  215. if (m_demo_processing)
  216. {
  217. // blur data from D3D11 surface with OpenCV on CPU
  218. cv::blur(m, m, cv::Size(15, 15));
  219. }
  220. m_timer.stop();
  221. cv::String strMode = cv::format("mode: %s", m_modeStr[MODE_CPU].c_str());
  222. cv::String strProcessing = m_demo_processing ? "blur frame" : "copy frame";
  223. cv::String strTime = cv::format("time: %4.3f msec", m_timer.getTimeMilli());
  224. cv::String strDevName = cv::format("OpenCL device: %s", m_oclDevName.c_str());
  225. cv::putText(m, strMode, cv::Point(0, 20), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0, 0, 200), 2);
  226. cv::putText(m, strProcessing, cv::Point(0, 40), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0, 0, 200), 2);
  227. cv::putText(m, strTime, cv::Point(0, 60), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0, 0, 200), 2);
  228. cv::putText(m, strDevName, cv::Point(0, 80), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0, 0, 200), 2);
  229. m_pD3D11Ctx->Unmap(pSurface, subResource);
  230. break;
  231. }
  232. case MODE_GPU_RGBA:
  233. case MODE_GPU_NV12:
  234. {
  235. // process video frame on GPU
  236. cv::UMat u;
  237. cv::directx::convertFromD3D11Texture2D(pSurface, u);
  238. if (m_demo_processing)
  239. {
  240. // blur data from D3D11 surface with OpenCV on GPU with OpenCL
  241. cv::blur(u, u, cv::Size(15, 15));
  242. }
  243. m_timer.stop();
  244. cv::String strMode = cv::format("mode: %s", m_modeStr[mode].c_str());
  245. cv::String strProcessing = m_demo_processing ? "blur frame" : "copy frame";
  246. cv::String strTime = cv::format("time: %4.3f msec", m_timer.getTimeMilli());
  247. cv::String strDevName = cv::format("OpenCL device: %s", m_oclDevName.c_str());
  248. cv::putText(u, strMode, cv::Point(0, 20), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0, 0, 200), 2);
  249. cv::putText(u, strProcessing, cv::Point(0, 40), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0, 0, 200), 2);
  250. cv::putText(u, strTime, cv::Point(0, 60), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0, 0, 200), 2);
  251. cv::putText(u, strDevName, cv::Point(0, 80), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0, 0, 200), 2);
  252. cv::directx::convertToD3D11Texture2D(u, pSurface);
  253. if (mode == MODE_GPU_NV12)
  254. {
  255. // just for rendering, we need to convert NV12 to RGBA.
  256. m_pD3D11Ctx->CopyResource(m_pSurfaceNV12_cpu_copy, m_pSurfaceNV12);
  257. // process video frame on CPU
  258. {
  259. UINT subResource = ::D3D11CalcSubresource(0, 0, 1);
  260. D3D11_MAPPED_SUBRESOURCE mappedTex;
  261. r = m_pD3D11Ctx->Map(m_pSurfaceNV12_cpu_copy, subResource, D3D11_MAP_READ, 0, &mappedTex);
  262. if (FAILED(r))
  263. {
  264. throw std::runtime_error("surface mapping failed!");
  265. }
  266. cv::Mat frame_nv12(m_height + (m_height / 2), m_width, CV_8UC1, mappedTex.pData, mappedTex.RowPitch);
  267. cv::cvtColor(frame_nv12, m_frame_rgba, cv::COLOR_YUV2RGBA_NV12);
  268. m_pD3D11Ctx->Unmap(m_pSurfaceNV12_cpu_copy, subResource);
  269. }
  270. {
  271. UINT subResource = ::D3D11CalcSubresource(0, 0, 1);
  272. D3D11_MAPPED_SUBRESOURCE mappedTex;
  273. r = m_pD3D11Ctx->Map(m_pSurfaceRGBA, subResource, D3D11_MAP_WRITE_DISCARD, 0, &mappedTex);
  274. if (FAILED(r))
  275. {
  276. throw std::runtime_error("surface mapping failed!");
  277. }
  278. cv::Mat m(m_height, m_width, CV_8UC4, mappedTex.pData, mappedTex.RowPitch);
  279. m_frame_rgba.copyTo(m);
  280. m_pD3D11Ctx->Unmap(m_pSurfaceRGBA, subResource);
  281. }
  282. pSurface = m_pSurfaceRGBA;
  283. }
  284. break;
  285. }
  286. } // switch
  287. // traditional DX render pipeline:
  288. // BitBlt surface to backBuffer and flip backBuffer to frontBuffer
  289. m_pD3D11Ctx->CopyResource(m_pBackBuffer, pSurface);
  290. // present the back buffer contents to the display
  291. // switch the back buffer and the front buffer
  292. r = m_pD3D11SwapChain->Present(0, 0);
  293. if (FAILED(r))
  294. {
  295. throw std::runtime_error("switch between fronat and back buffers failed!");
  296. }
  297. } // try
  298. catch (const cv::Exception& e)
  299. {
  300. std::cerr << "Exception: " << e.what() << std::endl;
  301. cleanup();
  302. return 10;
  303. }
  304. catch (const std::exception& e)
  305. {
  306. std::cerr << "Exception: " << e.what() << std::endl;
  307. cleanup();
  308. return 11;
  309. }
  310. return EXIT_SUCCESS;
  311. } // render()
  312. int cleanup(void)
  313. {
  314. SAFE_RELEASE(m_pSurfaceRGBA);
  315. SAFE_RELEASE(m_pSurfaceNV12);
  316. SAFE_RELEASE(m_pSurfaceNV12_cpu_copy);
  317. SAFE_RELEASE(m_pBackBuffer);
  318. SAFE_RELEASE(m_pD3D11SwapChain);
  319. SAFE_RELEASE(m_pRenderTarget);
  320. SAFE_RELEASE(m_pD3D11Dev);
  321. SAFE_RELEASE(m_pD3D11Ctx);
  322. D3DSample::cleanup();
  323. return EXIT_SUCCESS;
  324. } // cleanup()
  325. protected:
  326. void convert_I420_to_NV12(cv::Mat& i420, cv::Mat& nv12, int width, int height)
  327. {
  328. nv12.create(i420.rows, i420.cols, CV_8UC1);
  329. unsigned char* pSrcY = i420.data;
  330. unsigned char* pDstY = nv12.data;
  331. size_t srcStep = i420.step[0];
  332. size_t dstStep = nv12.step[0];
  333. {
  334. unsigned char* src;
  335. unsigned char* dst;
  336. // copy Y plane
  337. for (int i = 0; i < height; i++)
  338. {
  339. src = pSrcY + i*srcStep;
  340. dst = pDstY + i*dstStep;
  341. for (int j = 0; j < width; j++)
  342. {
  343. dst[j] = src[j];
  344. }
  345. }
  346. }
  347. {
  348. // copy U/V planes to UV plane
  349. unsigned char* pSrcU;
  350. unsigned char* pSrcV;
  351. unsigned char* pDstUV;
  352. size_t uv_offset = height * dstStep;
  353. for (int i = 0; i < height / 2; i++)
  354. {
  355. pSrcU = pSrcY + height*width + i*(width / 2);
  356. pSrcV = pSrcY + height*width + (height / 2) * (width / 2) + i*(width / 2);
  357. pDstUV = pDstY + uv_offset + i*dstStep;
  358. for (int j = 0; j < width / 2; j++)
  359. {
  360. pDstUV[j*2 + 0] = pSrcU[j];
  361. pDstUV[j*2 + 1] = pSrcV[j];
  362. }
  363. }
  364. }
  365. return;
  366. }
  367. private:
  368. ID3D11Device* m_pD3D11Dev;
  369. IDXGISwapChain* m_pD3D11SwapChain;
  370. ID3D11DeviceContext* m_pD3D11Ctx;
  371. ID3D11Texture2D* m_pBackBuffer;
  372. ID3D11Texture2D* m_pSurfaceRGBA;
  373. ID3D11Texture2D* m_pSurfaceNV12;
  374. ID3D11Texture2D* m_pSurfaceNV12_cpu_copy;
  375. ID3D11RenderTargetView* m_pRenderTarget;
  376. cv::ocl::Context m_oclCtx;
  377. cv::String m_oclPlatformName;
  378. cv::String m_oclDevName;
  379. bool m_nv12_available;
  380. cv::Mat m_frame_i420;
  381. cv::Mat m_frame_nv12;
  382. };
  383. // main func
  384. int main(int argc, char** argv)
  385. {
  386. std::string title = "D3D11 interop sample";
  387. return d3d_app<D3D11WinApp>(argc, argv, title);
  388. }