mswinrtmediasink.cpp 33.2 KB
Newer Older
1
#include "mswinrtmediasink.h"
2
#include "mswinrtcap.h"
3 4 5
#include <mediastreamer2/mscommon.h>

using namespace libmswinrtvid;
6
using namespace Windows::Foundation;
7 8


9 10 11 12
//#define MSWINRTMEDIASINK_DEBUG ms_message
#define MSWINRTMEDIASINK_DEBUG(...)


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
#define RETURN_HR(hr) { \
	if (FAILED(hr)) \
		ms_error("%s:%d -> 0x%x", __FUNCTION__, __LINE__, hr); \
	return hr; \
}


static void AddAttribute(_In_ GUID guidKey, _In_ IPropertyValue ^value, _In_ IMFAttributes *pAttr)
{
	HRESULT hr = S_OK;
	PropertyType type = value->Type;
	switch (type) {
	case PropertyType::UInt8Array:
		{
			Array<BYTE>^ arr;
			value->GetUInt8Array(&arr);
			hr = pAttr->SetBlob(guidKey, arr->Data, arr->Length);
		}
		break;
	case PropertyType::Double:
		hr = pAttr->SetDouble(guidKey, value->GetDouble());
		break;
	case PropertyType::Guid:
		hr = pAttr->SetGUID(guidKey, value->GetGuid());
		break;
	case PropertyType::String:
		hr = pAttr->SetString(guidKey, value->GetString()->Data());
		break;
	case PropertyType::UInt32:
		hr = pAttr->SetUINT32(guidKey, value->GetUInt32());
		break;
	case PropertyType::UInt64:
		hr = pAttr->SetUINT64(guidKey, value->GetUInt64());
		break;
	// ignore unknown values
	}

	if (FAILED(hr))
		throw ref new Exception(hr);
}

static void ConvertPropertiesToMediaType(_In_ IMediaEncodingProperties ^mep, _Outptr_ IMFMediaType **ppMT)
{
	if (mep == nullptr || ppMT == nullptr)
		throw ref new InvalidArgumentException();

	ComPtr<IMFMediaType> spMT;
	*ppMT = nullptr;
	HRESULT hr = MFCreateMediaType(&spMT);
	if (FAILED(hr))
		throw ref new Exception(hr);

	auto it = mep->Properties->First();
	while (it->HasCurrent) {
		auto currentValue = it->Current;
		AddAttribute(currentValue->Key, safe_cast<IPropertyValue^>(currentValue->Value), spMT.Get());
		it->MoveNext();
	}

	GUID guiMajorType = safe_cast<IPropertyValue^>(mep->Properties->Lookup(MF_MT_MAJOR_TYPE))->GetGuid();
	if (guiMajorType != MFMediaType_Video)
		throw ref new Exception(E_UNEXPECTED);

	*ppMT = spMT.Detach();
}




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
MSWinRTMarker::MSWinRTMarker(MFSTREAMSINK_MARKER_TYPE eMarkerType) : _cRef(1), _eMarkerType(eMarkerType)
{
	ZeroMemory(&_varMarkerValue, sizeof(_varMarkerValue));
	ZeroMemory(&_varContextValue, sizeof(_varContextValue));
}

MSWinRTMarker::~MSWinRTMarker()
{
	PropVariantClear(&_varMarkerValue);
	PropVariantClear(&_varContextValue);
}

HRESULT MSWinRTMarker::Create(MFSTREAMSINK_MARKER_TYPE eMarkerType, const PROPVARIANT *pvarMarkerValue, const PROPVARIANT *pvarContextValue, IMarker **ppMarker)
{
	if (ppMarker == nullptr)
		return E_POINTER;

	HRESULT hr = S_OK;
	ComPtr<MSWinRTMarker> spMarker;

	spMarker.Attach(new (std::nothrow) MSWinRTMarker(eMarkerType));
	if (spMarker == nullptr)
		hr = E_OUTOFMEMORY;
	// Copy the marker data.
	if (SUCCEEDED(hr)) {
		if (pvarMarkerValue)
			hr = PropVariantCopy(&spMarker->_varMarkerValue, pvarMarkerValue);
	}
	if (SUCCEEDED(hr)) {
		if (pvarContextValue)
			hr = PropVariantCopy(&spMarker->_varContextValue, pvarContextValue);
	}
	if (SUCCEEDED(hr))
		*ppMarker = spMarker.Detach();
	return hr;
}

// IUnknown methods.

IFACEMETHODIMP_(ULONG) MSWinRTMarker::AddRef()
{
	return InterlockedIncrement(&_cRef);
}

IFACEMETHODIMP_(ULONG) MSWinRTMarker::Release()
{
	ULONG cRef = InterlockedDecrement(&_cRef);
	if (cRef == 0)
		delete this;
	return cRef;
}

IFACEMETHODIMP MSWinRTMarker::QueryInterface(REFIID riid, void **ppv)
{
	if (ppv == nullptr)
		return E_POINTER;
	(*ppv) = nullptr;

	HRESULT hr = S_OK;
	if (riid == IID_IUnknown || riid == __uuidof(IMarker)) {
		(*ppv) = static_cast<IMarker*>(this);
		AddRef();
	} else {
		hr = E_NOINTERFACE;
	}
	return hr;
}

// IMarker methods.

IFACEMETHODIMP MSWinRTMarker::GetMarkerType(MFSTREAMSINK_MARKER_TYPE *pType)
{
	if (pType == NULL)
		return E_POINTER;
	*pType = _eMarkerType;
	return S_OK;
}

IFACEMETHODIMP MSWinRTMarker::GetMarkerValue(PROPVARIANT *pvar)
{
	if (pvar == NULL)
		return E_POINTER;
	return PropVariantCopy(pvar, &_varMarkerValue);

}

IFACEMETHODIMP MSWinRTMarker::GetContext(PROPVARIANT *pvar)
{
	if (pvar == NULL)
		return E_POINTER;
	return PropVariantCopy(pvar, &_varContextValue);
}




178 179 180 181 182 183 184 185 186 187 188 189 190 191

