Renderer.cpp 14.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
Renderer.cpp

mediastreamer2 library - modular sound and video processing and streaming
Windows Audio Session API sound card plugin for mediastreamer2
Copyright (C) 2010-2015 Belledonne Communications, Grenoble, France

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
20
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 22 23 24 25 26 27 28 29 30 31 32 33
*/

#include "Renderer.h"
#include "ScopeLock.h"

#include <mediastreamer2/mscommon.h>

using namespace libmswinrtvid;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace ABI::Windows::Foundation::Collections;


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
MSWinRTExtensionManager^ MSWinRTExtensionManager::_instance = ref new MSWinRTExtensionManager();

MSWinRTExtensionManager::MSWinRTExtensionManager()
	: mMediaExtensionManager(nullptr), mExtensionManagerProperties(nullptr)
{
}

MSWinRTExtensionManager::~MSWinRTExtensionManager()
{
}

Platform::Boolean MSWinRTExtensionManager::Setup()
{
	if ((mMediaExtensionManager != nullptr) && (mExtensionManagerProperties != nullptr)) return true;

	using Windows::Foundation::ActivateInstance;
	HRESULT hr = ActivateInstance(HStringReference(RuntimeClass_Windows_Media_MediaExtensionManager).Get(), mMediaExtensionManager.ReleaseAndGetAddressOf());
	if (FAILED(hr)) {
		ms_error("MSWinRTExtensionManager::Setup: Failed to create media extension manager %x", hr);
		return false;
	}
	ComPtr<IMap<HSTRING, IInspectable*>> props;
	hr = ActivateInstance(HStringReference(RuntimeClass_Windows_Foundation_Collections_PropertySet).Get(), props.ReleaseAndGetAddressOf());
	ComPtr<IPropertySet> propSet;
	props.As(&propSet);
59
	HStringReference clsid(L"MSWinRTVideo.SchemeHandler");
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
	HStringReference scheme(L"mswinrtvid:");
	hr = mMediaExtensionManager->RegisterSchemeHandlerWithSettings(clsid.Get(), scheme.Get(), propSet.Get());
	if (FAILED(hr)) {
		ms_error("MSWinRTExtensionManager::Setup: RegisterSchemeHandlerWithSettings failed %x", hr);
		return false;
	}
	mExtensionManagerProperties = props;
	return true;
}

Platform::Boolean MSWinRTExtensionManager::RegisterUrl(Platform::String^ url, Windows::Media::Core::MediaStreamSource^ source)
{
	boolean replaced;
	auto streamInspect = reinterpret_cast<IInspectable*>(source);
	return mExtensionManagerProperties->Insert(HStringReference(url->Data()).Get(), streamInspect, &replaced) == S_OK;
}

Platform::Boolean MSWinRTExtensionManager::UnregisterUrl(Platform::String^ url)
{
	return mExtensionManagerProperties->Remove(HStringReference(url->Data()).Get()) == S_OK;
}



84
MSWinRTRenderer::MSWinRTRenderer() :
85
	mMediaStreamSource(nullptr), mMediaEngine(nullptr), mUrl(nullptr),
86 87 88 89 90 91 92
	mForegroundProcess(nullptr), mMemoryMapping(nullptr), mSharedData(nullptr), mLock(nullptr), mShutdownEvent(nullptr), mEventAvailableEvent(nullptr)
{
}

MSWinRTRenderer::~MSWinRTRenderer()
{
	Close();
93
	mUrl = nullptr;
94 95
}

