summaryrefslogtreecommitdiffstats
path: root/tinyDAV/src/video/mf/tdav_producer_video_mf.cxx
blob: be899a0105f133e8b37adf812a05930d022c61df (plain)
1
2
3
4
5
6
7
8
9
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
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
612
613
614
615
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
/*Copyright (C) 2013 Doubango Telecom <http://www.doubango.org>
* Copyright (C) Microsoft Corporation. All rights reserved.
*	
* This file is part of Open Source Doubango Framework.
*
* DOUBANGO 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 3 of the License, or
* (at your option) any later version.
*	
* DOUBANGO 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 DOUBANGO.
*/
/**@file tdav_producer_video_mf.cxx
 * @brief Microsoft Media Foundation video producer (source).
 *	http://msdn.microsoft.com/en-us/library/windows/desktop/ms694197(v=vs.85).aspx
 */
#include "tinydav/video/mf/tdav_producer_video_mf.h"

#if HAVE_MF

#include "tsk_semaphore.h"
#include "tsk_thread.h"
#include "tsk_string.h"
#include "tsk_debug.h"

#undef _WIN32_WINNT /* project-level value is 0x0501 (XP) */
#define _WIN32_WINNT _WIN32_WINNT_WIN7 /* must be re-defined before include Media Doundation headers */

#if defined(_MSC_VER)
#	pragma comment(lib, "mfplat.lib")
#	pragma comment(lib, "mf.lib")
#	pragma comment(lib, "mfuuid.lib")
#	pragma comment(lib, "shlwapi.lib")
#endif

#include <new>
#include <mfapi.h>
#include <mfidl.h>
#include <Mferror.h>
#include <shlwapi.h>

#undef SafeRelease
#define SafeRelease(ppT) \
{ \
    if (*ppT) \
    { \
        (*ppT)->Release(); \
        *ppT = NULL; \
    } \
} 

#undef CHECK_HR
#define CHECK_HR(x) if (FAILED(x)) { TSK_DEBUG_ERROR("Operation Failed"); goto bail; }


typedef struct VideoSubTypeGuidPair
{
	tmedia_chroma_t chroma;
	const GUID fourcc;
}
VideoSubTypeGuidPair;
static const VideoSubTypeGuidPair g_VideoSubTypeGuidPairs[] =
{
	
	{ tmedia_chroma_nv12, MFVideoFormat_NV12 }, // 0
	{ tmedia_chroma_rgb24, MFVideoFormat_RGB24 },
	{ tmedia_chroma_rgb32, MFVideoFormat_RGB32 },
	// to be continued
};

// MFVideoFormat_NV12, MFVideoFormat_YUY2, MFVideoFormat_UYVY,
// MFVideoFormat_RGB32, MFVideoFormat_RGB24, MFVideoFormat_IYUV
#undef DEFAULT_SUBTYPE_INDEX
#define DEFAULT_SUBTYPE_INDEX 0

//
//	DeviceList [Declaration]
//
class DeviceList
{
    UINT32      m_cDevices;
    IMFActivate **m_ppDevices;

public:
    DeviceList() : m_ppDevices(NULL), m_cDevices(0)
    {

    }
    ~DeviceList()
    {
        Clear();
    }

    UINT32  Count() const { return m_cDevices; }

    void    Clear();
    HRESULT EnumerateDevices();
    HRESULT GetDeviceAtIndex(UINT32 index, IMFActivate **ppActivate);
	HRESULT GetDeviceBest(IMFActivate **ppActivate);
    HRESULT GetDeviceName(UINT32 index, WCHAR **ppszName);
};


//
//	SampleGrabberCB [Declaration]
//	http://msdn.microsoft.com/en-us/library/windows/desktop/hh184779(v=vs.85).aspx
//
class SampleGrabberCB : public IMFSampleGrabberSinkCallback 
{
    long m_cRef;
	const struct tdav_producer_video_mf_s* m_pWrappedProducer;

    SampleGrabberCB(const struct tdav_producer_video_mf_s* pcWrappedProducer) : m_cRef(1), m_pWrappedProducer(pcWrappedProducer) {}

public:
    static HRESULT CreateInstance(const struct tdav_producer_video_mf_s* pcWrappedProducer, SampleGrabberCB **ppCB);

