Direct3DInterop.cpp 12.7 KB
Newer Older
wester committed
1 2 3 4 5 6
#include "pch.h"
#include "Direct3DInterop.h"
#include "Direct3DContentProvider.h"
#include <windows.storage.streams.h>
#include <wrl.h>
#include <robuffer.h>
a  
Kai Westerkamp committed
7 8 9
#include <opencv2\core\core.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv2\features2d\features2d.hpp>
wester committed
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 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
#include <algorithm>

using namespace Windows::Storage::Streams;
using namespace Microsoft::WRL;
using namespace Windows::Foundation;
using namespace Windows::UI::Core;
using namespace Microsoft::WRL;
using namespace Windows::Phone::Graphics::Interop;
using namespace Windows::Phone::Input::Interop;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Phone::Media::Capture;

#if !defined(_M_ARM)
#pragma message("warning: Direct3DInterop.cpp: Windows Phone camera code does not run in the emulator.")
#pragma message("warning: Direct3DInterop.cpp: Please compile as an ARM build and run on a device.")
#endif

namespace PhoneXamlDirect3DApp1Comp
{
    // Called each time a preview frame is available
    void CameraCapturePreviewSink::OnFrameAvailable(
        DXGI_FORMAT format,
        UINT width,
        UINT height,
        BYTE* pixels
        )
    {
        m_Direct3dInterop->UpdateFrame(pixels, width, height);
    }

    // Called each time a captured frame is available
    void CameraCaptureSampleSink::OnSampleAvailable(
        ULONGLONG hnsPresentationTime,
        ULONGLONG hnsSampleDuration,
        DWORD cbSample,
        BYTE* pSample)
    {


    }

    Direct3DInterop::Direct3DInterop()
        : m_algorithm(OCVFilterType::ePreview)
        , m_contentDirty(false)
        , m_backFrame(nullptr)
        , m_frontFrame(nullptr)
    {
    }

