Direct3DInterop.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. #include "pch.h"
  2. #include "Direct3DInterop.h"
  3. #include "Direct3DContentProvider.h"
  4. #include <windows.storage.streams.h>
  5. #include <wrl.h>
  6. #include <robuffer.h>
  7. #include <opencv2\core.hpp>
  8. #include <opencv2\imgproc.hpp>
  9. #include <opencv2\features2d.hpp>
  10. #include <algorithm>
  11. using namespace Windows::Storage::Streams;
  12. using namespace Microsoft::WRL;
  13. using namespace Windows::Foundation;
  14. using namespace Windows::UI::Core;
  15. using namespace Microsoft::WRL;
  16. using namespace Windows::Phone::Graphics::Interop;
  17. using namespace Windows::Phone::Input::Interop;
  18. using namespace Windows::Foundation;
  19. using namespace Windows::Foundation::Collections;
  20. using namespace Windows::Phone::Media::Capture;
  21. #if !defined(_M_ARM)
  22. #pragma message("warning: Direct3DInterop.cpp: Windows Phone camera code does not run in the emulator.")
  23. #pragma message("warning: Direct3DInterop.cpp: Please compile as an ARM build and run on a device.")
  24. #endif
  25. namespace PhoneXamlDirect3DApp1Comp
  26. {
  27. // Called each time a preview frame is available
  28. void CameraCapturePreviewSink::OnFrameAvailable(
  29. DXGI_FORMAT format,
  30. UINT width,
  31. UINT height,
  32. BYTE* pixels
  33. )
  34. {
  35. m_Direct3dInterop->UpdateFrame(pixels, width, height);
  36. }
  37. // Called each time a captured frame is available
  38. void CameraCaptureSampleSink::OnSampleAvailable(
  39. ULONGLONG hnsPresentationTime,
  40. ULONGLONG hnsSampleDuration,
  41. DWORD cbSample,
  42. BYTE* pSample)
  43. {
  44. }
  45. Direct3DInterop::Direct3DInterop()
  46. : m_algorithm(OCVFilterType::ePreview)
  47. , m_contentDirty(false)
  48. , m_backFrame(nullptr)
  49. , m_frontFrame(nullptr)
  50. {
  51. }
  52. bool Direct3DInterop::SwapFrames()
  53. {
  54. std::lock_guard<std::mutex> lock(m_mutex);
  55. if(m_backFrame != nullptr)
  56. {
  57. std::swap(m_backFrame, m_frontFrame);
  58. return true;
  59. }
  60. return false;
  61. }
  62. void Direct3DInterop::UpdateFrame(byte* buffer,int width,int height)
  63. {
  64. std::lock_guard<std::mutex> lock(m_mutex);
  65. if(m_backFrame == nullptr)
  66. {
  67. m_backFrame = std::shared_ptr<cv::Mat> (new cv::Mat(height, width, CV_8UC4));
  68. m_frontFrame = std::shared_ptr<cv::Mat> (new cv::Mat(height, width, CV_8UC4));
  69. }
  70. memcpy(m_backFrame.get()->data, buffer, 4 * height*width);
  71. m_contentDirty = true;
  72. RequestAdditionalFrame();
  73. }
  74. void Direct3DInterop::ProcessFrame()
  75. {
  76. if (SwapFrames())
  77. {
  78. if (m_renderer)
  79. {
  80. cv::Mat* mat = m_frontFrame.get();
  81. switch (m_algorithm)
  82. {
  83. case OCVFilterType::ePreview:
  84. {
  85. break;
  86. }
  87. case OCVFilterType::eGray:
  88. {
  89. ApplyGrayFilter(mat);
  90. break;
  91. }
  92. case OCVFilterType::eCanny:
  93. {
  94. ApplyCannyFilter(mat);
  95. break;
  96. }
  97. case OCVFilterType::eBlur:
  98. {
  99. ApplyBlurFilter(mat);
  100. break;
  101. }
  102. case OCVFilterType::eFindFeatures:
  103. {
  104. ApplyFindFeaturesFilter(mat);
  105. break;
  106. }
  107. case OCVFilterType::eSepia:
  108. {
  109. ApplySepiaFilter(mat);
  110. break;
  111. }
  112. }
  113. m_renderer->CreateTextureFromByte(mat->data, mat->cols, mat->rows);
  114. }
  115. }
  116. }
  117. void Direct3DInterop::ApplyGrayFilter(cv::Mat* mat)
  118. {
  119. cv::Mat intermediateMat;
  120. cv::cvtColor(*mat, intermediateMat, COLOR_RGBA2GRAY);
  121. cv::cvtColor(intermediateMat, *mat, COLOR_GRAY2BGRA);
  122. }
  123. void Direct3DInterop::ApplyCannyFilter(cv::Mat* mat)
  124. {
  125. cv::Mat intermediateMat;
  126. cv::Canny(*mat, intermediateMat, 80, 90);
  127. cv::cvtColor(intermediateMat, *mat, COLOR_GRAY2BGRA);
  128. }
  129. void Direct3DInterop::ApplyBlurFilter(cv::Mat* mat)
  130. {
  131. cv::Mat intermediateMat;
  132. // cv::Blur(image, intermediateMat, 80, 90);
  133. cv::cvtColor(intermediateMat, *mat, COLOR_GRAY2BGRA);
  134. }
  135. void Direct3DInterop::ApplyFindFeaturesFilter(cv::Mat* mat)
  136. {
  137. cv::Mat intermediateMat;
  138. cv::Ptr<cv::FastFeatureDetector> detector = cv::FastFeatureDetector::create(50);
  139. std::vector<cv::KeyPoint> features;
  140. cv::cvtColor(*mat, intermediateMat, COLOR_RGBA2GRAY);
  141. detector->detect(intermediateMat, features);
  142. for( unsigned int i = 0; i < std::min(features.size(), (size_t)50); i++ )
  143. {
  144. const cv::KeyPoint& kp = features[i];
  145. cv::circle(*mat, cv::Point((int)kp.pt.x, (int)kp.pt.y), 10, cv::Scalar(255,0,0,255));
  146. }
  147. }
  148. void Direct3DInterop::ApplySepiaFilter(cv::Mat* mat)
  149. {
  150. const float SepiaKernelData[16] =
  151. {
  152. /* B */0.131f, 0.534f, 0.272f, 0.f,
  153. /* G */0.168f, 0.686f, 0.349f, 0.f,
  154. /* R */0.189f, 0.769f, 0.393f, 0.f,
  155. /* A */0.000f, 0.000f, 0.000f, 1.f
  156. };
  157. const cv::Mat SepiaKernel(4, 4, CV_32FC1, (void*)SepiaKernelData);
  158. cv::transform(*mat, *mat, SepiaKernel);
  159. }
  160. IDrawingSurfaceContentProvider^ Direct3DInterop::CreateContentProvider()
  161. {
  162. ComPtr<Direct3DContentProvider> provider = Make<Direct3DContentProvider>(this);
  163. return reinterpret_cast<IDrawingSurfaceContentProvider^>(provider.Detach());
  164. }
  165. // IDrawingSurfaceManipulationHandler
  166. void Direct3DInterop::SetManipulationHost(DrawingSurfaceManipulationHost^ manipulationHost)
  167. {
  168. manipulationHost->PointerPressed +=
  169. ref new TypedEventHandler<DrawingSurfaceManipulationHost^, PointerEventArgs^>(this, &Direct3DInterop::OnPointerPressed);
  170. manipulationHost->PointerMoved +=
  171. ref new TypedEventHandler<DrawingSurfaceManipulationHost^, PointerEventArgs^>(this, &Direct3DInterop::OnPointerMoved);
  172. manipulationHost->PointerReleased +=
  173. ref new TypedEventHandler<DrawingSurfaceManipulationHost^, PointerEventArgs^>(this, &Direct3DInterop::OnPointerReleased);
  174. }
  175. void Direct3DInterop::RenderResolution::set(Windows::Foundation::Size renderResolution)
  176. {
  177. if (renderResolution.Width != m_renderResolution.Width ||
  178. renderResolution.Height != m_renderResolution.Height)
  179. {
  180. m_renderResolution = renderResolution;
  181. if (m_renderer)
  182. {
  183. m_renderer->UpdateForRenderResolutionChange(m_renderResolution.Width, m_renderResolution.Height);
  184. RecreateSynchronizedTexture();
  185. }
  186. }
  187. }
  188. // Event Handlers
  189. void Direct3DInterop::OnPointerPressed(DrawingSurfaceManipulationHost^ sender, PointerEventArgs^ args)
  190. {
  191. // Insert your code here.
  192. }
  193. void Direct3DInterop::OnPointerMoved(DrawingSurfaceManipulationHost^ sender, PointerEventArgs^ args)
  194. {
  195. // Insert your code here.
  196. }
  197. void Direct3DInterop::OnPointerReleased(DrawingSurfaceManipulationHost^ sender, PointerEventArgs^ args)
  198. {
  199. // Insert your code here.
  200. }
  201. void Direct3DInterop::StartCamera()
  202. {
  203. // Set the capture dimensions
  204. Size captureDimensions;
  205. captureDimensions.Width = 640;
  206. captureDimensions.Height = 480;
  207. // Open the AudioVideoCaptureDevice for video only
  208. IAsyncOperation<AudioVideoCaptureDevice^> ^openOperation = AudioVideoCaptureDevice::OpenForVideoOnlyAsync(CameraSensorLocation::Back, captureDimensions);
  209. openOperation->Completed = ref new AsyncOperationCompletedHandler<AudioVideoCaptureDevice^>(
  210. [this] (IAsyncOperation<AudioVideoCaptureDevice^> ^operation, Windows::Foundation::AsyncStatus status)
  211. {
  212. if (status == Windows::Foundation::AsyncStatus::Completed)
  213. {
  214. auto captureDevice = operation->GetResults();
  215. // Save the reference to the opened video capture device
  216. pAudioVideoCaptureDevice = captureDevice;
  217. // Retrieve the native ICameraCaptureDeviceNative interface from the managed video capture device
  218. ICameraCaptureDeviceNative *iCameraCaptureDeviceNative = NULL;
  219. HRESULT hr = reinterpret_cast<IUnknown*>(captureDevice)->QueryInterface(__uuidof(ICameraCaptureDeviceNative), (void**) &iCameraCaptureDeviceNative);
  220. // Save the pointer to the native interface
  221. pCameraCaptureDeviceNative = iCameraCaptureDeviceNative;
  222. // Initialize the preview dimensions (see the accompanying article at )
  223. // The aspect ratio of the capture and preview resolution must be equal,
  224. // 4:3 for capture => 4:3 for preview, and 16:9 for capture => 16:9 for preview.
  225. Size previewDimensions;
  226. previewDimensions.Width = 640;
  227. previewDimensions.Height = 480;
  228. IAsyncAction^ setPreviewResolutionAction = pAudioVideoCaptureDevice->SetPreviewResolutionAsync(previewDimensions);
  229. setPreviewResolutionAction->Completed = ref new AsyncActionCompletedHandler(
  230. [this](IAsyncAction^ action, Windows::Foundation::AsyncStatus status)
  231. {
  232. HResult hr = action->ErrorCode;
  233. if (status == Windows::Foundation::AsyncStatus::Completed)
  234. {
  235. // Create the sink
  236. MakeAndInitialize<CameraCapturePreviewSink>(&pCameraCapturePreviewSink);
  237. pCameraCapturePreviewSink->SetDelegate(this);
  238. pCameraCaptureDeviceNative->SetPreviewSink(pCameraCapturePreviewSink);
  239. // Set the preview format
  240. pCameraCaptureDeviceNative->SetPreviewFormat(DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM);
  241. }
  242. }
  243. );
  244. // Retrieve IAudioVideoCaptureDeviceNative native interface from managed projection.
  245. IAudioVideoCaptureDeviceNative *iAudioVideoCaptureDeviceNative = NULL;
  246. hr = reinterpret_cast<IUnknown*>(captureDevice)->QueryInterface(__uuidof(IAudioVideoCaptureDeviceNative), (void**) &iAudioVideoCaptureDeviceNative);
  247. // Save the pointer to the IAudioVideoCaptureDeviceNative native interface
  248. pAudioVideoCaptureDeviceNative = iAudioVideoCaptureDeviceNative;
  249. // Set sample encoding format to ARGB. See the documentation for further values.
  250. pAudioVideoCaptureDevice->VideoEncodingFormat = CameraCaptureVideoFormat::Argb;
  251. // Initialize and set the CameraCaptureSampleSink class as sink for captures samples
  252. MakeAndInitialize<CameraCaptureSampleSink>(&pCameraCaptureSampleSink);
  253. pAudioVideoCaptureDeviceNative->SetVideoSampleSink(pCameraCaptureSampleSink);
  254. // Start recording (only way to receive samples using the ICameraCaptureSampleSink interface
  255. pAudioVideoCaptureDevice->StartRecordingToSinkAsync();
  256. }
  257. }
  258. );
  259. }
  260. // Interface With Direct3DContentProvider
  261. HRESULT Direct3DInterop::Connect(_In_ IDrawingSurfaceRuntimeHostNative* host)
  262. {
  263. m_renderer = ref new QuadRenderer();
  264. m_renderer->Initialize();
  265. m_renderer->UpdateForWindowSizeChange(WindowBounds.Width, WindowBounds.Height);
  266. m_renderer->UpdateForRenderResolutionChange(m_renderResolution.Width, m_renderResolution.Height);
  267. StartCamera();
  268. return S_OK;
  269. }
  270. void Direct3DInterop::Disconnect()
  271. {
  272. m_renderer = nullptr;
  273. }
  274. HRESULT Direct3DInterop::PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty)
  275. {
  276. *contentDirty = m_contentDirty;
  277. if(m_contentDirty)
  278. {
  279. ProcessFrame();
  280. }
  281. m_contentDirty = false;
  282. return S_OK;
  283. }
  284. HRESULT Direct3DInterop::GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle)
  285. {
  286. m_renderer->Update();
  287. m_renderer->Render();
  288. return S_OK;
  289. }
  290. ID3D11Texture2D* Direct3DInterop::GetTexture()
  291. {
  292. return m_renderer->GetTexture();
  293. }
  294. }