    // IUnknown methods
    STDMETHODIMP QueryInterface(REFIID iid, void** ppv);
    STDMETHODIMP_(ULONG) AddRef();
    STDMETHODIMP_(ULONG) Release();

    // IMFClockStateSink methods
    STDMETHODIMP OnClockStart(MFTIME hnsSystemTime, LONGLONG llClockStartOffset);
    STDMETHODIMP OnClockStop(MFTIME hnsSystemTime);
    STDMETHODIMP OnClockPause(MFTIME hnsSystemTime);
    STDMETHODIMP OnClockRestart(MFTIME hnsSystemTime);
    STDMETHODIMP OnClockSetRate(MFTIME hnsSystemTime, float flRate);

    // IMFSampleGrabberSinkCallback methods
    STDMETHODIMP OnSetPresentationClock(IMFPresentationClock* pClock);
    STDMETHODIMP OnProcessSample(REFGUID guidMajorMediaType, DWORD dwSampleFlags,
        LONGLONG llSampleTime, LONGLONG llSampleDuration, const BYTE * pSampleBuffer,
        DWORD dwSampleSize);
    STDMETHODIMP OnShutdown();
};


//
//	tdav_producer_video_mf_t
//
typedef struct tdav_producer_video_mf_s
{
	TMEDIA_DECLARE_PRODUCER;

	bool bStarted;	
	tsk_thread_handle_t* ppTread[1];

	DeviceList* pDeviceList;

	IMFMediaSession *pSession;
    IMFMediaSource *pSource;
    SampleGrabberCB *pCallback;
    IMFActivate *pSinkActivate;
    IMFTopology *pTopology;
    IMFMediaType *pType;
}
tdav_producer_video_mf_t;

//
// Forward declarations for glovbal functions
//
static HRESULT CreateTopology(
	IMFMediaSource *pSource, 
	IMFActivate *pSinkActivate, 
	IMFTopology **ppTopo);
static HRESULT AddSourceNode(
    IMFTopology *pTopology,
    IMFMediaSource *pSource,
    IMFPresentationDescriptor *pPD,
    IMFStreamDescriptor *pSD,
    IMFTopologyNode **ppNode);
static HRESULT AddOutputNode(
    IMFTopology *pTopology,
    IMFActivate *pActivate,
    DWORD dwId,
    IMFTopologyNode **ppNode);
static HRESULT RunSession(
	IMFMediaSession *pSession, 
	IMFTopology *pTopology);
static HRESULT StopSession(
	IMFMediaSession *pSession,
	IMFMediaSource *pSource);
static HRESULT PauseSession(
	IMFMediaSession *pSession);
static void* TSK_STDCALL RunSessionThread(void *pArg);


/* ============ Media Producer Interface ================= */
static int tdav_producer_video_mf_set(tmedia_producer_t *self, const tmedia_param_t* param)
{
	int ret = 0;
	tdav_producer_video_mf_t* pSelf = (tdav_producer_video_mf_t*)self;

	if(!pSelf || !param){
		TSK_DEBUG_ERROR("Invalid parameter");
		return -1;
	}

	return ret;
}