MSWinRTStreamSink::MSWinRTStreamSink(DWORD dwIdentifier)
	: _cRef(1)
	, _dwIdentifier(dwIdentifier)
	, _state(State_TypeNotSet)
	, _IsShutdown(false)
	, _fGetStartTimeFromSample(false)
	, _fWaitingForFirstSample(false)
	, _fFirstSampleAfterConnect(false)
	, _StartTime(0)
	, _WorkQueueId(0)
	, _pParent(nullptr)
#pragma warning(push)
#pragma warning(disable:4355)
192
	, _WorkQueueCB(this, &MSWinRTStreamSink::OnDispatchWorkItem)
193 194 195
#pragma warning(pop)
{
	ZeroMemory(&_guiCurrentSubtype, sizeof(_guiCurrentSubtype));
196
	_guiCurrentFrameSize = 0;
197
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink constructor");
198 199 200 201
}

MSWinRTStreamSink::~MSWinRTStreamSink()
{
202
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink destructor");
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
MSWinRTStreamSink::MSWinRTAsyncOperation::MSWinRTAsyncOperation(StreamOperation op)
	: _cRef(1), m_op(op)
{
}

MSWinRTStreamSink::MSWinRTAsyncOperation::~MSWinRTAsyncOperation()
{
}

ULONG MSWinRTStreamSink::MSWinRTAsyncOperation::AddRef()
{
	return InterlockedIncrement(&_cRef);
}

ULONG MSWinRTStreamSink::MSWinRTAsyncOperation::Release()
{
	ULONG cRef = InterlockedDecrement(&_cRef);
	if (cRef == 0) {
		delete this;
	}
	return cRef;
}

HRESULT MSWinRTStreamSink::MSWinRTAsyncOperation::QueryInterface(REFIID iid, void **ppv)
{
	if (!ppv)
		return E_POINTER;
	if (iid == IID_IUnknown)
		*ppv = static_cast<IUnknown*>(this);
	else {
		*ppv = nullptr;
		return E_NOINTERFACE;
	}
	AddRef();
	return S_OK;
}



245 246 247 248
// IUnknown methods

IFACEMETHODIMP MSWinRTStreamSink::QueryInterface(REFIID riid, void **ppv)
{
249
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::QueryInterface");
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
	if (ppv == nullptr)
		RETURN_HR(E_POINTER)
	(*ppv) = nullptr;

	HRESULT hr = S_OK;
	if (riid == IID_IUnknown ||	riid == IID_IMFStreamSink || riid == IID_IMFMediaEventGenerator) {
		(*ppv) = static_cast<IMFStreamSink*>(this);
		AddRef();
	} else if (riid == IID_IMFMediaTypeHandler) {
		(*ppv) = static_cast<IMFMediaTypeHandler*>(this);
		AddRef();
	} else {
		hr = E_NOINTERFACE;
	}

	if (FAILED(hr) && riid == IID_IMarshal) {
		if (_spFTM == nullptr) {
267
			AutoLock lock(_critSec);
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
			if (_spFTM == nullptr)
				hr = CoCreateFreeThreadedMarshaler(static_cast<IMFStreamSink*>(this), &_spFTM);
		}
		if (SUCCEEDED(hr)) {
			if (_spFTM == nullptr)
				hr = E_UNEXPECTED;
			else
				hr = _spFTM.Get()->QueryInterface(riid, ppv);
		}
	}

	RETURN_HR(hr)
}

IFACEMETHODIMP_(ULONG) MSWinRTStreamSink::AddRef()
{
Ghislain MARY's avatar
Ghislain MARY committed
284
	long cRef = InterlockedIncrement(&_cRef);
285
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::AddRef -> %d", cRef);
Ghislain MARY's avatar
Ghislain MARY committed
286
	return cRef;
287 288 289 290 291
}

IFACEMETHODIMP_(ULONG) MSWinRTStreamSink::Release()
{
	long cRef = InterlockedDecrement(&_cRef);
292
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::Release -> %d", cRef);
293 294 295 296 297 298 299 300 301 302
	if (cRef == 0)
		delete this;
	return cRef;
}

// IMFMediaEventGenerator methods.
// Note: These methods call through to the event queue helper object.

IFACEMETHODIMP MSWinRTStreamSink::BeginGetEvent(IMFAsyncCallback *pCallback, IUnknown *punkState)
{
303
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::BeginGetEvent");
304
	HRESULT hr = S_OK;
305
	AutoLock lock(_critSec);
306 307 308 309 310 311 312 313
	hr = CheckShutdown();
	if (SUCCEEDED(hr))
		hr = _spEventQueue->BeginGetEvent(pCallback, punkState);
	RETURN_HR(hr)
}

IFACEMETHODIMP MSWinRTStreamSink::EndGetEvent(IMFAsyncResult *pResult, IMFMediaEvent **ppEvent)
{
314
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::EndGetEvent");
315
	HRESULT hr = S_OK;
316
	AutoLock lock(_critSec);
317 318 319 320 321 322 323 324 325 326 327 328
	hr = CheckShutdown();
	if (SUCCEEDED(hr))
		hr = _spEventQueue->EndGetEvent(pResult, ppEvent);
	RETURN_HR(hr)
}

IFACEMETHODIMP MSWinRTStreamSink::GetEvent(DWORD dwFlags, IMFMediaEvent **ppEvent)
{
	// NOTE:
	// GetEvent can block indefinitely, so we don't hold the lock.
	// This requires some juggling with the event queue pointer.

329
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::GetEvent");
330 331 332
	HRESULT hr = S_OK;
	ComPtr<IMFMediaEventQueue> spQueue;

333 334 335 336 337 338
	{
		AutoLock lock(_critSec);
		hr = CheckShutdown();
		if (SUCCEEDED(hr))
			spQueue = _spEventQueue;
	}
339 340 341 342 343 344 345 346

	if (SUCCEEDED(hr))
		hr = spQueue->GetEvent(dwFlags, ppEvent);
	RETURN_HR(hr)
}

IFACEMETHODIMP MSWinRTStreamSink::QueueEvent(MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, PROPVARIANT const *pvValue)
{
347
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::QueueEvent");
348
	HRESULT hr = S_OK;
349
	AutoLock lock(_critSec);
350 351 352 353 354 355 356 357 358 359
	hr = CheckShutdown();
	if (SUCCEEDED(hr))
		hr = _spEventQueue->QueueEventParamVar(met, guidExtendedType, hrStatus, pvValue);
	RETURN_HR(hr)
}

/// IMFStreamSink methods

IFACEMETHODIMP MSWinRTStreamSink::GetMediaSink(IMFMediaSink **ppMediaSink)
{
360
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::GetMediaSink");
361 362 363
	if (ppMediaSink == nullptr)
		RETURN_HR(E_INVALIDARG)

364
	AutoLock lock(_critSec);
365 366 367 368 369 370 371 372
	HRESULT hr = CheckShutdown();
	if (SUCCEEDED(hr))
		_spSink.Get()->QueryInterface(IID_IMFMediaSink, (void**)ppMediaSink);
	RETURN_HR(hr)
}

IFACEMETHODIMP MSWinRTStreamSink::GetIdentifier(DWORD *pdwIdentifier)
{
373
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::GetIdentifier");
374 375 376
	if (pdwIdentifier == nullptr)
		RETURN_HR(E_INVALIDARG)

377
	AutoLock lock(_critSec);
378 379
	HRESULT hr = CheckShutdown();
	if (SUCCEEDED(hr)) {
380
		MSWINRTMEDIASINK_DEBUG("\t-> %d", _dwIdentifier);
381 382 383 384 385 386 387
		*pdwIdentifier = _dwIdentifier;
	}
	RETURN_HR(hr)
}

IFACEMETHODIMP MSWinRTStreamSink::GetMediaTypeHandler(IMFMediaTypeHandler **ppHandler)
{
388
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::GetMediaTypeHandler");
389 390 391
	if (ppHandler == nullptr)
		RETURN_HR(E_INVALIDARG)

392
	AutoLock lock(_critSec);
393 394 395 396 397 398 399 400 401 402
	HRESULT hr = CheckShutdown();
	// This stream object acts as its own type handler, so we QI ourselves.
	if (SUCCEEDED(hr))
		hr = QueryInterface(IID_IMFMediaTypeHandler, (void**)ppHandler);
	RETURN_HR(hr)
}

// We received a sample from an upstream component
IFACEMETHODIMP MSWinRTStreamSink::ProcessSample(IMFSample *pSample)
{
403
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::ProcessSample");
404 405 406 407
	if (pSample == nullptr)
		RETURN_HR(E_INVALIDARG)

	HRESULT hr = S_OK;
408
	AutoLock lock(_critSec);
409 410 411 412 413
	hr = CheckShutdown();
	// Validate the operation.
	if (SUCCEEDED(hr))
		hr = ValidateOperation(OpProcessSample);

414
	if (SUCCEEDED(hr) && _fWaitingForFirstSample) {
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
		_spFirstVideoSample = pSample;
		_fWaitingForFirstSample = false;
		hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, hr, nullptr);
	} else if (SUCCEEDED(hr)) {
		// Add the sample to the sample queue.
		if (SUCCEEDED(hr))
			hr = _SampleQueue.InsertBack(pSample);

		// Unless we are paused, start an async operation to dispatch the next sample.
		if (SUCCEEDED(hr)) {
			if (_state != State_Paused) {
				// Queue the operation.
				hr = QueueAsyncOperation(OpProcessSample);
			}
		}
	}

	RETURN_HR(hr)
}