96
void MSWinRTRenderer::SetSwapChainPanel()
97 98
{
	Close();
99
	if (mSwapChainPanelName == nullptr) return;
100

101
	mMemoryMapping = OpenFileMappingFromApp(FILE_MAP_READ | FILE_MAP_WRITE, TRUE, mSwapChainPanelName->Data());
102 103 104 105
	if ((mMemoryMapping == nullptr) || (mMemoryMapping == INVALID_HANDLE_VALUE)) {
		DWORD error = GetLastError();
		throw ref new Platform::COMException(HRESULT_FROM_WIN32(error));
	}
106
	mSharedData = (MSWinRTVideo::SharedData*)MapViewOfFileFromApp(mMemoryMapping, FILE_MAP_READ | FILE_MAP_WRITE, 0LL, sizeof(*mSharedData));
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
	if (mSharedData == nullptr) {
		DWORD error = GetLastError();
		Close();
		throw ref new Platform::COMException(HRESULT_FROM_WIN32(error));
	}
	mSharedData->backgroundProcessId = GetCurrentProcessId();
	mForegroundProcess = OpenProcess(PROCESS_DUP_HANDLE, TRUE, mSharedData->foregroundProcessId);
	if ((mForegroundProcess == nullptr) || (mForegroundProcess == INVALID_HANDLE_VALUE)) {
		DWORD error = GetLastError();
		Close();
		throw ref new Platform::COMException(HRESULT_FROM_WIN32(error));
	}
	if (!DuplicateHandle(mForegroundProcess, mSharedData->foregroundLockMutex, GetCurrentProcess(), &mLock, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
		DWORD error = GetLastError();
		mLock = nullptr;
		Close();
		throw ref new Platform::COMException(HRESULT_FROM_WIN32(error));
	}
	if (!DuplicateHandle(mForegroundProcess, mSharedData->foregroundShutdownEvent, GetCurrentProcess(), &mShutdownEvent, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
		DWORD error = GetLastError();
		mLock = nullptr;
		Close();
		throw ref new Platform::COMException(HRESULT_FROM_WIN32(error));
	}
131 132 133 134 135 136
	if (!DuplicateHandle(mForegroundProcess, mSharedData->foregroundShutdownCompleteEvent, GetCurrentProcess(), &mShutdownCompleteEvent, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
		DWORD error = GetLastError();
		mLock = nullptr;
		Close();
		throw ref new Platform::COMException(HRESULT_FROM_WIN32(error));
	}
137 138 139 140 141 142
	if (!DuplicateHandle(mForegroundProcess, mSharedData->foregroundEventAvailableEvent, GetCurrentProcess(), &mEventAvailableEvent, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
		DWORD error = GetLastError();
		mLock = nullptr;
		Close();
		throw ref new Platform::COMException(HRESULT_FROM_WIN32(error));
	}
143 144 145 146 147 148
	if (!DuplicateHandle(mForegroundProcess, mSharedData->foregroundCommandAvailableEvent, GetCurrentProcess(), &mCommandAvailableEvent, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
		DWORD error = GetLastError();
		mLock = nullptr;
		Close();
		throw ref new Platform::COMException(HRESULT_FROM_WIN32(error));
	}
149 150 151 152
}

void MSWinRTRenderer::Close()
{
Ghislain MARY's avatar
Ghislain MARY committed
153 154 155
	if (mMediaEngineNotify != nullptr)
	{
		mMediaEngineNotify->SetCallback(nullptr);
156
		mMediaEngineNotify = nullptr;
Ghislain MARY's avatar
Ghislain MARY committed
157
	}
158 159 160
	if (mMediaEngine != nullptr)
	{
		mMediaEngine->Shutdown();
161 162 163 164 165
		mMediaEngine = nullptr;
	}
	if (mMediaEngineEx != nullptr)
	{
		mMediaEngineEx = nullptr;
166 167 168 169 170 171
	}
	if (mUrl != nullptr)
	{
		MSWinRTExtensionManager::Instance->UnregisterUrl(mUrl);
		mUrl = nullptr;
	}
Ghislain MARY's avatar
Ghislain MARY committed
172 173 174 175 176
	if (mMediaStreamSource != nullptr)
	{
		mMediaStreamSource->Stop();
		mMediaStreamSource = nullptr;
	}
177 178 179 180 181 182
	if (mDevice != nullptr) {
		mDevice = nullptr;
	}
	if (mDxGIManager != nullptr) {
		mDxGIManager = nullptr;
	}
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
	if (mSharedData != nullptr)
	{
		UnmapViewOfFile(mSharedData);
		mSharedData = nullptr;
	}
	if (mMemoryMapping != nullptr)
	{
		CloseHandle(mMemoryMapping);
		mMemoryMapping = nullptr;
	}
	if (mLock != nullptr)
	{
		CloseHandle(mLock);
		mLock = nullptr;
	}
	if (mShutdownEvent != nullptr)
	{
		CloseHandle(mShutdownEvent);
		mShutdownEvent = nullptr;
	}
	if (mEventAvailableEvent != nullptr)
	{
		CloseHandle(mEventAvailableEvent);
		mEventAvailableEvent = nullptr;
	}
	if (mForegroundProcess != nullptr)
	{
		CloseHandle(mForegroundProcess);
		mForegroundProcess = nullptr;
	}
214 215 216 217 218 219 220 221 222 223 224
	if (mShutdownCompleteEvent != nullptr)
	{
		SetEvent(mShutdownCompleteEvent);
		mShutdownCompleteEvent = nullptr;
	}
	if (mCommandAvailableEvent != nullptr)
	{
		CloseHandle(mCommandAvailableEvent);
		mCommandAvailableEvent = nullptr;
	}
	mSwapChainHandle.Close();
225 226 227 228
}

bool MSWinRTRenderer::Start()
{
229
	SetSwapChainPanel();
230
	mFrameWidth = mFrameHeight = mSwapChainPanelWidth = mSwapChainPanelHeight = 0;
231
	HRESULT hr = MSWinRTExtensionManager::Instance->Setup() ? S_OK : E_FAIL;
232 233 234 235 236 237 238 239 240 241
	if (FAILED(hr)) {
		SendErrorEvent(hr);
		return false;
	}
	hr = SetupDirectX();
	if (FAILED(hr)) {
		SendErrorEvent(hr);
		return false;
	}
	mMediaStreamSource = MediaStreamSource::CreateMediaSource();
242
	mUrl = "mswinrtvid://";
243 244 245 246 247 248 249
	GUID result;
	hr = CoCreateGuid(&result);
	if (FAILED(hr)) {
		SendErrorEvent(hr);
		return false;
	}
	Platform::Guid gd(result);
250 251
	mUrl += gd.ToString();
	hr = MSWinRTExtensionManager::Instance->RegisterUrl(mUrl, mMediaStreamSource->Source) ? S_OK : E_FAIL;
252 253 254 255 256
	if (FAILED(hr)) {
		SendErrorEvent(hr);
		return false;
	}
	BSTR sourceBSTR;
257
	sourceBSTR = SysAllocString(mUrl->Data());
258 259 260
	hr = mMediaEngine->SetSource(sourceBSTR);
	SysFreeString(sourceBSTR);
	if (FAILED(hr)) {
261
		ms_error("MSWinRTRenderer::Start: Media engine SetSource failed %x", hr);
262 263 264 265 266
		SendErrorEvent(hr);
		return false;
	}
	hr = mMediaEngine->Load();
	if (FAILED(hr)) {
267
		ms_error("MSWinRTRenderer::Start: Media engine Load failed %x", hr);
268 269 270 271 272 273
		SendErrorEvent(hr);
		return false;
	}
	return true;
}

Ghislain MARY's avatar
Ghislain MARY committed
274 275 276 277 278
void MSWinRTRenderer::Stop()
{
	Close();
}

279 280
void MSWinRTRenderer::Feed(Windows::Storage::Streams::IBuffer^ pBuffer, int width, int height)
{
281
	if ((mMediaStreamSource != nullptr) && (mSharedData != nullptr) && (mMediaEngineEx != nullptr)) {
282
		bool sizeChanged = false;
283 284 285 286 287 288
		HRESULT hr = mDevice->GetDeviceRemovedReason();
		if (FAILED(hr)) {
			ms_error("MSWinRTRenderer::Feed: Device lost %x", hr);
			Stop();
			Start();
		}
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
		if ((width != mFrameWidth) || (height != mFrameHeight)) {
			mFrameWidth = width;
			mFrameHeight = height;
			sizeChanged = true;
		}
		if ((mSharedData->width != mSwapChainPanelWidth) || (mSharedData->height != mSwapChainPanelHeight)) {
			mSwapChainPanelWidth = mSharedData->width;
			mSwapChainPanelHeight = mSharedData->height;
			sizeChanged = true;
		}
		if (sizeChanged) {
			MFVideoNormalizedRect srcSize = { 0.f, 0.f, (float)width, (float)height };
			RECT dstSize = { 0, 0, mSwapChainPanelWidth, mSwapChainPanelHeight };
			MFARGB backgroundColor = { 0, 0, 0, 0 };
			mMediaEngineEx->UpdateVideoStream(&srcSize, &dstSize, &backgroundColor);
		}
305

306 307 308 309 310 311 312 313 314
		mMediaStreamSource->Feed(pBuffer, width, height);
	}
}

HRESULT MSWinRTRenderer::SetupDirectX()
{
	mUseHardware = true;
	HRESULT hr = MFStartup(MF_VERSION);
	if (FAILED(hr)) {
315
		ms_error("MSWinRTRenderer::SetupDirectX: MFStartup failed %x", hr);
316 317 318 319 320 321
		return hr;
	}
	hr = CreateDX11Device();
	if (FAILED(hr)) {
		return hr;
	}
322
	hr = MFCreateDXGIDeviceManager(&mResetToken, &mDxGIManager);
323
	if (FAILED(hr)) {
324
		ms_error("MSWinRTRenderer::SetupDirectX: MFCreateDXGIDeviceManager failed %x", hr);
325 326
		return hr;
	}
327
	hr = mDxGIManager->ResetDevice(mDevice.Get(), mResetToken);
328
	if (FAILED(hr)) {
329
		ms_error("MSWinRTRenderer::SetupDirectX: ResetDevice failed %x", hr);
330 331 332
		return hr;
	}
	ComPtr<IMFMediaEngineClassFactory> factory;
333
	hr = CoCreateInstance(CLSID_MFMediaEngineClassFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&factory));
334
	if (FAILED(hr)) {
335
		ms_error("MSWinRTRenderer::SetupDirectX: CoCreateInstance failed %x", hr);
336 337 338 339 340
		return hr;
	}
	ComPtr<IMFAttributes> attributes;
	hr = MFCreateAttributes(&attributes, 3);
	if (FAILED(hr)) {
341
		ms_error("MSWinRTRenderer::SetupDirectX: MFCreateAttributes failed %x", hr);
342 343 344 345
		return hr;
	}
	hr = attributes->SetUnknown(MF_MEDIA_ENGINE_DXGI_MANAGER, (IUnknown*)mDxGIManager.Get());
	if (FAILED(hr)) {
346
		ms_error("MSWinRTRenderer::SetupDirectX: Set MF_MEDIA_ENGINE_DXGI_MANAGER attribute failed %x", hr);
347 348
		return hr;
	}
Ghislain MARY's avatar
Ghislain MARY committed
349 350
	mMediaEngineNotify = Make<MediaEngineNotify>();
	mMediaEngineNotify->SetCallback(this);
351 352
	hr = attributes->SetUINT32(MF_MEDIA_ENGINE_VIDEO_OUTPUT_FORMAT, DXGI_FORMAT_NV12);
	if (FAILED(hr)) {
353
		ms_error("MSWinRTRenderer::SetupDirectX: Set MF_MEDIA_ENGINE_VIDEO_OUTPUT_FORMAT attribute failed %x", hr);
354 355
		return hr;
	}
Ghislain MARY's avatar
Ghislain MARY committed
356
	hr = attributes->SetUnknown(MF_MEDIA_ENGINE_CALLBACK, (IUnknown*)mMediaEngineNotify.Get());
357
	if (FAILED(hr)) {
358
		ms_error("MSWinRTRenderer::SetupDirectX: Set MF_MEDIA_ENGINE_CALLBACK attribute failed %x", hr);
359 360
		return hr;
	}
361
	hr = factory->CreateInstance(MF_MEDIA_ENGINE_REAL_TIME_MODE, attributes.Get(), &mMediaEngine);
362
	if (FAILED(hr)) {
363
		ms_error("MSWinRTRenderer::SetupDirectX: CreateInstance failed %x", hr);
364 365 366 367
		return hr;
	}
	hr = mMediaEngine.Get()->QueryInterface(__uuidof(IMFMediaEngineEx), (void**)&mMediaEngineEx);
	if (FAILED(hr)) {
368
		ms_error("MSWinRTRenderer::SetupDirectX: QueryInterface failed %x", hr);
369 370 371 372
		return hr;
	}
	hr = mMediaEngineEx->EnableWindowlessSwapchainMode(TRUE);
	if (FAILED(hr)) {
373
		ms_error("MSWinRTRenderer::SetupDirectX: EnableWindowlessSwapchainMode failed %x", hr);
374 375 376 377 378 379 380 381 382 383 384
		return hr;
	}
	return S_OK;
}

HRESULT MSWinRTRenderer::CreateDX11Device()
{
	static const D3D_FEATURE_LEVEL levels[] = {
		D3D_FEATURE_LEVEL_11_1,
		D3D_FEATURE_LEVEL_11_0,
		D3D_FEATURE_LEVEL_10_1,
385 386 387 388
		D3D_FEATURE_LEVEL_10_0,
		D3D_FEATURE_LEVEL_9_3,
		D3D_FEATURE_LEVEL_9_2,
		D3D_FEATURE_LEVEL_9_1
389 390 391
	};
	D3D_FEATURE_LEVEL FeatureLevel;
	HRESULT hr = S_OK;
392
	UINT createFlag = D3D11_CREATE_DEVICE_VIDEO_SUPPORT;
393 394

	if (mUseHardware) {
395
		hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createFlag, levels, ARRAYSIZE(levels), D3D11_SDK_VERSION, &mDevice, &FeatureLevel, nullptr);
396 397 398
	}

	if (FAILED(hr)) {
399
		ms_warning("MSWinRTRenderer::CreateDX11Device: Failed to create hardware device, falling back to software %x", hr);
400 401 402 403
		mUseHardware = false;
	}

	if (!mUseHardware) {
404
		hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, createFlag, levels, ARRAYSIZE(levels), D3D11_SDK_VERSION, &mDevice, &FeatureLevel, nullptr);
405
		if (FAILED(hr)) {
406
			ms_error("MSWinRTRenderer::CreateDX11Device: Failed to create WARP device %x", hr);
407 408 409 410 411 412 413 414
			return hr;
		}
	}

	if (mUseHardware) {
		ComPtr<ID3D10Multithread> multithread;
		hr = mDevice.Get()->QueryInterface(IID_PPV_ARGS(&multithread));
		if (FAILED(hr)) {
415
			ms_error("MSWinRTRenderer::CreateDX11Device: Failed to set hardware to multithreaded %x", hr);
416 417 418 419 420 421 422
			return hr;
		}
		multithread->SetMultithreadProtected(TRUE);
	}
	return hr;
}

423
void MSWinRTRenderer::SendSwapChainHandle(HANDLE swapChain)
424 425 426 427
{
	if ((swapChain == nullptr) || (swapChain == INVALID_HANDLE_VALUE)) return;

	ScopeLock lock(mLock);
428 429 430 431
	mSwapChainHandle.AssignHandle(swapChain, mSharedData->foregroundProcessId);
	HANDLE remoteHandle = mSwapChainHandle.GetRemoteHandle();
	if (remoteHandle != mSharedData->foregroundSwapChainHandle) {
		mSharedData->foregroundSwapChainHandle = remoteHandle;
432 433 434 435 436 437 438
		SetEvent(mEventAvailableEvent);
	}
}

void MSWinRTRenderer::SendErrorEvent(HRESULT hr)
{
	ScopeLock lock(mLock);
439
	if (mSharedData) mSharedData->error = hr;
440
	SetEvent(mEventAvailableEvent);
441 442 443 444 445 446 447 448
}

void MSWinRTRenderer::OnMediaEngineEvent(uint32 meEvent, uintptr_t param1, uint32 param2)
{
	HRESULT hr;
	HANDLE swapChainHandle;
	switch ((DWORD)meEvent) {
	case MF_MEDIA_ENGINE_EVENT_ERROR:
449
		ms_message("MSWinRTRenderer::OnMediaEngineEvent: Error");
450
		//SendErrorEvent((HRESULT)param2);
451 452 453 454
		break;
	case MF_MEDIA_ENGINE_EVENT_PLAYING:
	case MF_MEDIA_ENGINE_EVENT_FIRSTFRAMEREADY:
		mMediaEngineEx->GetVideoSwapchainHandle(&swapChainHandle);
455
		SendSwapChainHandle(swapChainHandle);
456 457 458
		break;
	case MF_MEDIA_ENGINE_EVENT_FORMATCHANGE:
		mMediaEngineEx->GetVideoSwapchainHandle(&swapChainHandle);
459
		ms_message("MSWinRTRenderer::OnMediaEngineEvent: Format change");
460
		SendSwapChainHandle(swapChainHandle);
461 462 463 464
		break;
	case MF_MEDIA_ENGINE_EVENT_CANPLAY:
		hr = mMediaEngine->Play();
		if (FAILED(hr)) {
465
			ms_error("MSWinRTRenderer::OnMediaEngineEvent: Error on play");
466 467 468 469 470
			SendErrorEvent(hr);
		}
		break;
	}
}