static int tdav_producer_video_mf_prepare(tmedia_producer_t* self, const tmedia_codec_t* codec)
{
	tdav_producer_video_mf_t* pSelf = (tdav_producer_video_mf_t*)self;

	if(!pSelf || !codec || !codec->plugin){
		TSK_DEBUG_ERROR("Invalid parameter");
		return -1;
	}
	
#if 0
	TMEDIA_PRODUCER(producer)->encoder.codec_id = (tmedia_codec_id_t)(tmedia_codec_id_h264_bp | tmedia_codec_id_h264_mp);
#else
	TMEDIA_PRODUCER(pSelf)->video.chroma = g_VideoSubTypeGuidPairs[DEFAULT_SUBTYPE_INDEX].chroma;
#endif

	TMEDIA_PRODUCER(pSelf)->video.fps = TMEDIA_CODEC_VIDEO(codec)->out.fps;
	TMEDIA_PRODUCER(pSelf)->video.width = TMEDIA_CODEC_VIDEO(codec)->out.width;
	TMEDIA_PRODUCER(pSelf)->video.height = TMEDIA_CODEC_VIDEO(codec)->out.height;

	// MFVideoFormat_NV12, MFVideoFormat_YUY2, MFVideoFormat_UYVY,
// MFVideoFormat_RGB32, MFVideoFormat_RGB24, MFVideoFormat_IYUV
#undef DEFAULT_SUBTYPE

	HRESULT hr = S_OK;

	// create device list object
	if(!pSelf->pDeviceList && !(pSelf->pDeviceList = new DeviceList())){
		TSK_DEBUG_ERROR("Failed to create device list");
		hr = E_OUTOFMEMORY;
		goto  bail;
	}
	// enumerate devices
	hr = pSelf->pDeviceList->EnumerateDevices();
	if(!SUCCEEDED(hr)){
		goto bail;
	}

	// check if we have at least one MF video source connected to the PC
	if(pSelf->pDeviceList->Count() == 0){
		TSK_DEBUG_WARN("No MF video source could be found...no video will be sent");
		// do not break the negotiation as one-way video connection is a valid use-case
	}
	else{
		IMFActivate* pActivate = NULL;
		// Get best MF video source
		hr = pSelf->pDeviceList->GetDeviceBest(&pActivate);
		if(!SUCCEEDED(hr) || !pActivate){
			TSK_DEBUG_ERROR("Failed to get best MF video source");
			if(!pActivate){
				hr = E_OUTOFMEMORY;
			}
			goto bail;
		}
		
		// Create the media source for the device.
		hr = pActivate->ActivateObject(
			__uuidof(IMFMediaSource),
			(void**)&pSelf->pSource
			);
		SafeRelease(&pActivate);
		if(!SUCCEEDED(hr)){
			TSK_DEBUG_ERROR("ActivateObject(MF video source) failed");
			goto bail;
		}

		// Configure the media type that the Sample Grabber will receive.
		// Setting the major and subtype is usually enough for the topology loader
		// to resolve the topology.

		CHECK_HR(hr = MFCreateMediaType(&pSelf->pType));
		CHECK_HR(hr = pSelf->pType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video));
#if 0
		CHECK_HR(hr = pSelf->pType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_H264);
#else
		CHECK_HR(hr = pSelf->pType->SetGUID(MF_MT_SUBTYPE, g_VideoSubTypeGuidPairs[DEFAULT_SUBTYPE_INDEX].fourcc));
#endif
		CHECK_HR(hr = MFSetAttributeSize(pSelf->pType, MF_MT_FRAME_SIZE, TMEDIA_PRODUCER(pSelf)->video.width, TMEDIA_PRODUCER(pSelf)->video.height));
		// CHECK_HR(hr = pSelf->pType->SetUINT32(MF_MT_DEFAULT_STRIDE, 1280));
		CHECK_HR(hr = pSelf->pType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, 1));
		CHECK_HR(hr = pSelf->pType->SetUINT32(MF_MT_FIXED_SIZE_SAMPLES, 1));
		// CHECK_HR(hr = pSelf->pType->SetUINT32(MF_MT_AVG_BITRATE,    147456000));
		//CHECK_HR(hr = MFSetAttributeRatio(pSelf->pType, MF_MT_FRAME_RATE, (UINT32)30000, 1001));    
		CHECK_HR(hr = MFSetAttributeRatio(pSelf->pType, MF_MT_PIXEL_ASPECT_RATIO, 1, 1)); 
		CHECK_HR(hr = pSelf->pType->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive)); 

		// Create the sample grabber sink.
		CHECK_HR(hr = SampleGrabberCB::CreateInstance(pSelf, &pSelf->pCallback));
		CHECK_HR(hr = MFCreateSampleGrabberSinkActivate(pSelf->pType, pSelf->pCallback, &pSelf->pSinkActivate));

		// To run as fast as possible, set this attribute (requires Windows 7):
		CHECK_HR(hr = pSelf->pSinkActivate->SetUINT32(MF_SAMPLEGRABBERSINK_IGNORE_CLOCK, TRUE));

		// Create the Media Session.
		CHECK_HR(hr = MFCreateMediaSession(NULL, &pSelf->pSession));

		// Create the topology.
		CHECK_HR(hr = CreateTopology(pSelf->pSource, pSelf->pSinkActivate, &pSelf->pTopology));
	}

bail:
	return SUCCEEDED(hr) ? 0 : -1;
}