// The client can call PlaceMarker at any time. In response,
// we need to queue an MEStreamSinkMarker event, but not until
// *after *we have processed all samples that we have received
// up to this point.
//
// Also, in general you might need to handle specific marker
// types, although this sink does not.

IFACEMETHODIMP MSWinRTStreamSink::PlaceMarker(MFSTREAMSINK_MARKER_TYPE eMarkerType, const PROPVARIANT *pvarMarkerValue, const PROPVARIANT *pvarContextValue)
{
445
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::PlaceMarker");
446 447 448
	HRESULT hr = S_OK;
	ComPtr<IMarker> spMarker;

449
	AutoLock lock(_critSec);
450 451 452 453
	hr = CheckShutdown();
	if (SUCCEEDED(hr))
		hr = ValidateOperation(OpPlaceMarker);
	if (SUCCEEDED(hr))
454
		hr = MSWinRTMarker::Create(eMarkerType, pvarMarkerValue, pvarContextValue, &spMarker);
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
	if (SUCCEEDED(hr))
		hr = _SampleQueue.InsertBack(spMarker.Get());

	// Unless we are paused, start an async operation to dispatch the next sample/marker.
	if (SUCCEEDED(hr)) {
		if (_state != State_Paused) {
			// Queue the operation.
			hr = QueueAsyncOperation(OpPlaceMarker); // Increments ref count on pOp.
		}
	}
	RETURN_HR(hr)
}

// Discards all samples that were not processed yet.
IFACEMETHODIMP MSWinRTStreamSink::Flush()
{
471
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::Flush");
472
	HRESULT hr = S_OK;
473
	AutoLock lock(_critSec);
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
	try {
		hr = CheckShutdown();
		if (FAILED(hr)) {
			throw ref new Exception(hr);
		}

		// Note: Even though we are flushing data, we still need to send
		// any marker events that were queued.
		DropSamplesFromQueue();
	} catch (Exception ^exc) {
		hr = exc->HResult;
	}

	RETURN_HR(hr)
}


/// IMFMediaTypeHandler methods