    bool Direct3DInterop::SwapFrames()
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        if(m_backFrame != nullptr)
        {
            std::swap(m_backFrame, m_frontFrame);
            return true;
        }
        return false;
    }

    void Direct3DInterop::UpdateFrame(byte* buffer,int width,int height)
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        if(m_backFrame == nullptr)
        {
            m_backFrame = std::shared_ptr<cv::Mat> (new cv::Mat(height, width, CV_8UC4));
            m_frontFrame = std::shared_ptr<cv::Mat> (new cv::Mat(height, width, CV_8UC4));
        }

        memcpy(m_backFrame.get()->data, buffer, 4 * height*width);
        m_contentDirty = true;
        RequestAdditionalFrame();
    }

    void Direct3DInterop::ProcessFrame()
    {
        if (SwapFrames())
        {
            if (m_renderer)
            {
                cv::Mat* mat = m_frontFrame.get();

                switch (m_algorithm)
                {
                    case OCVFilterType::ePreview:
                    {
                        break;
                    }

                    case OCVFilterType::eGray:
                    {
                        ApplyGrayFilter(mat);
                        break;
                    }

                    case OCVFilterType::eCanny:
                    {
                        ApplyCannyFilter(mat);
                        break;
                    }

                    case OCVFilterType::eBlur:
                    {
                        ApplyBlurFilter(mat);
                        break;
                    }

                    case OCVFilterType::eFindFeatures:
                    {
                        ApplyFindFeaturesFilter(mat);
                        break;
                    }

                    case OCVFilterType::eSepia:
                    {
                        ApplySepiaFilter(mat);
                        break;
                    }
                }

                m_renderer->CreateTextureFromByte(mat->data, mat->cols, mat->rows);
            }
        }
    }

    void Direct3DInterop::ApplyGrayFilter(cv::Mat* mat)
    {
        cv::Mat intermediateMat;
        cv::cvtColor(*mat, intermediateMat, CV_RGBA2GRAY);
        cv::cvtColor(intermediateMat, *mat, CV_GRAY2BGRA);
    }

    void Direct3DInterop::ApplyCannyFilter(cv::Mat* mat)
    {
        cv::Mat intermediateMat;
        cv::Canny(*mat, intermediateMat, 80, 90);
        cv::cvtColor(intermediateMat, *mat, CV_GRAY2BGRA);
    }

    void Direct3DInterop::ApplyBlurFilter(cv::Mat* mat)
    {
        cv::Mat intermediateMat;
        //	cv::Blur(image, intermediateMat, 80, 90);
        cv::cvtColor(intermediateMat, *mat, CV_GRAY2BGRA);
    }

    void Direct3DInterop::ApplyFindFeaturesFilter(cv::Mat* mat)
    {
        cv::Mat intermediateMat;
        cv::Ptr<cv::FastFeatureDetector> detector = cv::FastFeatureDetector::create(50);
        std::vector<cv::KeyPoint> features;

        cv::cvtColor(*mat, intermediateMat, CV_RGBA2GRAY);
        detector->detect(intermediateMat, features);

        for( unsigned int i = 0; i < std::min(features.size(), (size_t)50); i++ )
        {
            const cv::KeyPoint& kp = features[i];
            cv::circle(*mat, cv::Point((int)kp.pt.x, (int)kp.pt.y), 10, cv::Scalar(255,0,0,255));
        }
    }

    void Direct3DInterop::ApplySepiaFilter(cv::Mat* mat)
    {
        const float SepiaKernelData[16] =
        {
            /* B */0.131f, 0.534f, 0.272f, 0.f,
            /* G */0.168f, 0.686f, 0.349f, 0.f,
            /* R */0.189f, 0.769f, 0.393f, 0.f,
            /* A */0.000f, 0.000f, 0.000f, 1.f
        };

        const cv::Mat SepiaKernel(4, 4, CV_32FC1, (void*)SepiaKernelData);
        cv::transform(*mat, *mat, SepiaKernel);
    }

    IDrawingSurfaceContentProvider^ Direct3DInterop::CreateContentProvider()
    {
        ComPtr<Direct3DContentProvider> provider = Make<Direct3DContentProvider>(this);
        return reinterpret_cast<IDrawingSurfaceContentProvider^>(provider.Detach());
    }

    // IDrawingSurfaceManipulationHandler
    void Direct3DInterop::SetManipulationHost(DrawingSurfaceManipulationHost^ manipulationHost)
    {
        manipulationHost->PointerPressed +=
            ref new TypedEventHandler<DrawingSurfaceManipulationHost^, PointerEventArgs^>(this, &Direct3DInterop::OnPointerPressed);

        manipulationHost->PointerMoved +=
            ref new TypedEventHandler<DrawingSurfaceManipulationHost^, PointerEventArgs^>(this, &Direct3DInterop::OnPointerMoved);

        manipulationHost->PointerReleased +=
            ref new TypedEventHandler<DrawingSurfaceManipulationHost^, PointerEventArgs^>(this, &Direct3DInterop::OnPointerReleased);
    }

    void Direct3DInterop::RenderResolution::set(Windows::Foundation::Size renderResolution)
    {
        if (renderResolution.Width  != m_renderResolution.Width ||
            renderResolution.Height != m_renderResolution.Height)
        {
            m_renderResolution = renderResolution;

            if (m_renderer)
            {
                m_renderer->UpdateForRenderResolutionChange(m_renderResolution.Width, m_renderResolution.Height);
                RecreateSynchronizedTexture();
            }
        }
    }

    // Event Handlers

    void Direct3DInterop::OnPointerPressed(DrawingSurfaceManipulationHost^ sender, PointerEventArgs^ args)
    {
        // Insert your code here.
    }

    void Direct3DInterop::OnPointerMoved(DrawingSurfaceManipulationHost^ sender, PointerEventArgs^ args)
    {
        // Insert your code here.
    }

    void Direct3DInterop::OnPointerReleased(DrawingSurfaceManipulationHost^ sender, PointerEventArgs^ args)
    {
        // Insert your code here.
    }

    void Direct3DInterop::StartCamera()
    {
        // Set the capture dimensions
        Size captureDimensions;
        captureDimensions.Width = 640;
        captureDimensions.Height = 480;

        // Open the AudioVideoCaptureDevice for video only
        IAsyncOperation<AudioVideoCaptureDevice^> ^openOperation = AudioVideoCaptureDevice::OpenForVideoOnlyAsync(CameraSensorLocation::Back, captureDimensions);

        openOperation->Completed = ref new AsyncOperationCompletedHandler<AudioVideoCaptureDevice^>(
            [this] (IAsyncOperation<AudioVideoCaptureDevice^> ^operation, Windows::Foundation::AsyncStatus status)
            {
                if (status == Windows::Foundation::AsyncStatus::Completed)
                {
                    auto captureDevice = operation->GetResults();

                    // Save the reference to the opened video capture device
                    pAudioVideoCaptureDevice = captureDevice;

                    // Retrieve the native ICameraCaptureDeviceNative interface from the managed video capture device
                    ICameraCaptureDeviceNative *iCameraCaptureDeviceNative = NULL;
                    HRESULT hr = reinterpret_cast<IUnknown*>(captureDevice)->QueryInterface(__uuidof(ICameraCaptureDeviceNative), (void**) &iCameraCaptureDeviceNative);

                    // Save the pointer to the native interface
                    pCameraCaptureDeviceNative = iCameraCaptureDeviceNative;

                    // Initialize the preview dimensions (see the accompanying article at )
                    // The aspect ratio of the capture and preview resolution must be equal,
                    // 4:3 for capture => 4:3 for preview, and 16:9 for capture => 16:9 for preview.
                    Size previewDimensions;
                    previewDimensions.Width = 640;
                    previewDimensions.Height = 480;

                    IAsyncAction^ setPreviewResolutionAction = pAudioVideoCaptureDevice->SetPreviewResolutionAsync(previewDimensions);
                    setPreviewResolutionAction->Completed = ref new AsyncActionCompletedHandler(
                        [this](IAsyncAction^ action, Windows::Foundation::AsyncStatus status)
                        {
                            HResult hr = action->ErrorCode;

                            if (status == Windows::Foundation::AsyncStatus::Completed)
                            {
                                // Create the sink
                                MakeAndInitialize<CameraCapturePreviewSink>(&pCameraCapturePreviewSink);
                                pCameraCapturePreviewSink->SetDelegate(this);
                                pCameraCaptureDeviceNative->SetPreviewSink(pCameraCapturePreviewSink);

                                // Set the preview format
                                pCameraCaptureDeviceNative->SetPreviewFormat(DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM);
                            }
                        }
                    );

                    // Retrieve IAudioVideoCaptureDeviceNative native interface from managed projection.
                    IAudioVideoCaptureDeviceNative *iAudioVideoCaptureDeviceNative = NULL;
                    hr = reinterpret_cast<IUnknown*>(captureDevice)->QueryInterface(__uuidof(IAudioVideoCaptureDeviceNative), (void**) &iAudioVideoCaptureDeviceNative);

                    // Save the pointer to the IAudioVideoCaptureDeviceNative native interface
                    pAudioVideoCaptureDeviceNative = iAudioVideoCaptureDeviceNative;

                    // Set sample encoding format to ARGB. See the documentation for further values.
                    pAudioVideoCaptureDevice->VideoEncodingFormat = CameraCaptureVideoFormat::Argb;

                    // Initialize and set the CameraCaptureSampleSink class as sink for captures samples
                    MakeAndInitialize<CameraCaptureSampleSink>(&pCameraCaptureSampleSink);
                    pAudioVideoCaptureDeviceNative->SetVideoSampleSink(pCameraCaptureSampleSink);

                    // Start recording (only way to receive samples using the ICameraCaptureSampleSink interface
                    pAudioVideoCaptureDevice->StartRecordingToSinkAsync();
                }
            }
        );

    }
    // Interface With Direct3DContentProvider
    HRESULT Direct3DInterop::Connect(_In_ IDrawingSurfaceRuntimeHostNative* host)
    {
        m_renderer = ref new QuadRenderer();
        m_renderer->Initialize();
        m_renderer->UpdateForWindowSizeChange(WindowBounds.Width, WindowBounds.Height);
        m_renderer->UpdateForRenderResolutionChange(m_renderResolution.Width, m_renderResolution.Height);
        StartCamera();

        return S_OK;
    }

    void Direct3DInterop::Disconnect()
    {
        m_renderer = nullptr;
    }

    HRESULT Direct3DInterop::PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty)
    {
        *contentDirty = m_contentDirty;
        if(m_contentDirty)
        {
            ProcessFrame();
        }
        m_contentDirty = false;
        return S_OK;
    }

    HRESULT Direct3DInterop::GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle)
    {
        m_renderer->Update();
        m_renderer->Render();
        return S_OK;
    }

    ID3D11Texture2D* Direct3DInterop::GetTexture()
    {
        return m_renderer->GetTexture();
    }
}