static int tdav_producer_video_mf_start(tmedia_producer_t* self)
{
	tdav_producer_video_mf_t* pSelf = (tdav_producer_video_mf_t*)self;

	if(!pSelf){
		TSK_DEBUG_ERROR("Invalid parameter");
		return -1;
	}
	if(pSelf->bStarted){
		return 0;
	}

	HRESULT hr = S_OK;

	// Run the media session.
	CHECK_HR(hr = RunSession(pSelf->pSession, pSelf->pTopology));

	// Start asynchronous watcher thread
	pSelf->bStarted = true;
	int ret = tsk_thread_create(&pSelf->ppTread[0], RunSessionThread, pSelf);
	if(ret != 0){
		TSK_DEBUG_ERROR("Failed to create thread");
		hr = E_FAIL;
		pSelf->bStarted = false;
		StopSession(pSelf->pSession, pSelf->pSource);
		goto bail;
	}

bail:
	return SUCCEEDED(hr) ? 0 : -1;
}

static int tdav_producer_video_mf_pause(tmedia_producer_t* self)
{
	tdav_producer_video_mf_t* pSelf = (tdav_producer_video_mf_t*)self;

	if(!pSelf){
		TSK_DEBUG_ERROR("Invalid parameter");
		return -1;
	}

	HRESULT hr = PauseSession(pSelf->pSession);
	
	return 0;
}

static int tdav_producer_video_mf_stop(tmedia_producer_t* self)
{
	tdav_producer_video_mf_t* pSelf = (tdav_producer_video_mf_t*)self;

	if(!pSelf){
		TSK_DEBUG_ERROR("Invalid parameter");
		return -1;
	}

	HRESULT hr = S_OK;

	// for the thread
	pSelf->bStarted = false;
	hr = StopSession(pSelf->pSession, NULL); // stop session to wakeup the asynchronous thread
	if(pSelf->ppTread[0]){
		tsk_thread_join(&pSelf->ppTread[0]);
	}
	hr = StopSession(NULL, pSelf->pSource); // stop source to release the camera

	return 0;
}

//
//	Windows Media Foundation video producer object definition
//
/* constructor */
static tsk_object_t* tdav_producer_video_mf_ctor(tsk_object_t * self, va_list * app)
{
	tdav_producer_video_mf_t *pSelf = (tdav_producer_video_mf_t *)self;
	if(pSelf){
		/* init base */
		tmedia_producer_init(TMEDIA_PRODUCER(pSelf));
#if 0 // H.264
		TMEDIA_PRODUCER(pSelf)->video.chroma = tmedia_chroma_yuv420p; // To avoid chroma conversion
#endif
		/* init self with default values*/

		TMEDIA_PRODUCER(pSelf)->video.fps = 15;
		TMEDIA_PRODUCER(pSelf)->video.width = 352;
		TMEDIA_PRODUCER(pSelf)->video.height = 288;

#if TDAV_UNDER_WINDOWS_PHONE
		pSelf->videoCapturePhone = ref new VideoCapturePhone();
#endif
	}
	return self;
}
/* destructor */
static tsk_object_t* tdav_producer_video_mf_dtor(tsk_object_t * self)
{ 
	tdav_producer_video_mf_t *pSelf = (tdav_producer_video_mf_t *)self;
	if(pSelf){
		/* stop */
		//if(pSelf->started){
			tdav_producer_video_mf_stop((tmedia_producer_t*)self);
		//}

		/* deinit base */
		tmedia_producer_deinit(TMEDIA_PRODUCER(pSelf));
		/* deinit self */
		if(pSelf->pDeviceList){
			delete pSelf->pDeviceList, pSelf->pDeviceList = NULL;
		}
		if(pSelf->pSource){
			pSelf->pSource->Shutdown();
		}
		if(pSelf->pSession){
			pSelf->pSession->Shutdown();
		}

		SafeRelease(&pSelf->pSession);
		SafeRelease(&pSelf->pSource);
		SafeRelease(&pSelf->pCallback);
		SafeRelease(&pSelf->pSinkActivate);
		SafeRelease(&pSelf->pTopology);
		SafeRelease(&pSelf->pType);
	}

	return self;
}
/* object definition */
static const tsk_object_def_t tdav_producer_video_mf_def_s = 
{
	sizeof(tdav_producer_video_mf_t),
	tdav_producer_video_mf_ctor, 
	tdav_producer_video_mf_dtor,
	tsk_null, 
};
/* plugin definition*/
static const tmedia_producer_plugin_def_t tdav_producer_video_mf_plugin_def_s = 
{
	&tdav_producer_video_mf_def_s,

	tmedia_video,
	"Microsoft Windows Media Foundation producer (Video)",

	tdav_producer_video_mf_set,
	tdav_producer_video_mf_prepare,
	tdav_producer_video_mf_start,
	tdav_producer_video_mf_pause,
	tdav_producer_video_mf_stop
};
const tmedia_producer_plugin_def_t *tdav_producer_video_mf_plugin_def_t = &tdav_producer_video_mf_plugin_def_s;