// Check if a media type is supported.
IFACEMETHODIMP MSWinRTStreamSink::IsMediaTypeSupported(/* [in] */ IMFMediaType *pMediaType, /* [out] */ IMFMediaType **ppMediaType)
{
496
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::IsMediaTypeSupported");
497 498 499 500 501
	if (pMediaType == nullptr)
		RETURN_HR(E_INVALIDARG)

	GUID majorType = GUID_NULL;
	UINT cbSize = 0;
502
	AutoLock lock(_critSec);
503 504 505 506 507 508 509
	HRESULT hr = CheckShutdown();
	if (SUCCEEDED(hr))
		hr = pMediaType->GetGUID(MF_MT_MAJOR_TYPE, &majorType);

	// First make sure it's video type.
	if (SUCCEEDED(hr)) {
		if (majorType != MFMediaType_Video)
510
			hr = MF_E_INVALIDMEDIATYPE;
511 512 513 514 515
	}

	if (SUCCEEDED(hr) && _spCurrentType != nullptr) {
		GUID guiNewSubtype;
		if (FAILED(pMediaType->GetGUID(MF_MT_SUBTYPE, &guiNewSubtype)) || guiNewSubtype != _guiCurrentSubtype)
516
			hr = MF_E_INVALIDMEDIATYPE;
517
	}
Ghislain MARY's avatar
Ghislain MARY committed
518 519
	if (SUCCEEDED(hr)) {
		UINT64 frameSize = 0;
520 521 522
		if (FAILED(pMediaType->GetUINT64(MF_MT_FRAME_SIZE, &frameSize)) || frameSize != _guiCurrentFrameSize)
			hr = MF_E_INVALIDMEDIATYPE;
		else
523
			MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::IsMediaTypeSupported: %dx%d", (frameSize & 0xffffffff00000000) >> 32, frameSize & 0xffffffff);
Ghislain MARY's avatar
Ghislain MARY committed
524
	}
525 526 527 528 529 530 531 532 533 534 535 536

	// We don't return any "close match" types.
	if (ppMediaType)
		*ppMediaType = nullptr;

	RETURN_HR(hr)
}


// Return the number of preferred media types.
IFACEMETHODIMP MSWinRTStreamSink::GetMediaTypeCount(DWORD *pdwTypeCount)
{
537
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::GetMediaTypeCount");
538 539 540
	if (pdwTypeCount == nullptr)
		RETURN_HR(E_INVALIDARG)

541
	AutoLock lock(_critSec);
542 543 544 545 546 547 548 549 550 551 552 553 554
	HRESULT hr = CheckShutdown();
	if (SUCCEEDED(hr)) {
		// We've got only one media type
		*pdwTypeCount = 1;
	}

	RETURN_HR(hr)
}


// Return a preferred media type by index.
IFACEMETHODIMP MSWinRTStreamSink::GetMediaTypeByIndex(/* [in] */ DWORD dwIndex, /* [out] */ IMFMediaType **ppType)
{
555
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::GetMediaTypeByIndex");
556 557 558
	if (ppType == nullptr)
		RETURN_HR(E_INVALIDARG)

559
	AutoLock lock(_critSec);
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
	HRESULT hr = CheckShutdown();
	if (dwIndex > 0)
		hr = MF_E_NO_MORE_TYPES;
	else {
		*ppType = _spCurrentType.Get();
		if (*ppType != nullptr)
			(*ppType)->AddRef();
	}

	RETURN_HR(hr)
}


// Set the current media type.
IFACEMETHODIMP MSWinRTStreamSink::SetCurrentMediaType(IMFMediaType *pMediaType)
{
576
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::SetCurrentMediaType");
577 578 579 580 581
	HRESULT hr = S_OK;
	try {
		if (pMediaType == nullptr)
			throw ref new Exception(E_INVALIDARG);

582
		AutoLock lock(_critSec);
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
		hr = CheckShutdown();
		if (FAILED(hr)) {
			throw ref new Exception(hr);
		}

		// We don't allow format changes after streaming starts.
		hr = ValidateOperation(OpSetMediaType);
		if (FAILED(hr)) {
			throw ref new Exception(hr);
		}

		// We set media type already
		if (_state >= State_Ready) {
			hr = IsMediaTypeSupported(pMediaType, nullptr);
			if (FAILED(hr)) {
				throw ref new Exception(hr);
			}
		}

		hr = MFCreateMediaType(_spCurrentType.ReleaseAndGetAddressOf());
		if (FAILED(hr)) {
			throw ref new Exception(hr);
		}
		hr = pMediaType->CopyAllItems(_spCurrentType.Get());
		if (FAILED(hr)) {
			throw ref new Exception(hr);
		}
		hr = _spCurrentType->GetGUID(MF_MT_SUBTYPE, &_guiCurrentSubtype);
		if (FAILED(hr)) {
612 613 614 615
			throw ref new Exception(hr);
		}
		hr = _spCurrentType->GetUINT64(MF_MT_FRAME_SIZE, &_guiCurrentFrameSize);
		if (FAILED(hr)) {
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
			throw ref new Exception(hr);
		}
		if (_state < State_Ready)
			_state = State_Ready;
		else if (_state > State_Ready) {
			ComPtr<IMFMediaType> spType;
			hr = MFCreateMediaType(&spType);
			if (FAILED(hr)) {
				throw ref new Exception(hr);
			}
			hr = pMediaType->CopyAllItems(spType.Get());
			if (FAILED(hr)) {
				throw ref new Exception(hr);
			}
			ProcessFormatChange(spType.Get());
		}
	} catch (Exception ^exc) {
		hr = exc->HResult;
	}

	RETURN_HR(hr)
}

// Return the current media type, if any.
IFACEMETHODIMP MSWinRTStreamSink::GetCurrentMediaType(IMFMediaType **ppMediaType)
{
642
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::GetCurrentMediaType");
643 644 645
	if (ppMediaType == nullptr)
		RETURN_HR(E_INVALIDARG)

646
	AutoLock lock(_critSec);
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
	HRESULT hr = CheckShutdown();
	if (SUCCEEDED(hr)) {
		if (_spCurrentType == nullptr)
			hr = MF_E_NOT_INITIALIZED;
	}
	if (SUCCEEDED(hr)) {
		*ppMediaType = _spCurrentType.Get();
		(*ppMediaType)->AddRef();
	}

	RETURN_HR(hr)
}


// Return the major type GUID.
IFACEMETHODIMP MSWinRTStreamSink::GetMajorType(GUID *pguidMajorType)
{
664
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::GetMajorType");
665 666 667 668 669 670 671 672 673 674 675 676 677 678
	if (pguidMajorType == nullptr)
		RETURN_HR(E_INVALIDARG)

	if (!_spCurrentType)
		return MF_E_NOT_INITIALIZED;

	*pguidMajorType = MFMediaType_Video;
	return S_OK;
}


