-
Notifications
You must be signed in to change notification settings - Fork 94
/
display_graph.cpp
4377 lines (3673 loc) · 127 KB
/
display_graph.cpp
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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
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
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------------
//
// MONOGRAM GraphStudio
//
// Author : Igor Janos
//
//-----------------------------------------------------------------------------
#include "stdafx.h"
#include <math.h>
#include <atlbase.h>
#include <atlpath.h>
#include "MediaTypeSelectForm.h"
#include "GRF_File.h"
#include <atlenc.h>
#include <set>
#include "Psapi.h"
#pragma warning(disable: 4244) // DWORD -> BYTE warning
GRAPHSTUDIO_NAMESPACE_START // cf stdafx.h for explanation
static bool CanSeekByTimeFormat(IMediaSeeking * ims, const GUID & time_format)
{
bool enable = false;
if (ims) {
DWORD caps = AM_SEEKING_CanSeekAbsolute;
if (S_OK == ims->CheckCapabilities(&caps)) {
if (S_OK == ims->IsUsingTimeFormat(&time_format)) {
enable = true;
} else {
// Some filters fail to convert time formats even when they advertise they support them
// so test the conversion before enabling seeking
LONGLONG dummy = 0LL;
enable = SUCCEEDED(ims->ConvertTimeFormat(&dummy, NULL, dummy, &time_format)) &&
SUCCEEDED(ims->ConvertTimeFormat(&dummy, &time_format, dummy, NULL));
}
}
}
return enable;
}
// attempt to determine whether a filter is a source or renderer
// based on methods used in dshowutil.h
static Filter::FilterPurpose GetFilterPurpose(const Filter * filter)
{
if (!filter)
return Filter::FILTER_OTHER;
CComQIPtr<IAMFilterMiscFlags> flags(filter->filter);
if (flags) {
const ULONG filter_flags = flags->GetMiscFlags();
if (filter_flags & AM_FILTER_MISC_FLAGS_IS_RENDERER)
return Filter::FILTER_RENDERER;
else if (filter_flags & AM_FILTER_MISC_FLAGS_IS_SOURCE)
return Filter::FILTER_SOURCE;
else
return Filter::FILTER_OTHER;
}
// Look for the following conditions:
// 1) Zero output pins AND at least 1 unmapped input pin
// - or -
// 2) At least 1 rendered input pin.
// definitions:
// unmapped input pin = IPin::QueryInternalConnections returns E_NOTIMPL
// rendered input pin = IPin::QueryInternalConnections returns "0" slots
// These cases are somewhat obscure and probably don't apply to many filters
// that actually exist.
for (int i=0; i<filter->input_pins.GetCount(); i++) {
const Pin * const input_pin = filter->input_pins[i];
// It's an input pin. Is it mapped to an output pin?
ULONG nPin = 0;
CONST HRESULT hr = input_pin->ipin->QueryInternalConnections(NULL, &nPin);
if (hr == S_OK) {
// The count (nPin) was zero, and the method returned S_OK, so
// this input pin is mapped to exactly zero ouput pins.
// Therefore, it is a rendered input pin.
return Filter::FILTER_RENDERER;
// The heuristics below are unreliable, probably because it matches the default
// QueryInternalConnections implementation in the baseclasses
//} else if (hr == E_NOTIMPL && filter->output_pins.GetCount() == 0) {
// This pin is not mapped to any particular output pin.
// // and there are no output pins
// CComPtr<IUnknown> unk;
// if (S_OK == filter->filter->QueryInterface(__uuidof(IBasicAudio), (void**)&unk)
// || filter->filter->QueryInterface(__uuidof(IBasicVideo), (void**)&unk))
// return Filter::FILTER_RENDERER;
}
}
CComPtr<IUnknown> unk;
// Last resort - some heuristics on which interfaces the filter supports, could be improved
if ( S_OK == filter->filter->QueryInterface(__uuidof(IBasicAudio), (void**)&unk)
|| S_OK == filter->filter->QueryInterface(__uuidof(IBasicVideo), (void**)&unk)
|| S_OK == filter->filter->QueryInterface(__uuidof(IFileSinkFilter), (void**)&unk))
return Filter::FILTER_RENDERER;
else if (S_OK == filter->filter->QueryInterface(__uuidof(IFileSourceFilter), (void**)&unk))
return Filter::FILTER_SOURCE;
else
return Filter::FILTER_OTHER;
}
//-------------------------------------------------------------------------
//
// DisplayGraph class
//
//-------------------------------------------------------------------------
DisplayGraph::DisplayGraph()
: callback(NULL)
, params(NULL)
, dc(NULL)
, is_remote(false)
, is_frame_stepping(false)
, uses_clock(true)
, clock_status_text(_T("No Clock"))
, rotRegister(0)
, dirty(true)
, m_filter_graph_clsid(&CLSID_FilterGraph)
, m_log_file(INVALID_HANDLE_VALUE)
, supports_time_seeking(false)
, supports_frame_seeking(false)
, min_time_per_frame(_I64_MAX)
{
HRESULT hr = NOERROR;
graph_callback = new GraphCallbackImpl(NULL, &hr, this);
graph_callback->NonDelegatingAddRef();
MakeNew();
}
DisplayGraph::~DisplayGraph()
{
CloseLogFile();
if (graph_callback) {
graph_callback->NonDelegatingRelease();
graph_callback = NULL;
}
DeleteAllFilters();
}
// caller must clean up graph if error returned
HRESULT DisplayGraph::ConnectToRemote(IFilterGraph *remote_graph)
{
int ret = MakeNew();
if (ret < 0)
return E_FAIL;
// release graph objects
RemoveFromRot();
mc = NULL;
ms = NULL;
fs = NULL;
if (me) {
// clear events...
me->SetNotifyWindow(NULL, 0, NULL);
me = NULL;
}
if (!is_remote && gb)
gb->SetLogFile(NULL);
gb = NULL;
cgb = NULL;
is_remote = false;
is_frame_stepping = false;
uses_clock = true;
// attach remote graph
HRESULT hr = remote_graph->QueryInterface(IID_IGraphBuilder, (void**)&gb);
if (FAILED(hr))
return hr;
// get hold of interfaces
hr = gb->QueryInterface(IID_IMediaControl, (void**)&mc);
if (FAILED(hr))
return hr;
hr = gb->QueryInterface(IID_IMediaSeeking, (void**)&ms);
if (FAILED(hr))
return hr;
hr = gb->QueryInterface(IID_IVideoFrameStep, (void**)&fs);
if (FAILED(hr))
return hr;
// now we're a remote graph
is_remote = true;
if(params)
params->is_remote = true;
return hr;
}
int DisplayGraph::AttachCaptureGraphBuilder()
{
if (cgb) return 1;
HRESULT hr = cgb.CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC_SERVER);
if (FAILED(hr)) return -1;
cgb->SetFiltergraph(gb);
return 0;
}
int DisplayGraph::MakeNew()
{
if (ms) ms = NULL;
if (fs) fs = NULL;
// release from ROT
RemoveFromRot();
// we only do this for our own graph so we don't mess up
// the host application when connected to remote graph
if (!is_remote) {
if (mc) {
mc->Stop();
mc = NULL;
}
if (me) {
// clear events...
me->SetNotifyWindow(NULL, 0, NULL);
me = NULL;
}
SelectAllFilters(true);
RemoveSelectionFromGraph();
DeleteAllFilters();
columns.RemoveAll();
if (gb)
gb->SetLogFile(NULL);
gb = NULL;
cgb = NULL;
} else {
mc = NULL;
me = NULL;
DeleteAllFilters();
columns.RemoveAll();
gb = NULL;
cgb = NULL;
}
is_remote = false;
if(params) params->is_remote = false;
is_frame_stepping = false;
uses_clock = true;
clock_status_text = "No Clock";
// create new instance of filter graph
HRESULT hr;
do {
hr = gb.CoCreateInstance(*m_filter_graph_clsid, NULL, CLSCTX_INPROC_SERVER);
if (FAILED(hr))
break;
// If log file already open use it with the new graph showing any errors
if (m_log_file != INVALID_HANDLE_VALUE)
DSUtil::ShowError(gb->SetLogFile((DWORD_PTR)m_log_file), _T("Set Log File"));
AddToRot();
// Historically, GraphStudio and GraphStudioNext used to always call SetDefaultSyncSource on startup
// This has been removed as appears it's not DirectShow best practice cf issue #291
// gb->SetDefaultSyncSource();
// This behaviour can be simulated by turning the graph clock off and on again
gb->QueryInterface(IID_IMediaControl, (void**)&mc);
// setup event handler
gb->QueryInterface(IID_IMediaEventEx, (void**)&me);
me->SetNotifyWindow((OAHWND)wndEvents, WM_GRAPH_EVENT, (LONG_PTR)this);
gb->QueryInterface(IID_IMediaSeeking, (void**)&ms);
gb->QueryInterface(IID_IVideoFrameStep, (void**)&fs);
AttachCaptureGraphBuilder();
// attach graph callback
CComPtr<IObjectWithSite> obj_with_site;
hr = gb->QueryInterface(IID_IObjectWithSite, (void**)&obj_with_site);
if (SUCCEEDED(hr)) {
CComPtr<IUnknown> unk;
graph_callback->NonDelegatingQueryInterface(IID_IUnknown, (void**)&unk);
obj_with_site->SetSite(unk);
unk = NULL;
obj_with_site = NULL;
}
} while (0);
if (FAILED(hr)) {
RemoveFromRot();
cgb = NULL;
gb = NULL;
mc = NULL;
me = NULL;
ms = NULL;
fs = NULL;
return -1;
}
RefreshClock();
return 0;
}
HRESULT DisplayGraph::OpenLogFile(LPCTSTR file_name)
{
if (!gb)
return E_POINTER;
if (is_remote)
return E_FAIL;
if (IsLogFileOpen())
return E_HANDLE;
gb->SetLogFile(NULL);
m_log_file = CreateFile(file_name, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
const DWORD error = GetLastError();
if(error != 0 && error != ERROR_ALREADY_EXISTS)
return HRESULT_FROM_WIN32(error);
return gb->SetLogFile((DWORD_PTR)m_log_file);
}
HRESULT DisplayGraph::CloseLogFile()
{
HRESULT hr = S_FALSE;
if (gb && !is_remote)
hr = gb->SetLogFile(NULL);
if (m_log_file != INVALID_HANDLE_VALUE) {
CloseHandle(m_log_file);
m_log_file = INVALID_HANDLE_VALUE;
}
return hr;
}
bool DisplayGraph::IsOwnRotGraph(const CString& moniker_name)
{
CString strPid;
// MAINTENANCE WARNING - this format string needs to be a substring of the format string in DisplayGraph::AddToRot
strPid.Format(_T("pid %08x"), GetCurrentProcessId());
return ( moniker_name.Find(strPid) != -1 );
}
void DisplayGraph::AddToRot()
{
// MAINTENANCE WARNING - this format string needs to include the format string in DisplayGraph::IsOwnGraph
#ifdef _WIN64
const WCHAR * const moniker_format_string = L"FilterGraph %08I64x pid %08x GraphStudioNextx64";
#else
const WCHAR * const moniker_format_string = L"FilterGraph %08x pid %08x GraphStudioNext";
#endif
IMoniker * pMoniker = NULL;
IRunningObjectTable *pROT = NULL;
if (FAILED(GetRunningObjectTable(0, &pROT)))
return;
const size_t STRING_LENGTH = 256;
WCHAR wsz[STRING_LENGTH];
StringCchPrintfW(
wsz, STRING_LENGTH,
moniker_format_string,
(void*)(gb.p),
GetCurrentProcessId()
);
HRESULT hr = CreateItemMoniker(L"!", wsz, &pMoniker);
if (SUCCEEDED(hr))
{
hr = pROT->Register(ROTFLAGS_REGISTRATIONKEEPSALIVE, gb, pMoniker, &rotRegister);
pMoniker->Release();
}
pROT->Release();
}
void DisplayGraph::RemoveFromRot()
{
if (rotRegister != 0)
{
IRunningObjectTable *pROT;
if (SUCCEEDED(GetRunningObjectTable(0, &pROT)))
{
pROT->Revoke(rotRegister);
pROT->Release();
}
rotRegister = 0;
}
}
void DisplayGraph::SelectAllFilters(bool select)
{
for (int i=0; i<filters.GetCount(); i++) {
filters[i]->Select(select);
}
}
CRect DisplayGraph::GetGraphSize()
{
// find out the rectangle
CRect rect(0, 0, 0, 0);
for (int i=0; i<filters.GetCount(); i++) {
Filter *filter = filters[i];
rect.left = (i==0 || filter->posx < rect.left) ? filter->posx : rect.left ;
rect.top = (i==0 || filter->posy < rect.top) ? filter->posy : rect.top ;
rect.right = (i==0 || filter->posx + filter->width > rect.right) ? filter->posx+filter->width : rect.right ;
rect.bottom = (i==0 || filter->posy + filter->height > rect.bottom) ? filter->posy+filter->height : rect.bottom ;
}
// Round outwards and add an extra grid of border
rect.left = DisplayGraph::PrevGridPos(rect.left) - DisplayGraph::GRID_SIZE;
rect.left = max(rect.left, 0);
rect.top = DisplayGraph::PrevGridPos(rect.top) - DisplayGraph::GRID_SIZE;
rect.top = max(rect.top, 0);
rect.right = DisplayGraph::NextGridPos(rect.right) + DisplayGraph::GRID_SIZE;
rect.bottom = DisplayGraph::NextGridPos(rect.bottom) + DisplayGraph::GRID_SIZE;
return rect;
}
int DisplayGraph::GetState(FILTER_STATE &state, DWORD timeout)
{
if (!mc) {
state = State_Stopped;
return -1;
}
// pretend we're in paused state
if (is_frame_stepping) {
state = State_Paused;
return NOERROR;
}
HRESULT hr = mc->GetState(timeout, (OAFilterState*)&state);
if (FAILED(hr)) return hr;
return hr;
}
void DisplayGraph::DoFrameStep()
{
if (fs) {
fs->Step(1, NULL);
is_frame_stepping = true;
}
}
HRESULT DisplayGraph::DoPlay(bool full_screen /*= false*/)
{
HRESULT hr = S_OK;
// notify all EVR windows
if (!is_remote) {
for (int i=0; i<filters.GetCount(); i++) {
Filter *filter = filters[i];
if (filter->videowindow) {
hr = filter->videowindow->Start(full_screen);
if (FAILED(hr))
return hr;
}
}
}
if (is_frame_stepping) {
if (fs)
hr = fs->CancelStep();
if (mc)
hr = mc->Run();
// reset the frame stepping flag
is_frame_stepping = false;
} else {
hr = mc ? mc->Run() : E_NOINTERFACE;
}
return hr;
}
HRESULT DisplayGraph::DoStop()
{
HRESULT hr = S_OK;
if (!is_remote) {
for (int i=0; i<filters.GetCount(); i++) {
Filter *filter = filters[i];
if (filter->videowindow) {
hr = filter->videowindow->Stop();
}
}
}
if (is_frame_stepping) {
if (fs)
hr = fs->CancelStep();
is_frame_stepping = false;
}
if (mc) {
hr = mc->Stop();
Seek(0);
return hr;
}
return E_NOINTERFACE;
}
HRESULT DisplayGraph::DoPause(bool full_screen /*= false*/)
{
HRESULT hr = S_OK;
// send start notification to all EVR filters
// set the new clock for all filters
if (!is_remote) {
for (int i=0; i<filters.GetCount(); i++) {
Filter *filter = filters[i];
if (filter->videowindow) {
hr = filter->videowindow->Start(full_screen);
if (FAILED(hr))
return hr;
}
}
}
if (mc)
hr = mc->Pause();
return hr;
}
int DisplayGraph::Seek(double time_ms, BOOL keyframe)
{
if (!ms)
return E_POINTER;
REFERENCE_TIME rtpos = time_ms * (UNITS/1000);
DWORD flags = AM_SEEKING_AbsolutePositioning;
if (keyframe) {
flags |= AM_SEEKING_SeekToKeyFrame;
}
ms->SetTimeFormat(&TIME_FORMAT_MEDIA_TIME); // other format may be in use by CSeekForm
return ms->SetPositions(&rtpos, flags, NULL, AM_SEEKING_NoPositioning);
}
int DisplayGraph::GetRate(double* rate)
{
if (!ms) return -1;
return ms->GetRate(rate);
}
int DisplayGraph::SetRate(double rate)
{
if (!ms) return -1;
return ms->SetRate(rate);
}
void DisplayGraph::RefreshClock()
{
bool uses_clock_from_filter = false;
// update clock status for all filters
for (int i=0; i<filters.GetCount(); i++) {
Filter *filter = filters[i];
filter->UpdateClock();
uses_clock_from_filter |= filter->is_sync_source;
}
// Ask the graph whether which clock we're using - it may not be one of the filters
bool uses_system_clock = false;
CComPtr<IReferenceClock> new_clock;
CComQIPtr<IMediaFilter> sync_interface(gb);
if (sync_interface && SUCCEEDED(sync_interface->GetSyncSource(&new_clock))) {
uses_clock = new_clock.p != NULL;
CComQIPtr<IPersist> persist(new_clock);
if (persist) {
CLSID clsidClock;
persist->GetClassID(&clsidClock);
uses_system_clock = (CLSID_SystemClock == clsidClock) != FALSE;
}
}
if (new_clock)
{
if (uses_clock_from_filter)
clock_status_text = _T("Clock from Filter");
else if (uses_system_clock)
clock_status_text = _T("System Clock");
else
clock_status_text = _T("Unknown Clock");
}
else
clock_status_text = _T("No Clock");
}
void DisplayGraph::SetClock(bool default_clock, IReferenceClock *new_clock)
{
FILTER_STATE state;
int ret = GetState(state, 50);
if (ret < 0) {
MessageBeep(MB_ICONASTERISK);
return ;
}
if (state != State_Stopped) {
MessageBeep(MB_ICONASTERISK);
return ;
}
if (default_clock) {
if (gb)
gb->SetDefaultSyncSource();
uses_clock = true;
} else {
// Don't call SetSyncSource directly on filters, call IMediaFilter::SetSyncSource on filter graph manager instead
// MSDN docs warn about this. Calling filters directly causes unreliable clock setting behaviour
uses_clock = (new_clock == NULL ? false : true);
CComQIPtr<IMediaFilter> sync_interface(gb);
if (sync_interface)
sync_interface->SetSyncSource(new_clock);
}
RefreshClock();
}
// seeking helpers
int DisplayGraph::GetFPS(double &fps)
{
fps = this->fps;
return 0;
}
int DisplayGraph::RefreshFPS()
{
supports_time_seeking = CanSeekByTimeFormat(ms, TIME_FORMAT_MEDIA_TIME);
supports_frame_seeking = CanSeekByTimeFormat(ms, TIME_FORMAT_FRAME);
// calculate fps via min_time_per_frame in case frame time format is not supported
if (min_time_per_frame > 0LL && min_time_per_frame < _I64_MAX) {
fps = (double)UNITS / (double)min_time_per_frame;
} else {
fps = 0.0;
}
if (!ms) {
return 0;
}
HRESULT hr = NOERROR;
do {
REFERENCE_TIME rtDur, rtFrames;
rtDur = 0;
rtFrames = 0;
if (ms->IsFormatSupported(&TIME_FORMAT_FRAME) != NOERROR) {
hr = E_FAIL;
break;
}
hr = ms->SetTimeFormat(&TIME_FORMAT_FRAME);
if (SUCCEEDED(hr))
hr = ms->GetDuration(&rtFrames);
hr = ms->SetTimeFormat(&TIME_FORMAT_MEDIA_TIME);
if (SUCCEEDED(hr))
hr = ms->GetDuration(&rtDur);
// special case
if (rtFrames == 0 || rtDur == 0) {
return 0;
}
// calculate the FPS
fps = (double)rtFrames * (double)UNITS / (double)rtDur;
hr = NOERROR;
} while (0);
if (FAILED(hr)) {
return -1;
}
return 0;
}
int DisplayGraph::GetPositionAndDuration(double ¤t_ms, double &duration_ms)
{
if (!ms) {
current_ms = 0;
duration_ms = 0;
return 0;
}
HRESULT hr = NOERROR;
do {
GUID time_format;
REFERENCE_TIME rtDur, rtCur;
hr = ms->GetTimeFormat(&time_format);
if (FAILED(hr)) break;
// get duration
hr = ms->GetDuration(&rtDur);
if (FAILED(hr)) {
duration_ms = 0;
} else {
// do we need to convert the time ?
if (time_format != TIME_FORMAT_MEDIA_TIME) {
REFERENCE_TIME temp;
GUID out_format = TIME_FORMAT_MEDIA_TIME;
hr = ms->ConvertTimeFormat(&temp, &out_format, rtDur, &time_format);
if (FAILED(hr)) {
temp = 0;
}
rtDur = temp;
}
// in milliseconds
duration_ms = (double)rtDur / (double)(UNITS/1000);
}
/*
I had to enable exceptions for C++ because Gabest's Avi Splitter
kept crashing after this call when not connected. Not sure why.
But the splitter wasn't able to play any files.. so I guess
it might be wrong.
*/
// get position
try {
hr = ms->GetCurrentPosition(&rtCur);
}
catch (...) {
hr = E_FAIL;
}
if (FAILED(hr)) {
current_ms = 0;
} else {
// do we need to convert the time ?
if (time_format != TIME_FORMAT_MEDIA_TIME) {
REFERENCE_TIME temp;
GUID out_format = TIME_FORMAT_MEDIA_TIME;
hr = ms->ConvertTimeFormat(&temp, &out_format, rtCur, &time_format);
if (FAILED(hr)) {
temp = 0;
}
rtCur = temp;
}
// in seconds
current_ms = (double)rtCur / (double)(UNITS/1000);
}
hr = NOERROR;
} while (0);
if (FAILED(hr)) {
current_ms = 0;
duration_ms = 0;
return hr;
}
return 0;
}
void DisplayGraph::RemoveSelectionFromGraph()
{
Pin * selected_pin = NULL;
// For safety remove any IPin references from pins that aren't affected by the operation
// For some buggy filters, disconnecting one pin may delete other pins rather than Releasing them
// These will be refreshed by RefreshFilters call below
for (int i=0; i<filters.GetCount(); i++) {
if (!filters[i]->selected) { // Filter not selected
for (int j=0; j<=1; j++) {
CArray<Pin*> & pins = j==0 ? filters[i]->output_pins : filters[i]->input_pins;
for (int k=0; k<pins.GetCount(); k++) {
Pin * const pin = pins[k];
if (!pin->selected && (!pin->peer || !pin->peer->selected)) // pin not selected and not connected to selected pin
pin->Load(NULL);
}
}
}
}
// first delete connections and then filters
for (int i=0; i<filters.GetCount(); i++) {
if (!filters[i]->selected)
filters[i]->RemoveSelectedConnections(); // Allow code below to deal with deleting selected filters and their connections
}
for (int i=0; i<filters.GetCount(); i++) {
if (filters[i]->selected) {
// select the output pin the deleted filter was connected to
CArray<Pin*> & pins(filters[i]->input_pins);
const int pin_count = pins.GetCount();
for (int k=0; k<pin_count && !selected_pin; k++) {
if (pins[k]->peer && !pins[k]->peer->filter->selected)
selected_pin = pins[k]->peer;
}
if (callback)
callback->OnFilterRemoved(this, filters[i]);
filters[i]->RemoveFromGraph();
}
}
if (selected_pin)
selected_pin->selected = true;
RefreshFilters();
SmartPlacement(false);
}
HRESULT DisplayGraph::AddFilter(IBaseFilter *filter, CString proposed_name)
{
if (!gb) return E_FAIL;
// find the best name
CComPtr<IBaseFilter> temp;
CString name = proposed_name;
HRESULT hr = gb->FindFilterByName(name, &temp);
if (SUCCEEDED(hr)) {
temp = NULL;
int i=0;
do {
name.Format(_T("%s %.04d"), (LPCTSTR)proposed_name, i);
hr = gb->FindFilterByName(name, &temp);
temp = NULL;
i++;
} while (hr == NOERROR);
}
// now we have unique name
hr = gb->AddFilter(filter, name);
if (FAILED(hr)) {
// cannot add filter
return hr;
}
// refresh our filters
RefreshFilters();
return NOERROR;
}
static CStringA UTF16toUTF8(const CStringW &utf16)
{
CStringA utf8;
int len = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL, 0, 0, 0);
if (len>1) {
char *ptr = utf8.GetBuffer(len-1);
if (ptr) WideCharToMultiByte(CP_UTF8, 0, utf16, -1, ptr, len, 0, 0);
utf8.ReleaseBuffer();
}
return utf8;
}
static BOOL MakeRelative(const CPath& sBaseDirectory, CString& sPath)
{
if(!_tcslen(sBaseDirectory))
return FALSE; // No Base
CPath sRelativePath;
// NOTE: We prefer to restrict to containing directory (note that API returns path started with .\)
if(!sRelativePath.RelativePathTo(sBaseDirectory, FILE_ATTRIBUTE_DIRECTORY, sPath, FILE_ATTRIBUTE_NORMAL))
return FALSE; // Failed to Make Relative
// if(CString(sRelativePath).Left(3).Compare(_T("..\\")) == 0)
// return FALSE; // Not There or Deeper
if(!_tcslen(sRelativePath))
return FALSE; // Unexpected
sPath = (LPCTSTR) sRelativePath;
return TRUE;
}
static HRESULT SaveXML_IFileSourceFilter(IBaseFilter *filter, XML::XMLWriter &xml, const CPath& sBaseDirectory)
{
CComQIPtr<IFileSourceFilter> src(filter);
if (src) {
CComHeapPtr<OLECHAR> fn;
CMediaType media_type;
if (SUCCEEDED(src->GetCurFile(&fn, &media_type))) {
// <ifilesourcefilter source="d:\sga.avi"/>
xml.BeginNode(_T("ifilesourcefilter"));
CString sPath(fn);
CString sRelativePath = sPath;
if(MakeRelative(sBaseDirectory, sRelativePath))
xml.WriteValue(_T("relativesource"), sRelativePath);
xml.WriteValue(_T("source"), sPath);
xml.EndNode();
}
}
return S_OK;
}
static HRESULT SaveXML_IFileSinkFilter(IBaseFilter *filter, XML::XMLWriter &xml, const CPath& sBaseDirectory)
{
CComQIPtr<IFileSinkFilter> sink(filter);
if (sink) {
CComHeapPtr<OLECHAR> fn;
CMediaType media_type;
if (SUCCEEDED(sink->GetCurFile(&fn, &media_type))) {
// <ifilesinkfilter dest="d:\sga.avi"/>
xml.BeginNode(_T("ifilesinkfilter"));
CString sPath(fn);
CString sRelativePath = sPath;
if(MakeRelative(sBaseDirectory, sRelativePath))
xml.WriteValue(_T("relativedest"), sRelativePath);
xml.WriteValue(_T("dest"), sPath);
xml.EndNode();
}
}
return S_OK;
}
static HRESULT SaveXML_IPersistStream(IBaseFilter *filter, XML::XMLWriter &xml)
{
HRESULT hr = E_FAIL;
CComQIPtr<IPersistStream> persist_stream(filter);
if (persist_stream) {
const HGLOBAL hglobal_stream = GlobalAlloc(GHND, 0); // free by stream unless stream isn't created
CComPtr<IStream> stream;
CreateStreamOnHGlobal(hglobal_stream, FALSE, &stream);
if (stream
&& hglobal_stream
&& SUCCEEDED(hr = persist_stream->Save(stream, TRUE))) {
const SIZE_T binary_max_size = GlobalSize(hglobal_stream);
BYTE * const binary_data = new BYTE[binary_max_size]; // create buffer big enough for all data
LARGE_INTEGER start_offset;
start_offset.QuadPart = 0LL;
HRESULT hr2 = stream->Seek(start_offset, STREAM_SEEK_SET, NULL);
ASSERT(SUCCEEDED(hr2));
ULONG binary_size = 0;
hr2 = stream->Read(binary_data, binary_max_size, &binary_size); // read as much data as is available
ASSERT(SUCCEEDED(hr2));
if (binary_size > 0) { // Some datas have zero bytes of IPersistStream data
const DWORD base64_flags = ATL_BASE64_FLAG_NOCRLF;
const int base64_size = Base64EncodeGetRequiredLength(binary_size, base64_flags);
char* const base64_data = new char[base64_size];
int converted_size = base64_size;
if (Base64Encode((const BYTE*)binary_data, binary_size, base64_data, &converted_size, base64_flags)
&& converted_size > 0) {
// <ipersiststream encoding="base64" data="MAAwADAAMAAwADAAMAAwADAAMAAwACAA="/>
xml.BeginNode(_T("ipersiststream"));
xml.WriteValue(_T("encoding"), _T("base64"));
xml.WriteValue(_T("data"), CString(base64_data, converted_size));
xml.EndNode();
} else {
ASSERT(!"base64 conversion failed");
}
delete[] base64_data;
}
delete[] binary_data;
} else {
ASSERT(!"Failed to create IStream");
}
if (hglobal_stream)
GlobalFree(hglobal_stream);
}
return S_OK;
}
static void SaveXML_MediaType(XML::XMLWriter &xml, const CMediaType& mt)
{
xml.BeginNode(_T("mediaType"));
CString type_name;
CString guid_name;
// name major and/or sub type if known for readability of XML file