//
//	DeviceList [Implementation]
//
void DeviceList::Clear()
{
    for (UINT32 i = 0; i < m_cDevices; i++)
    {
        SafeRelease(&m_ppDevices[i]);
    }
    CoTaskMemFree(m_ppDevices);
    m_ppDevices = NULL;

    m_cDevices = 0;
}

HRESULT DeviceList::EnumerateDevices()
{
    HRESULT hr = S_OK;
    IMFAttributes *pAttributes = NULL;

    Clear();

    // Initialize an attribute store. We will use this to
    // specify the enumeration parameters.

    hr = MFCreateAttributes(&pAttributes, 1);

    // Ask for source type = video capture devices
    if (SUCCEEDED(hr))
    {
        hr = pAttributes->SetGUID(
            MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
            MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
            );
    }

    // Enumerate devices.
    if (SUCCEEDED(hr))
    {
        hr = MFEnumDeviceSources(pAttributes, &m_ppDevices, &m_cDevices);
    }

    SafeRelease(&pAttributes);

    return hr;
}


HRESULT DeviceList::GetDeviceAtIndex(UINT32 index, IMFActivate **ppActivate)
{
    if (index >= Count())
    {
        return E_INVALIDARG;
    }

    *ppActivate = m_ppDevices[index];
    (*ppActivate)->AddRef();

    return S_OK;
}

HRESULT DeviceList::GetDeviceBest(IMFActivate **ppActivate)
{
	// for now we just get the default video source device (index = 0)
	return GetDeviceAtIndex(0, ppActivate);
}

HRESULT DeviceList::GetDeviceName(UINT32 index, WCHAR **ppszName)
{
    if (index >= Count())
    {
        return E_INVALIDARG;
    }

    HRESULT hr = S_OK;

    hr = m_ppDevices[index]->GetAllocatedString(
        MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME,
        ppszName,
        NULL
        );

    return hr;
}


//
// SampleGrabberCB [implementation]
// http://msdn.microsoft.com/en-us/library/windows/desktop/hh184779(v=vs.85).aspx
//

// Create a new instance of the object.
HRESULT SampleGrabberCB::CreateInstance(const struct tdav_producer_video_mf_s* pcWrappedProducer, SampleGrabberCB **ppCB)
{
    *ppCB = new (std::nothrow) SampleGrabberCB(pcWrappedProducer);

    if (ppCB == NULL)
    {
        return E_OUTOFMEMORY;
    }
    return S_OK;
}

STDMETHODIMP SampleGrabberCB::QueryInterface(REFIID riid, void** ppv)
{
    static const QITAB qit[] = 
    {
        QITABENT(SampleGrabberCB, IMFSampleGrabberSinkCallback),
        QITABENT(SampleGrabberCB, IMFClockStateSink),
        { 0 }
    };
    return QISearch(this, qit, riid, ppv);
}

STDMETHODIMP_(ULONG) SampleGrabberCB::AddRef()
{
    return InterlockedIncrement(&m_cRef);
}

STDMETHODIMP_(ULONG) SampleGrabberCB::Release()
{
    ULONG cRef = InterlockedDecrement(&m_cRef);
    if (cRef == 0)
    {
        delete this;
    }
    return cRef;

}

// IMFClockStateSink methods.

// In these example, the IMFClockStateSink methods do not perform any actions. 
// You can use these methods to track the state of the sample grabber sink.

STDMETHODIMP SampleGrabberCB::OnClockStart(MFTIME hnsSystemTime, LONGLONG llClockStartOffset)
{
    return S_OK;
}

STDMETHODIMP SampleGrabberCB::OnClockStop(MFTIME hnsSystemTime)
{
    return S_OK;
}

STDMETHODIMP SampleGrabberCB::OnClockPause(MFTIME hnsSystemTime)
{
    return S_OK;
}