// private methods
HRESULT MSWinRTStreamSink::Initialize(MSWinRTMediaSink *pParent)
{
679
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::Initialize");
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
	// Create the event queue helper.
	HRESULT hr = MFCreateEventQueue(&_spEventQueue);

	// Allocate a new work queue for async operations.
	if (SUCCEEDED(hr))
		hr = MFAllocateSerialWorkQueue(MFASYNC_CALLBACK_QUEUE_STANDARD, &_WorkQueueId);

	if (SUCCEEDED(hr)) {
		_spSink = pParent;
		_pParent = pParent;
	}

	RETURN_HR(hr)
}


// Called when the presentation clock starts.
HRESULT MSWinRTStreamSink::Start(MFTIME start)
{
699
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::Start");
700
	AutoLock lock(_critSec);
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
	HRESULT hr = ValidateOperation(OpStart);
	if (SUCCEEDED(hr)) {
		if (start != PRESENTATION_CURRENT_POSITION) {
			_StartTime = start;        // Cache the start time.
			_fGetStartTimeFromSample = false;
		} else {
			_fGetStartTimeFromSample = true;
		}
		_state = State_Started;
		_fWaitingForFirstSample = true;
		hr = QueueAsyncOperation(OpStart);
	}
	RETURN_HR(hr)
}

// Called when the presentation clock stops.
HRESULT MSWinRTStreamSink::Stop()
{
719
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::Stop");
720
	AutoLock lock(_critSec);
721 722 723 724 725 726 727 728 729 730 731
	HRESULT hr = ValidateOperation(OpStop);
	if (SUCCEEDED(hr)) {
		_state = State_Stopped;
		hr = QueueAsyncOperation(OpStop);
	}
	RETURN_HR(hr)
}

// Called when the presentation clock restarts.
HRESULT MSWinRTStreamSink::Restart()
{
732
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::Restart");
733
	AutoLock lock(_critSec);
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
	HRESULT hr = ValidateOperation(OpRestart);
	if (SUCCEEDED(hr)) {
		_state = State_Started;
		hr = QueueAsyncOperation(OpRestart);
	}
	RETURN_HR(hr)
}

// Class-static matrix of operations vs states.
// If an entry is TRUE, the operation is valid from that state.
BOOL MSWinRTStreamSink::ValidStateMatrix[MSWinRTStreamSink::State_Count][MSWinRTStreamSink::Op_Count] =
{
	// States:    Operations:
	//            SetType   Start     Restart   Pause     Stop      Sample    Marker   
	/* NotSet */  TRUE,     FALSE,    FALSE,    FALSE,    FALSE,    FALSE,    FALSE,

	/* Ready */   TRUE,     TRUE,     FALSE,    TRUE,     TRUE,     FALSE,    TRUE,

	/* Start */   TRUE,     TRUE,     FALSE,    TRUE,     TRUE,     TRUE,     TRUE,

	/* Pause */   TRUE,     TRUE,     TRUE,     TRUE,     TRUE,     TRUE,     TRUE,

	/* Stop */    TRUE,     TRUE,     FALSE,    FALSE,    TRUE,     FALSE,    TRUE,

};

// Checks if an operation is valid in the current state.
HRESULT MSWinRTStreamSink::ValidateOperation(StreamOperation op)
{
763
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::ValidateOperation");
764 765 766 767 768 769 770 771 772 773 774
	if (ValidStateMatrix[_state][op])
		return S_OK;
	else if (_state == State_TypeNotSet)
		return MF_E_NOT_INITIALIZED;
	else
		return MF_E_INVALIDREQUEST;
}

// Shuts down the stream sink.
HRESULT MSWinRTStreamSink::Shutdown()
{
775
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::Shutdown");
776
	AutoLock lock(_critSec);
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
	if (!_IsShutdown) {
		if (_spEventQueue)
			_spEventQueue->Shutdown();

		MFUnlockWorkQueue(_WorkQueueId);
		_SampleQueue.Clear();
		_spSink.Reset();
		_spEventQueue.Reset();
		_spByteStream.Reset();
		_spCurrentType.Reset();
		_IsShutdown = true;
	}
	return S_OK;
}

// Puts an async operation on the work queue.
HRESULT MSWinRTStreamSink::QueueAsyncOperation(StreamOperation op)
{
795
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::QueueAsyncOperation");
796
	HRESULT hr = S_OK;
797 798
	ComPtr<MSWinRTAsyncOperation> spOp;
	spOp.Attach(new MSWinRTAsyncOperation(op)); // Created with ref count = 1
799 800 801 802 803 804 805 806 807
	if (!spOp)
		hr = E_OUTOFMEMORY;
	if (SUCCEEDED(hr))
		hr = MFPutWorkItem2(_WorkQueueId, 0, &_WorkQueueCB, spOp.Get());
	RETURN_HR(hr)
}