STDMETHODIMP SampleGrabberCB::OnClockRestart(MFTIME hnsSystemTime)
{
    return S_OK;
}

STDMETHODIMP SampleGrabberCB::OnClockSetRate(MFTIME hnsSystemTime, float flRate)
{
    return S_OK;
}

// IMFSampleGrabberSink methods.

STDMETHODIMP SampleGrabberCB::OnSetPresentationClock(IMFPresentationClock* pClock)
{
    return S_OK;
}

STDMETHODIMP SampleGrabberCB::OnProcessSample(REFGUID guidMajorMediaType, DWORD dwSampleFlags,
    LONGLONG llSampleTime, LONGLONG llSampleDuration, const BYTE * pSampleBuffer,
    DWORD dwSampleSize)
{
	if(m_pWrappedProducer && TMEDIA_PRODUCER(m_pWrappedProducer)->enc_cb.callback)
	{
		TMEDIA_PRODUCER(m_pWrappedProducer)->enc_cb.callback(TMEDIA_PRODUCER(m_pWrappedProducer)->enc_cb.callback_data, pSampleBuffer, dwSampleSize);
	}

    return S_OK;
}

STDMETHODIMP SampleGrabberCB::OnShutdown()
{
    return S_OK;
}


//
//	Global functions
//

// Create the topology.
static HRESULT CreateTopology(IMFMediaSource *pSource, IMFActivate *pSinkActivate, IMFTopology **ppTopo)
{
    IMFTopology *pTopology = NULL;
    IMFPresentationDescriptor *pPD = NULL;
    IMFStreamDescriptor *pSD = NULL;
    IMFMediaTypeHandler *pHandler = NULL;
    IMFTopologyNode *pNode1 = NULL;
    IMFTopologyNode *pNode2 = NULL;

    HRESULT hr = S_OK;
    DWORD cStreams = 0;

    CHECK_HR(hr = MFCreateTopology(&pTopology));
    CHECK_HR(hr = pSource->CreatePresentationDescriptor(&pPD));
    CHECK_HR(hr = pPD->GetStreamDescriptorCount(&cStreams));
    
    for (DWORD i = 0; i < cStreams; i++)
    {
        // In this example, we look for audio streams and connect them to the sink.

        BOOL fSelected = FALSE;
        GUID majorType;

        CHECK_HR(hr = pPD->GetStreamDescriptorByIndex(i, &fSelected, &pSD));
        CHECK_HR(hr = pSD->GetMediaTypeHandler(&pHandler));
        CHECK_HR(hr = pHandler->GetMajorType(&majorType));

        if (majorType == MFMediaType_Video && fSelected)
        {
            CHECK_HR(hr = AddSourceNode(pTopology, pSource, pPD, pSD, &pNode1));
            CHECK_HR(hr = AddOutputNode(pTopology, pSinkActivate, 0, &pNode2));
            CHECK_HR(hr = pNode1->ConnectOutput(0, pNode2, 0));
            break;
        }
        else
        {
            CHECK_HR(hr = pPD->DeselectStream(i));
        }
        SafeRelease(&pSD);
        SafeRelease(&pHandler);
    }

    *ppTopo = pTopology;
    (*ppTopo)->AddRef();

bail:
    SafeRelease(&pTopology);
    SafeRelease(&pNode1);
    SafeRelease(&pNode2);
    SafeRelease(&pPD);
    SafeRelease(&pSD);
    SafeRelease(&pHandler);
    return hr;
}

// Add a source node to a topology.
static HRESULT AddSourceNode(
    IMFTopology *pTopology,           // Topology.
    IMFMediaSource *pSource,          // Media source.
    IMFPresentationDescriptor *pPD,   // Presentation descriptor.
    IMFStreamDescriptor *pSD,         // Stream descriptor.
    IMFTopologyNode **ppNode)         // Receives the node pointer.
{
    IMFTopologyNode *pNode = NULL;

    HRESULT hr = S_OK;
    CHECK_HR(hr = MFCreateTopologyNode(MF_TOPOLOGY_SOURCESTREAM_NODE, &pNode));
    CHECK_HR(hr = pNode->SetUnknown(MF_TOPONODE_SOURCE, pSource));
    CHECK_HR(hr = pNode->SetUnknown(MF_TOPONODE_PRESENTATION_DESCRIPTOR, pPD));
    CHECK_HR(hr = pNode->SetUnknown(MF_TOPONODE_STREAM_DESCRIPTOR, pSD));
    CHECK_HR(hr = pTopology->AddNode(pNode));

    // Return the pointer to the caller.
    *ppNode = pNode;
    (*ppNode)->AddRef();

bail:
    SafeRelease(&pNode);
    return hr;
}

// Add an output node to a topology.
static HRESULT AddOutputNode(
    IMFTopology *pTopology,     // Topology.
    IMFActivate *pActivate,     // Media sink activation object.
    DWORD dwId,                 // Identifier of the stream sink.
    IMFTopologyNode **ppNode)   // Receives the node pointer.
{
    IMFTopologyNode *pNode = NULL;

    HRESULT hr = S_OK;
    CHECK_HR(hr = MFCreateTopologyNode(MF_TOPOLOGY_OUTPUT_NODE, &pNode));
    CHECK_HR(hr = pNode->SetObject(pActivate));
    CHECK_HR(hr = pNode->SetUINT32(MF_TOPONODE_STREAMID, dwId));
    CHECK_HR(hr = pNode->SetUINT32(MF_TOPONODE_NOSHUTDOWN_ON_REMOVE, FALSE));
    CHECK_HR(hr = pTopology->AddNode(pNode));

    // Return the pointer to the caller.
    *ppNode = pNode;
    (*ppNode)->AddRef();

bail:
    SafeRelease(&pNode);
    return hr;
}

// Run session
static HRESULT RunSession(IMFMediaSession *pSession, IMFTopology *pTopology)
{
    IMFMediaEvent *pEvent = NULL;

    PROPVARIANT var;
    PropVariantInit(&var);

	MediaEventType met;
	HRESULT hrStatus = S_OK;
    HRESULT hr = S_OK;
    CHECK_HR(hr = pSession->SetTopology(0, pTopology));
    CHECK_HR(hr = pSession->Start(&GUID_NULL, &var));

	// Check first event
	hr = pSession->GetEvent(MF_EVENT_FLAG_NO_WAIT, &pEvent);
	if(hr == MF_E_NO_EVENTS_AVAILABLE){
		hr = S_OK;
		goto bail;
	}
    CHECK_HR(hr = pEvent->GetStatus(&hrStatus));
	if (FAILED(hrStatus))
    {
		CHECK_HR(hr = pEvent->GetType(&met));
		TSK_DEBUG_ERROR("Session error: 0x%x (event id: %d)\n", hrStatus, met);
        hr = hrStatus;
        goto bail;
    }

bail:
    SafeRelease(&pEvent);
    return hr;
}

// Stop session
static HRESULT StopSession(
	IMFMediaSession *pSession,
	IMFMediaSource *pSource)
{
	// MUST be source then session
	if(pSource){
		pSource->Shutdown();
	}
	if(pSession){
		pSession->Shutdown();
	}
	return S_OK;
}

// Pause session
static HRESULT PauseSession(
	IMFMediaSession *pSession)
{
	if(!pSession){
		return E_INVALIDARG;
	}
	return pSession->Pause();
}

// Run session async thread
static void* TSK_STDCALL RunSessionThread(void *pArg)
{
	tdav_producer_video_mf_t *pSelf = (tdav_producer_video_mf_t *)pArg;
	HRESULT hrStatus = S_OK;
	HRESULT hr = S_OK;
	IMFMediaEvent *pEvent = NULL;
    MediaEventType met;

	TSK_DEBUG_INFO("RunSessionThread - ENTER");

	while(pSelf->bStarted){
        CHECK_HR(hr = pSelf->pSession->GetEvent(0, &pEvent));
        CHECK_HR(hr = pEvent->GetStatus(&hrStatus));
        CHECK_HR(hr = pEvent->GetType(&met));

        if (FAILED(hrStatus))
        {
			TSK_DEBUG_ERROR("Session error: 0x%x (event id: %d)\n", hrStatus, met);
            hr = hrStatus;
            goto bail;
        }
        if (met == MESessionEnded)
        {
            break;
        }
        SafeRelease(&pEvent);
	}

bail:
	TSK_DEBUG_INFO("RunSessionThread - EXIT");

	return NULL;
}

#endif /*HAVE_MF  */
OpenPOWER on IntegriCloud