HRESULT MSWinRTStreamSink::OnDispatchWorkItem(IMFAsyncResult *pAsyncResult)
{
808
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::OnDispatchWorkItem");
809
	// Called by work queue thread. Need to hold the critical section.
810
	AutoLock lock(_critSec);
811 812 813 814 815 816 817 818 819

	try {
		ComPtr<IUnknown> spState;
		HRESULT hr = pAsyncResult->GetState(&spState);
		if (FAILED(hr)) {
			throw ref new Exception(hr);
		}

		// The state object is a CAsncOperation object.
820
		MSWinRTAsyncOperation *pOp = static_cast<MSWinRTAsyncOperation *>(spState.Get());
821
		StreamOperation op = pOp->m_op;
822
		bool fRequestMoreSamples = false;
823 824 825 826 827 828 829 830 831 832 833

		switch (op) {
		case OpStart:
		case OpRestart:
			// Send MEStreamSinkStarted.
			hr = QueueEvent(MEStreamSinkStarted, GUID_NULL, S_OK, nullptr);
			if (FAILED(hr)) {
				throw ref new Exception(hr);
			}

			// There might be samples queue from earlier (ie, while paused).
834
			fRequestMoreSamples = SendSampleFromQueue();
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
			if (fRequestMoreSamples) {
				// If false there is no samples in the queue now so request one
				hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, nullptr);
				if (FAILED(hr)) {
					throw ref new Exception(hr);
				}
			}
			break;

		case OpStop:
			// Drop samples from queue.
			DropSamplesFromQueue();

			// Send the event even if the previous call failed.
			hr = QueueEvent(MEStreamSinkStopped, GUID_NULL, S_OK, nullptr);
			if (FAILED(hr)) {
				throw ref new Exception(hr);
			}
			break;

		case OpPause:
			hr = QueueEvent(MEStreamSinkPaused, GUID_NULL, S_OK, nullptr);
			if (FAILED(hr)) {
				throw ref new Exception(hr);
			}
			break;

		case OpProcessSample:
		case OpPlaceMarker:
		case OpSetMediaType:
			DispatchProcessSample(pOp);
			break;
		}
	} catch (Exception ^exc) {
		HandleError(exc->HResult);
	}

	return S_OK;
}

// Complete a ProcessSample or PlaceMarker request.
876
void MSWinRTStreamSink::DispatchProcessSample(MSWinRTAsyncOperation *pOp)
877
{
878
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::DispatchProcessSample");
879
	bool fRequestMoreSamples = SendSampleFromQueue();
880 881 882 883 884 885 886 887 888 889 890 891 892 893

	// Ask for another sample
	if (fRequestMoreSamples) {
		if (pOp->m_op == OpProcessSample) {
			HRESULT hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, nullptr);
			if (FAILED(hr))
				throw ref new Exception(hr);
		}
	}
}

// Drop samples in the queue
bool MSWinRTStreamSink::DropSamplesFromQueue()
{
894
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::DropSamplesFromQueue");
895 896 897 898 899 900 901
	ProcessSamplesFromQueue(true);
	return true;
}

// Send sample from the queue
bool MSWinRTStreamSink::SendSampleFromQueue()
{
902
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::SendSampleFromQueue");
903 904 905 906 907
	return ProcessSamplesFromQueue(false);
}

bool MSWinRTStreamSink::ProcessSamplesFromQueue(bool fFlush)
{
908
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::ProcessSamplesFromQueue");
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
	bool fNeedMoreSamples = false;
	ComPtr<IUnknown> spunkSample;
	bool fSendSamples = true;
	bool fSendEOS = false;

	if (FAILED(_SampleQueue.RemoveFront(&spunkSample))) {
		fNeedMoreSamples = true;
		fSendSamples = false;
	}

	while (fSendSamples) {
		ComPtr<IMFSample> spSample;

		// Figure out if this is a marker or a sample.
		// If this is a sample, write it to the file.
		// Now handle the sample/marker appropriately.
		if (SUCCEEDED(spunkSample.As(&spSample))) {
			if (!fFlush) {
				// Prepare sample for sending
Ghislain MARY's avatar
Ghislain MARY committed
928 929
				if (FAILED(PrepareSample(spSample.Get()))) {
					fSendSamples = false;
930
				}
Ghislain MARY's avatar
Ghislain MARY committed
931
			}
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
		} else {
			ComPtr<IMarker> spMarker;
			// Check if it is a marker
			if (SUCCEEDED(spunkSample.As(&spMarker))) {
				MFSTREAMSINK_MARKER_TYPE markerType;
				PROPVARIANT var;
				HRESULT hr;
				PropVariantInit(&var);
				hr = spMarker->GetMarkerType(&markerType);
				if (FAILED(hr)) throw ref new Exception(hr);
				// Get the context data.
				hr = spMarker->GetContext(&var);
				if (FAILED(hr)) throw ref new Exception(hr);
				hr = QueueEvent(MEStreamSinkMarker, GUID_NULL, S_OK, &var);
				PropVariantClear(&var);
				if (FAILED(hr)) throw ref new Exception(hr);

				if (markerType == MFSTREAMSINK_MARKER_ENDOFSEGMENT) {
					fSendEOS = true;
				}
			}
#if 0 // TODO
			else {
				ComPtr<IMFMediaType> spType;
				HRESULT hr = spunkSample.As(&spType);
				if (FAILED(hr)) throw ref new Exception(hr);
				if (!fFlush) {
					spPacket = PrepareFormatChange(spType.Get());
				}
			}
#endif
963 964
		}

965 966
		if (fSendSamples) {
			if (FAILED(_SampleQueue.RemoveFront(spunkSample.ReleaseAndGetAddressOf()))) {
967 968 969 970 971 972 973 974
				fNeedMoreSamples = true;
				fSendSamples = false;
			}
		}
	}

	if (fSendEOS)
	{
975
		ComPtr<MSWinRTMediaSink> spParent = _pParent;
976 977 978 979 980 981 982 983 984 985
		concurrency::create_task([spParent]() {
			spParent->ReportEndOfStream();
		});
	}
	return fNeedMoreSamples;
}

// Processing format change
void MSWinRTStreamSink::ProcessFormatChange(IMFMediaType *pMediaType)
{
986
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::ProcessFormatChange");
987 988 989 990 991 992 993 994 995 996 997 998
	// Add the media type to the sample queue.
	HRESULT hr = _SampleQueue.InsertBack(pMediaType);
	if (FAILED(hr))
		throw ref new Exception(hr);

	// Unless we are paused, start an async operation to dispatch the next sample.
	// Queue the operation.
	hr = QueueAsyncOperation(OpSetMediaType);
	if (FAILED(hr))
		throw ref new Exception(hr);
}

999 1000
HRESULT MSWinRTStreamSink::PrepareSample(IMFSample *pSample)
{
1001
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::PrepareSample");
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
	LONGLONG llSampleTime;
	HRESULT hr = pSample->GetSampleTime(&llSampleTime);
	if (FAILED(hr))
		return hr;
	if (llSampleTime < 0)
		return hr;

	DWORD cBuffers = 0;
	hr = pSample->GetBufferCount(&cBuffers);
	if (SUCCEEDED(hr)) {
		for (DWORD nIndex = 0; nIndex < cBuffers; ++nIndex) {
			ComPtr<IMFMediaBuffer> spMediaBuffer;
			// Get buffer from the sample
			hr = pSample->GetBufferByIndex(nIndex, &spMediaBuffer);
			if (FAILED(hr)) break;
			BYTE *pBuffer = nullptr;
			DWORD currentLength = 0;
			hr = spMediaBuffer->Lock(&pBuffer, NULL, &currentLength);
			if (SUCCEEDED(hr)) {
1021
				static_cast<MSWinRTMediaSink *>(_spSink.Get())->OnSampleAvailable(pBuffer, currentLength, llSampleTime);
1022 1023 1024 1025 1026 1027 1028 1029 1030
				hr = spMediaBuffer->Unlock();
				if (FAILED(hr)) break;
			}
		}
	}

	RETURN_HR(hr);
}

1031 1032
void MSWinRTStreamSink::HandleError(HRESULT hr)
{
1033
	MSWINRTMEDIASINK_DEBUG("MSWinRTStreamSink::HandleError");
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
	if (!_IsShutdown)
		QueueEvent(MEError, GUID_NULL, hr, nullptr);
}






MSWinRTMediaSink::MSWinRTMediaSink()
	: _cRef(1)
	, _IsShutdown(false)
	, _IsConnected(false)
	, _llStartTime(0)
	, _cStreamsEnded(0)
	, _waitingConnectionId(0)
{
1051
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink constructor");
1052 1053 1054 1055
}

MSWinRTMediaSink::~MSWinRTMediaSink()
{
1056
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink destructor");
1057 1058
}

1059
HRESULT MSWinRTMediaSink::RuntimeClassInitialize(Windows::Media::MediaProperties::IMediaEncodingProperties ^videoEncodingProperties)
1060
{
1061
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::RuntimeClassInitialize");
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
	try
	{
		SetVideoStreamProperties(videoEncodingProperties);
	}
	catch (Exception ^exc)
	{
		return exc->HResult;
	}

	return S_OK;
}

void MSWinRTMediaSink::SetVideoStreamProperties(_In_opt_ Windows::Media::MediaProperties::IMediaEncodingProperties ^mediaEncodingProperties)
{
1076
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::SetVideoStreamProperties");
1077 1078 1079 1080
	if (mediaEncodingProperties != nullptr)
	{
		ComPtr<IMFMediaType> spMediaType;
		ConvertPropertiesToMediaType(mediaEncodingProperties, &spMediaType);
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094

		// Initialize the stream.
		HRESULT hr = S_OK;
		MSWinRTStreamSink *pStream = new MSWinRTStreamSink(0);
		if (pStream == nullptr)
			hr = E_OUTOFMEMORY;
		if (SUCCEEDED(hr)) {
			pStream->Initialize(this);
			hr = pStream->SetCurrentMediaType(spMediaType.Get());
		}
		if (SUCCEEDED(hr)) {
			_stream = pStream; // implicit AddRef
		}

1095 1096 1097 1098 1099 1100 1101 1102
		if (FAILED(hr))
			throw ref new Exception(hr);
	}
}

///  IMFMediaSink
IFACEMETHODIMP MSWinRTMediaSink::GetCharacteristics(DWORD *pdwCharacteristics)
{
1103
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::GetCharacteristics");
1104 1105 1106
	if (pdwCharacteristics == NULL)
		RETURN_HR(E_INVALIDARG)

1107
	AutoLock lock(_critSec);
1108 1109
	HRESULT hr = CheckShutdown();
	if (SUCCEEDED(hr)) {
1110 1111
		// Rateless sink with fixed number of streams (1).
		*pdwCharacteristics = MEDIASINK_RATELESS | MEDIASINK_FIXED_STREAMS;
1112 1113 1114 1115
	}
	RETURN_HR(hr)
}

1116
IFACEMETHODIMP MSWinRTMediaSink::AddStreamSink(/* [in] */ DWORD dwStreamSinkIdentifier, /* [in] */ IMFMediaType *pMediaType, /* [out] */ IMFStreamSink **ppStreamSink)
1117
{
1118
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::AddStreamSink");
1119
	RETURN_HR(E_NOTIMPL);
1120 1121 1122 1123
}

IFACEMETHODIMP MSWinRTMediaSink::RemoveStreamSink(DWORD dwStreamSinkIdentifier)
{
1124
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::RemoveStreamSink");
1125
	RETURN_HR(E_NOTIMPL);
1126 1127 1128 1129
}

IFACEMETHODIMP MSWinRTMediaSink::GetStreamSinkCount(_Out_ DWORD *pcStreamSinkCount)
{
1130
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::GetStreamSinkCount");
1131 1132 1133
	if (pcStreamSinkCount == NULL)
		RETURN_HR(E_INVALIDARG)

1134
	AutoLock lock(_critSec);
1135 1136 1137 1138 1139 1140 1141 1142 1143
	HRESULT hr = CheckShutdown();
	if (SUCCEEDED(hr))
		*pcStreamSinkCount = 1;

	RETURN_HR(hr)
}

IFACEMETHODIMP MSWinRTMediaSink::GetStreamSinkByIndex(DWORD dwIndex, _Outptr_ IMFStreamSink **ppStreamSink)
{
1144
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::GetStreamSinkByIndex(dwIndex=%d)", dwIndex);
1145 1146 1147 1148
	if (ppStreamSink == NULL)
		RETURN_HR(E_INVALIDARG)

	ComPtr<IMFStreamSink> spStream;
1149
	AutoLock lock(_critSec);
1150 1151 1152 1153
	if (dwIndex >= 1)
		return MF_E_INVALIDINDEX;

	HRESULT hr = CheckShutdown();
1154
	if (SUCCEEDED(hr)) {
1155 1156
		spStream = _stream;
		*ppStreamSink = spStream.Detach();
1157
	}
1158 1159 1160 1161 1162 1163

	RETURN_HR(hr)
}

IFACEMETHODIMP MSWinRTMediaSink::GetStreamSinkById(DWORD dwStreamSinkIdentifier, IMFStreamSink **ppStreamSink)
{
1164
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::GetStreamSinkById(dwStreamSinkIdentifier=%d)", dwStreamSinkIdentifier);
1165 1166 1167
	if (ppStreamSink == NULL)
		RETURN_HR(E_INVALIDARG)

1168
	AutoLock lock(_critSec);
1169 1170 1171 1172
	HRESULT hr = CheckShutdown();
	ComPtr<IMFStreamSink> spResult;
	if (SUCCEEDED(hr)) {
		DWORD dwId;
1173
		hr = _stream->GetIdentifier(&dwId);
1174
		if (SUCCEEDED(hr)) {
1175
			if (dwId == dwStreamSinkIdentifier)
Ghislain MARY's avatar
Ghislain MARY committed
1176
				spResult = _stream; // implicit AddRef
1177 1178
			else
				hr = MF_E_INVALIDSTREAMNUMBER;
1179 1180 1181
		} else {
			hr = MF_E_INVALIDSTREAMNUMBER;
		}
1182
		if (SUCCEEDED(hr)) {
1183
			*ppStreamSink = spResult.Detach();
1184
		}
1185 1186 1187 1188 1189 1190 1191
	}

	RETURN_HR(hr)
}

IFACEMETHODIMP MSWinRTMediaSink::SetPresentationClock(IMFPresentationClock *pPresentationClock)
{
1192
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::SetPresentationClock");
1193
	AutoLock lock(_critSec);
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
	HRESULT hr = CheckShutdown();

	// If we already have a clock, remove ourselves from that clock's
	// state notifications.
	if (SUCCEEDED(hr)) {
		if (_spClock)
			hr = _spClock->RemoveClockStateSink(this);
	}

	// Register ourselves to get state notifications from the new clock.
	if (SUCCEEDED(hr)) {
		if (pPresentationClock)
			hr = pPresentationClock->AddClockStateSink(this);
	}

	if (SUCCEEDED(hr)) {
		// Release the pointer to the old clock.
		// Store the pointer to the new clock.
		_spClock = pPresentationClock;
	}

	RETURN_HR(hr)
}

IFACEMETHODIMP MSWinRTMediaSink::GetPresentationClock(IMFPresentationClock **ppPresentationClock)
{
1220
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::GetPresentationClock");
1221 1222 1223
	if (ppPresentationClock == NULL)
		RETURN_HR(E_INVALIDARG)

1224
	AutoLock lock(_critSec);
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
	HRESULT hr = CheckShutdown();
	if (SUCCEEDED(hr)) {
		if (_spClock == NULL)
			hr = MF_E_NO_CLOCK; // There is no presentation clock.
		else {
			// Return the pointer to the caller.
			*ppPresentationClock = _spClock.Get();
			(*ppPresentationClock)->AddRef();
		}
	}

	RETURN_HR(hr)
}

IFACEMETHODIMP MSWinRTMediaSink::Shutdown()
{
1241
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::Shutdown");
1242
	AutoLock lock(_critSec);
1243 1244
	HRESULT hr = CheckShutdown();
	if (SUCCEEDED(hr)) {
1245 1246 1247
		ComPtr<IMFStreamSink> spStream = _stream;
		static_cast<MSWinRTStreamSink *>(spStream.Get())->Shutdown();
		_stream = nullptr;
1248 1249 1250 1251 1252 1253 1254 1255 1256
		_spClock.Reset();
		_IsShutdown = true;
	}
	return S_OK;
}

// IMFClockStateSink
IFACEMETHODIMP MSWinRTMediaSink::OnClockStart(MFTIME hnsSystemTime, LONGLONG llClockStartOffset)
{
1257
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::OnClockStart");
1258
	AutoLock lock(_critSec);
1259 1260
	HRESULT hr = CheckShutdown();
	if (SUCCEEDED(hr)) {
1261
		MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::OnClockStart ts=%I64d\n", llClockStartOffset);
1262
		_llStartTime = llClockStartOffset;
1263
		hr = static_cast<MSWinRTStreamSink *>(_stream.Get())->Start(llClockStartOffset);
1264 1265 1266 1267 1268 1269 1270
	}

	RETURN_HR(hr)
}

IFACEMETHODIMP MSWinRTMediaSink::OnClockStop(MFTIME hnsSystemTime)
{
1271
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::OnClockStop");
1272
	AutoLock lock(_critSec);
1273 1274
	HRESULT hr = CheckShutdown();
	if (SUCCEEDED(hr)) {
1275
		hr = static_cast<MSWinRTStreamSink *>(_stream.Get())->Stop();
1276 1277 1278 1279 1280 1281 1282 1283
	}

	RETURN_HR(hr)
}


IFACEMETHODIMP MSWinRTMediaSink::OnClockPause(MFTIME hnsSystemTime)
{
1284
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::OnClockPause");
1285 1286 1287 1288 1289
	return MF_E_INVALID_STATE_TRANSITION;
}

IFACEMETHODIMP MSWinRTMediaSink::OnClockRestart(MFTIME hnsSystemTime)
{
1290
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::OnClockRestart");
1291 1292 1293 1294 1295
	return MF_E_INVALID_STATE_TRANSITION;
}

IFACEMETHODIMP MSWinRTMediaSink::OnClockSetRate(/* [in] */ MFTIME hnsSystemTime, /* [in] */ float flRate)
{
1296
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::OnClockSetRate");
1297 1298 1299 1300 1301
	return S_OK;
}

void MSWinRTMediaSink::ReportEndOfStream()
{
1302
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::ReportEndOfStream");
1303
	AutoLock lock(_critSec);
1304 1305 1306
	++_cStreamsEnded;
}

1307
void MSWinRTMediaSink::OnSampleAvailable(BYTE *buf, DWORD bufLen, LONGLONG presentationTime)
1308
{
1309
	MSWINRTMEDIASINK_DEBUG("MSWinRTMediaSink::OnSampleAvailable");
1310
	if (_capture != nullptr) {
1311
		_capture->OnSampleAvailable(buf, bufLen, presentationTime);
1312 1313
	}
}