forked from MakeMagazinDE/GRBLize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VSample.pas
1564 lines (1274 loc) · 50.3 KB
/
VSample.pas
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
unit VSample;
(******************************************************************************
VSample.pas
Class TVideoSample
About
The TVideoSample class provides access to WebCams and similar Video-capture
devices via DirectShow.
It is based mainly on C++ examples from the Microsoft DirectX 9.0 SDK Update
(Summer 2003): PlayCap and PlayCapMoniker. Comments found in those samples
are copied into this Delphi code.
Depends on the DirectX Header conversion files which could be found here:
- http://www.progdigy.com
- http://www.clootie.ru/delphi
History
Version 1.22
2012-07-08 (Fixed some memory leaks. List of supported video sizes/compressions corrected)
Version 1.21
06.05.2012 (ansichar instead of char)
Version 1.2
23.08.2009
Version 1.1
07.09.2008
Version 1.03
30.08.2008
Version 1.02
26.07.2008
Version 1.01
03.05.2008
Version 1.0
16.01.2006
Contact:
michael@grizzlymotion.com
Copyright
Portions created by Microsoft are Copyright (C) Microsoft Corporation.
Original file names: PlayCap.cpp, PlayCapMoniker.cpp.
For copyrights of the DirectX Header ports see the original source files.
Other code (unless stated otherwise, see comments): Copyright (C) M. Braun
Licence:
The lion share of this project lies within the ports of the DirectX header
files (which are under the Mozilla Public License Version 1.1), and the
original SDK sample files from Microsoft (END-USER LICENSE AGREEMENT FOR
MICROSOFT SOFTWARE DirectX 9.0 Software Development Kit Update (Summer 2003))
My own contribution compared to that work is very small (although it cost me
lots of time), but still is "significant enough" to fulfill Microsofts licence
agreement ;)
So I think, the ZLib licence (http://www.zlib.net/zlib_license.html)
should be sufficient for my code contributions.
Please note:
There exist much more complete alternatives (incl. sound, AVI etc.):
- DSPack (http://www.progdigy.com/)
- TVideoCapture by Egor Averchenkov (can be found at http://www.torry.net)
******************************************************************************)
interface
USES Windows, Messages, SysUtils, Classes, ActiveX, Forms,
{$ifdef DXErr} DXErr9, {$endif}
DirectShow9;
{ $ define REGISTER_FILTERGRAPH}
CONST
WM_GRAPHNOTIFY = WM_APP+1;
WM_NewFrame = WM_User+2; // Used to inform application that a new video
// frame has arrived. Necessary only, if
// application hasn't defined a callback
// routine via TVideoSample.SetCallBack(...).
CONST { Copied from OLE2.pas }
{$EXTERNALSYM IID_IUnknown}
IID_IUnknown: TGUID = (
D1:$00000000;D2:$0000;D3:$0000;D4:($C0,$00,$00,$00,$00,$00,$00,$46));
TYPE
TPLAYSTATE = (PS_Stopped,
{PS_Init,}
PS_Paused,
PS_Running);
// ---= Pseudo-Interface for Frame Grabber Callback Routines =-------------
// c.f. Delphi Help text "Delegating to a class-type property"
//
// ISampleGrabber.SetCallback verlangt als ersten Parameter ein "ISampleGrabberCB"
// Um für ein solches Interface Routinen zu deklarieren ist scheinbar das
// folgende, sonderbare Konstrukt nötig.
//
// ISampleGrabber.SetCallback needs an "ISampleGrabberCB" as first parameter.
// This is my attempt to build such a thing with Delphi.
TYPE
TVideoSampleCallBack= procedure(pb : pbytearray; var Size: integer) of object;
TSampleGrabberCBInt = interface(ISampleGrabberCB)
function SampleCB(SampleTime: Double; pSample: IMediaSample): HResult; stdcall;
function BufferCB(SampleTime: Double; pBuffer: PByte; BufferLen: longint): HResult; stdcall;
end;
TSampleGrabberCBImpl= class
CallBack : TVideoSampleCallBack;
function SampleCB(SampleTime: Double; pSample: IMediaSample): HResult; stdcall;
function BufferCB(SampleTime: Double; pBuffer: PByte; BufferLen: longint): HResult; stdcall;
end;
TSampleGrabberCB = class(TInterfacedObject, TSampleGrabberCBInt)
FSampleGrabberCB: TSampleGrabberCBImpl;
CallBack : TVideoSampleCallBack;
property SampleGrabberCB: TSampleGrabberCBImpl read FSampleGrabberCB implements TSampleGrabberCBInt;
end;
TFormatInfo = RECORD
Width,
Height : integer;
SSize : cardinal;
OIndex : integer;
mt : TAMMediaType;
FourCC : ARRAY[0..3] OF ansichar; // ansichar, because in Delphi 2009 char is something different ;)
END;
TVideoSample = class(TObject)
private
ghApp : HWND;
pIVideoWindow : IVideoWindow;
pIMediaControl : IMediaControl;
pIMediaEventEx : IMediaEventEx;
pIGraphBuilder : IGraphBuilder;
pICapGraphBuild2 : ICaptureGraphBuilder2;
g_psCurrent : TPLAYSTATE;
pIAMStreamConfig : IAMStreamConfig;
piBFSampleGrabber : IBaseFilter;
pIAMVideoProcAmp : IAMVideoProcAmp;
pIBFNullRenderer : IBaseFilter;
pIKsPropertySet : IKsPropertySet;
pISampleGrabber : ISampleGrabber;
pIBFVideoSource : IBaseFilter;
{$ifdef REGISTER_FILTERGRAPH}
g_dwGraphRegister :DWORD;
{$endif}
SGrabberCB : TSampleGrabberCB;
_SGrabberCB : TSampleGrabberCBInt;
fVisible : boolean;
CallBack : TVideoSampleCallBack;
FormatArr : ARRAY OF TFormatInfo;
FUNCTION GetInterfaces(ForceRGB: boolean; WhichMethodToCallback: integer): HRESULT;
FUNCTION SetupVideoWindow(): HRESULT;
FUNCTION ConnectToCaptureDevice(DeviceName: string; VAR DeviceSelected: string; VAR ppIBFVideoSource: IBaseFilter): HRESULT;
FUNCTION RestartVideoEx(Visible: boolean):HRESULT;
FUNCTION ShowPropertyDialogEx(const IBF: IUnknown; FilterName: PWideChar): HResult;
FUNCTION LoadListOfResolution: HResult;
procedure DeleteBelow(const IBF: IBaseFilter);
procedure CloseInterfaces;
public
{$ifdef DXErr}
DXErrString: string; // for debugging
{$endif}
constructor Create(VideoCanvasHandle: THandle; ForceRGB: boolean; WhichMethodToCallback: integer; VAR HR: HResult);
destructor Destroy; override;
property PlayState: TPLAYSTATE read g_psCurrent;
procedure ResizeVideoWindow();
FUNCTION RestartVideo:HRESULT;
FUNCTION StartVideo(CaptureDeviceName: string; Visible: boolean; VAR DeviceSelected: string):HRESULT;
FUNCTION PauseVideo: HResult; // Pause running video
FUNCTION ResumeVideo: HResult; // Re-start paused video
FUNCTION StopVideo: HResult;
function GetImageBuffer(VAR pb : pbytearray; var Size: integer): HResult;
FUNCTION SetPreviewState(nShow: boolean): HRESULT;
FUNCTION ShowPropertyDialog: HResult;
FUNCTION ShowPropertyDialog_CaptureStream: HResult;
FUNCTION GetVideoPropAmpEx( Prop : TVideoProcAmpProperty;
VAR pMin, pMax,
pSteppingDelta,
pDefault : longint;
VAR pCapsFlags : TVideoProcAmpFlags;
VAR pActual : longint): HResult;
FUNCTION SetVideoPropAmpEx( Prop : TVideoProcAmpProperty;
pCapsFlags : TVideoProcAmpFlags;
pActual : longint): HResult;
PROCEDURE GetVideoPropAmpPercent(Prop: TVideoProcAmpProperty; VAR AcPerCent: integer);
PROCEDURE SetVideoPropAmpPercent(Prop: TVideoProcAmpProperty; AcPerCent: integer);
PROCEDURE GetVideoSize(VAR Width, height: integer);
FUNCTION ShowVfWCaptureDlg: HResult;
FUNCTION GetStreamInfo(VAR Width, Height: integer; VAR FourCC: dword): HResult;
FUNCTION GetExProp( guidPropSet : TGuiD;
dwPropID : TAMPropertyPin;
pInstanceData : pointer;
cbInstanceData: DWORD;
out pPropData;
cbPropData : DWORD;
out pcbReturned : DWORD): HResult;
FUNCTION SetExProp( guidPropSet : TGuiD;
dwPropID : TAMPropertyPin;
pInstanceData : pointer;
cbInstanceData : DWORD;
pPropData : pointer;
cbPropData : DWORD): HResult;
FUNCTION GetCaptureIAMStreamConfig(VAR pSC: IAMStreamConfig): HResult;
PROCEDURE DeleteCaptureGraph;
PROCEDURE SetCallBack(CB: TVideoSampleCallBack);
FUNCTION GetPlayState: TPlayState; // Deprecated
PROCEDURE GetListOfVideoSizes(VidSize: TStringList);
FUNCTION SetVideoSizeByListIndex(ListIndex: integer): HResult;
{$ifdef REGISTER_FILTERGRAPH}
FUNCTION AddGraphToRot(pUnkGraph: IUnknown; VAR pdwRegister: DWORD):HRESULT;
procedure RemoveGraphFromRot(pdwRegister: dword);
{$endif}
END;
FUNCTION TGUIDEqual(const TG1, TG2 : TGUID): boolean;
FUNCTION GetCaptureDeviceList(VAR SL: TStringList): HResult;
implementation
FUNCTION TGUIDEqual(const TG1, TG2 : TGUID): boolean;
BEGIN
Result := CompareMem(@TG1, @TG2, SizeOf(TGUID));
END; {TGUIDEqual}
{ Get a list of all capture devices installed }
FUNCTION GetCaptureDeviceList(VAR SL: TStringList): HResult;
VAR
pDevEnum : ICreateDevEnum;
pClassEnum : IEnumMoniker;
st : string;
// Okay, in the original C code from the microsoft samples this
// is not a subroutine.
// I decided to use it as a subroutine, because Delphi won't let
// me free pMoniker or pPropertyBag myself. ( ":= nil" )
// Hopefully ending the subroutine will clean up all instances of
// these interfaces automatically...
FUNCTION GetNextDeviceName(VAR Name: string): boolean;
VAR
pMoniker : IMoniker;
pPropertyBag : IPropertyBag;
v : OLEvariant;
cFetched : ulong;
BEGIN
Result := false;
Name := '';
pMoniker := nil;
IF (S_OK = (pClassEnum.Next (1, pMoniker, @cFetched))) THEN
BEGIN
pPropertyBag := nil;
if S_OK = pMoniker.BindToStorage(nil, nil, IPropertyBag, pPropertyBag) then
begin
if S_OK = pPropertyBag.Read('FriendlyName', v, nil) then
begin
Name := v;
Result := true;
end;
end;
END;
END; {GetNextDeviceName}
begin
Result := S_FALSE;
if not(assigned(SL)) then
SL := TStringlist.Create;
try
SL.Clear;
except
exit;
end;
// Create the system device enumerator
Result := CoCreateInstance (CLSID_SystemDeviceEnum,
nil,
CLSCTX_INPROC_SERVER,
IID_ICreateDevEnum,
pDevEnum);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
begin
// Couldn't create system enumerator!
exit;
end;
// Create an enumerator for the video capture devices
pClassEnum := nil;
Result := pDevEnum.CreateClassEnumerator (CLSID_VideoInputDeviceCategory, pClassEnum, 0);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
begin
// Couldn't create class enumerator!
exit;
end;
// If there are no enumerators for the requested type, then
// CreateClassEnumerator will succeed, but pClassEnum will be nil.
if (pClassEnum = nil) then
begin
// No video capture device was detected.
exit;
end;
WHILE GetNextDeviceName(st) DO
SL.Add(st);
end; {GetCaptureDeviceList}
// ---= Sample Grabber callback routines =------------------------------------
// In routine TVideoSample.GetInterfaces(..) the callback routine is defined
// with pISampleGrabber.SetCallback(..,..). If the second parameter in that
// call is 1, then the routine below is called during a callback.
// Otherwise, if the parameter is 0, callback routine BufferCB would be called.
function TSampleGrabberCBImpl.SampleCB(SampleTime: Double; pSample: IMediaSample): HResult; stdcall;
var
BufferLen: integer;
ppBuffer : pbyte;
begin
BufferLen := pSample.GetSize;
if BufferLen > 0 then
begin
pSample.GetPointer(ppBuffer); {*}
if @CallBack = nil
then SendMessage(Application.Mainform.handle, WM_NewFrame, BufferLen, integer(ppBuffer))
else Callback(pbytearray(ppBuffer), BufferLen);
end;
Result := 0;
end;
{*}
// Nebenbei bemerkt: Beim Debuggen fiel mir auf, daß die von mir verwendete
// WebCam scheinbar einen Triple-Buffer für die Bilddaten verwendet. Die oben
// von pSample.GetPointer(ppBuffer) zurückgelieferte Adresse wiederholt sich
// in einem 3-er Zyklus. Wenn das ein Feature von DirectShow ist und nicht
// von der Kamera-Steuersoftware, dann könnte man selbst auf Double- oder
// Triplebuffering verzichten.
// In routine TVideoSample.GetInterfaces(..) the callback routine is defined
// with pISampleGrabber.SetCallback(..,..). If the second parameter in that
// call is 0, then the routine below is called during a callback.
// Otherwise, if the parameter is 1, callback routine SampleCB would be called.
function TSampleGrabberCBImpl.BufferCB(SampleTime: Double; pBuffer: PByte; BufferLen: longint): HResult; stdcall;
begin
if BufferLen > 0 then
begin
if @CallBack = nil
then SendMessage(Application.Mainform.handle, WM_NewFrame, BufferLen, integer(pBuffer))
else Callback(pbytearray(pBuffer), BufferLen);
end;
Result := 0;
end;
// ---= End of Sample Grabber callback routines =---------------------------
constructor TVideoSample.Create(VideoCanvasHandle: THandle; ForceRGB: boolean; WhichMethodToCallback: integer; VAR HR: HResult);
begin
ghApp := 0;
pIVideoWindow := nil;
pIMediaControl := nil;
pIMediaEventEx := nil;
pIGraphBuilder := nil;
pICapGraphBuild2 := nil;
g_pSCurrent := PS_Stopped;
pIAMStreamConfig := nil;
piBFSampleGrabber := nil;
pIAMVideoProcAmp := nil;
pIKsPropertySet := nil;
{$ifdef REGISTER_FILTERGRAPH}
g_dwGraphRegister:=0;
{$endif}
pISampleGrabber := nil;
pIBFVideoSource := nil;
SGrabberCB := nil;
_SGrabberCB := nil;
pIBFNullRenderer := nil;
CallBack := nil;
inherited create;
ghApp := VideoCanvasHandle;
HR := GetInterfaces(ForceRGB, WhichMethodToCallback);
end;
FUNCTION TVideoSample.GetInterfaces(ForceRGB: boolean; WhichMethodToCallback: integer): HRESULT;
VAR
MT: _AMMediaType;
BEGIN
//--- Create the filter graph
Result := CoCreateInstance(CLSID_FilterGraph,
nil,
CLSCTX_INPROC,
IID_IGraphBuilder,
pIGraphBuilder);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
exit;
//--- Create Sample grabber
Result := CoCreateInstance(CLSID_SampleGrabber,
nil,
CLSCTX_INPROC_SERVER,
IBaseFilter,
piBFSampleGrabber);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
exit;
Result := CoCreateInstance(CLSID_NullRenderer, nil, CLSCTX_INPROC_SERVER,
IID_IBaseFilter, pIBFNullRenderer);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
exit;
Result := piBFSampleGrabber.QueryInterface(IID_ISampleGrabber, pISampleGrabber);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
exit;
pISampleGrabber.SetBufferSamples(false); // No buffering required in this demo
//--- Force 24bit color depth. (RGB24 erzwingen)
IF ForceRGB then
begin
FillChar(MT, sizeOf(MT), #0);
MT.majortype := MediaType_Video;
MT.subtype := MediaSubType_RGB24;
Result := pISampleGrabber.SetMediaType(MT);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
exit;
end;
//--- Prepare Sample-Grabber Callback Object----
if not assigned(SGrabberCB) then
begin
SGrabberCB := TSampleGrabberCB.Create;
TSampleGrabberCB(SGrabberCB).FSampleGrabberCB := TSampleGrabberCBImpl.Create;
_SGrabberCB := TSampleGrabberCB(SGrabberCB);
// Should this be _SGrabberCB := SGrabberCB as TSampleGrabberCB ?????!!!!!
// Compare discussion on
// http://delphi.newswhat.com/geoxml/forumgetthread?groupname=borland.public.delphi.oodesign&messageid=44f84705@newsgroups.borland.com&displaymode=all
// However, link has been lost in the web :(
end;
pISampleGrabber.SetCallback(ISampleGrabberCB(_SGrabberCB), WhichMethodToCallback);
// WhichMethodToCallback=0: SampleGrabber calls SampleCB with the original media sample
// WhichMethodToCallback=1: SampleGrabber calls BufferCB with a copy of the media sample
//--- Create the capture graph builder
Result := CoCreateInstance(CLSID_CaptureGraphBuilder2,
nil,
CLSCTX_INPROC,
IID_ICaptureGraphBuilder2,
pICapGraphBuild2);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
exit;
// Obtain interfaces for media control and Video Window
Result := pIGraphBuilder.QueryInterface(IID_IMediaControl, pIMediaControl);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
exit;
Result := pIGraphBuilder.QueryInterface(IID_IVideoWindow, pIVideoWindow);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
exit;
Result := pIGraphBuilder.QueryInterface(IID_IMediaEvent, pIMediaEventEx);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
exit;
//--- Set the window handle used to process graph events
Result := pIMediaEventEx.SetNotifyWindow(OAHWND(ghApp), WM_GRAPHNOTIFY, 0);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
end;
FUNCTION TVideoSample.ConnectToCaptureDevice(DeviceName: string; VAR DeviceSelected: string; VAR ppIBFVideoSource: IBaseFilter): HRESULT;
VAR
pDevEnum : ICreateDevEnum;
pClassEnum : IEnumMoniker;
Index : integer;
Found : boolean;
// see also: http://msdn.microsoft.com/en-us/library/ms787619.aspx
FUNCTION CheckNextDeviceName(Name: string; VAR Found: boolean): HResult;
VAR
pMoniker : IMoniker;
pPropertyBag : IPropertyBag;
v : OLEvariant;
cFetched : ulong;
MonName : string;
BEGIN
Found := false;
pMoniker := nil;
// Note that if the Next() call succeeds but there are no monikers,
// it will return S_FALSE (which is not a failure). Therefore, we
// check that the return code is S_OK instead of using SUCCEEDED() macro.
Result := pClassEnum.Next(1, pMoniker, @cFetched);
IF (S_OK = Result) THEN
BEGIN
Inc(Index);
pPropertyBag := nil;
Result := pMoniker.BindToStorage(nil, nil, IPropertyBag, pPropertyBag);
if S_OK = Result then
begin
Result := pPropertyBag.Read('FriendlyName', v, nil); // BTW: Other useful parameter: 'DevicePath'
if S_OK = Result then
begin
MonName := v;
if (Uppercase(Trim(MonName)) = UpperCase(Trim(Name))) or
((Length(Name)=2) and (Name[1]='#') and (ord(Name[2])-48=Index)) then
begin
DeviceSelected := Trim(MonName);
Result := pMoniker.BindToObject(nil, nil, IID_IBaseFilter, ppIBFVideoSource);
Found := Result = S_OK;
end;
end;
end;
END;
END; {CheckNextDeviceName}
BEGIN
DeviceSelected := '';
Index := 0;
DeviceName := Trim(DeviceName);
IF DeviceName = '' then
DeviceName := '#1'; // Default: First device (Erstes Gerät)
if @ppIBFVideoSource = nil then
begin
result := E_POINTER;
exit;
end;
// Create the system device enumerator
Result := CoCreateInstance(CLSID_SystemDeviceEnum,
nil,
CLSCTX_INPROC,
IID_ICreateDevEnum,
pDevEnum);
if (FAILED(Result)) then
begin
// Couldn't create system enumerator!
exit;
end;
// Create an enumerator for the video capture devices
pClassEnum := nil;
Result := pDevEnum.CreateClassEnumerator (CLSID_VideoInputDeviceCategory, pClassEnum, 0);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
begin
// Couldn't create class enumerator!
exit;
end;
// If there are no enumerators for the requested type, then
// CreateClassEnumerator will succeed, but pClassEnum will be nil.
if (pClassEnum = nil) then
begin
// No video capture device was detected.
result := E_FAIL;
exit;
end;
Found := false;
REPEAT
try
Result := CheckNextDeviceName(DeviceName, Found)
except
IF Result = 0 then
result := E_FAIL;
end;
UNTIL Found or (Result <> S_OK);
end; {ConnectToCaptureDevice}
procedure TVideoSample.ResizeVideoWindow();
var
rc : TRect;
begin
// Resize the video preview window to match owner window size
if (pIVideoWindow) <> nil then
begin
// Make the preview video fill our window
GetClientRect(ghApp, rc);
pIVideoWindow.SetWindowPosition(0, 0, rc.right, rc.bottom);
end;
end; {ResizeVideoWindow}
FUNCTION TVideoSample.SetupVideoWindow(): HRESULT;
BEGIN
// Set the video window to be a child of the main window
Result := pIVideoWindow.put_Owner(OAHWND(ghApp));
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
begin
exit;
end;
// Set video window style
Result := pIVideoWindow.put_WindowStyle(WS_CHILD or WS_CLIPCHILDREN);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
begin
exit;
end;
// Use helper function to position video window in client rect
// of main application window
ResizeVideoWindow();
// Make the video window visible, now that it is properly positioned
Result := pIVideoWindow.put_Visible(TRUE);
{$ifdef DXErr} DXErrString := DXGetErrorDescription9A(Result); {$endif}
if (FAILED(Result)) then
begin
exit;
end;
end; {SetupVideoWindow}
FUNCTION TVideoSample.RestartVideoEx(Visible: boolean):HRESULT;
VAR
pCut, pTyp : pGuiD;
{
pAMVidControl: IAMVideoControl;
pPin : IPin;
}
BEGIN
if (pIAMVideoProcAmp = nil) then
if not(S_OK = pIBFVideoSource.QueryInterface(IID_IAMVideoProcAmp, pIAMVideoProcAmp)) then
pIAMVideoProcAmp := nil;
if (pIKsPropertySet = nil) then
if not(S_OK = pIBFVideoSource.QueryInterface(IID_IKsPropertySet, pIKsPropertySet)) then
pIKsPropertySet := nil;
// Add Capture filter to our graph.
Result := pIGraphBuilder.AddFilter(pIBFVideoSource, Widestring('Video Capture'));
if (FAILED(Result)) then
begin
// Couldn''t add the capture filter to the graph!
exit;
end;
Result := pIGraphBuilder.AddFilter(piBFSampleGrabber, Widestring('Sample Grabber'));
if (FAILED(Result)) then
EXIT;
if not(Visible) then
begin
Result := pIGraphBuilder.AddFilter(pIBFNullRenderer, WideString('Null Renderer'));
if (FAILED(Result)) then
EXIT;
end;
// Render the preview pin on the video capture filter
// Use this instead of pIGraphBuilder->RenderFile
New(pCut);
New(pTyp);
//pCut^ := PIN_CATEGORY_PREVIEW;
pCut^ := PIN_CATEGORY_CAPTURE;
pTyp^ := MEDIATYPE_Video;
try
if Visible
then Result := pICapGraphBuild2.RenderStream (pCut, pTyp,
//Addr(PIN_CATEGORY_PREVIEW), Addr(MEDIATYPE_Video),
pIBFVideoSource, piBFSampleGrabber, nil)
else Result := pICapGraphBuild2.RenderStream (pCut, pTyp,
//Addr(PIN_CATEGORY_PREVIEW), Addr(MEDIATYPE_Video),
pIBFVideoSource, piBFSampleGrabber, pIBFNullRenderer);
except
Result := -1;
end;
if (FAILED(Result)) then
begin
// Couldn''t render the video capture stream.
// The capture device may already be in use by another application.
Dispose(pTyp);
Dispose(pCut);
exit;
end;
// Set video window style and position
if Visible then
begin
Result := SetupVideoWindow();
if (FAILED(Result)) then
begin
// Couldn't initialize video window!
Dispose(pTyp);
Dispose(pCut);
exit;
end;
end;
{$ifdef REGISTER_FILTERGRAPH}
// Add our graph to the running object table, which will allow
// the GraphEdit application to "spy" on our graph
try
hr := AddGraphToRot(IUnknown(pIGraphBuilder), g_dwGraphRegister);
except
// Failed to register filter graph with ROT!
end;
if (FAILED(Result)) then
begin
// Failed to register filter graph with ROT!
g_dwGraphRegister := 0;
end;
{$endif}
// if Visible then
begin
// Start previewing video data
Result := pIMediaControl.Run();
if (FAILED(Result)) then
begin
// Couldn't run the graph!
end;
end;
// Remember current state
g_psCurrent := PS_Running;
(*
// !!!!!!!!!
// Prepare getting images in higher resolution than video stream
// See DirectX9 Help "Capturing an Image From a Still Image Pin"
// Not working yet.....
pAMVidControl := nil;
Result := pIBFVideoSource.QueryInterface(IID_IAMVideoControl, pAMVidControl);
IF succeeded(Result) then
begin
pTyp := 0;
pPin := nil;
Result := pICapGraphBuild2.FindPin(pIBFVideoSource, PINDIR_OUTPUT, PIN_CATEGORY_STILL, pTyp^, false, 0, pPin);
if (SUCCEEDED(Result)) then
Result := pAMVidControl.SetMode(pPin, VideoControlFlag_Trigger);
end;
*)
Dispose(pTyp);
Dispose(pCut);
end; {RestartVideoEx}
FUNCTION TVideoSample.RestartVideo: HRESULT;
BEGIN
Result := RestartVideoEx(FVisible);
END; {RestartVideo}
FUNCTION TVideoSample.StartVideo(CaptureDeviceName: string; Visible: boolean; VAR DeviceSelected: string):HRESULT;
BEGIN
pIBFVideoSource := nil;
FVisible := Visible;
// Attach the filter graph to the capture graph
Result := pICapGraphBuild2.SetFiltergraph(pIGraphBuilder);
if (FAILED(Result)) then
begin
// Failed to set capture filter graph!
exit;
end;
// Use the system device enumerator and class enumerator to find
// a video capture/preview device, such as a desktop USB video camera.
Result := ConnectToCaptureDevice(CaptureDeviceName, DeviceSelected, pIBFVideoSource);
if (FAILED(Result)) then
begin
exit;
end;
LoadListOfResolution;
Result := RestartVideo;
end;
FUNCTION TVideoSample.PauseVideo: HResult;
BEGIN
IF g_psCurrent = PS_Paused
then begin
Result := S_OK;
EXIT;
end;
IF g_psCurrent = PS_Running then
begin
Result := pIMediaControl.Pause;
if Succeeded(Result) then
g_psCurrent := PS_Paused;
end
else Result := S_FALSE;
END;
FUNCTION TVideoSample.ResumeVideo: HResult;
BEGIN
IF g_psCurrent = PS_Running then
begin
Result := S_OK;
EXIT;
end;
IF g_psCurrent = PS_Paused then
begin
Result := pIMediaControl.Run;
if Succeeded(Result) then
g_psCurrent := PS_Running;
end
else Result := S_FALSE;
END;
FUNCTION TVideoSample.StopVideo: HResult;
BEGIN
// Stop previewing video data
Result := pIMediaControl.StopWhenReady();
g_psCurrent := PS_Stopped;
SetLength(FormatArr, 0);
END;
// Delete filter and pins bottom-up...
PROCEDURE TVideoSample.DeleteBelow(const IBF: IBaseFilter);
VAR
hr : HResult;
pins : IEnumPins;
pIPinFrom,
pIPinTo : IPin;
fetched : ulong;
pInfo : _PinInfo;
BEGIN
pIPinFrom := nil;
pIPinTo := nil;
hr := IBF.EnumPins(pins);
WHILE (hr = NoError) DO
BEGIN
hr := pins.Next(1, pIPinFrom, @fetched);
if (hr = S_OK) and (pIPinFrom <> nil) then
BEGIN
hr := pIPinFrom.ConnectedTo(pIPinTo);
if (hr = S_OK) and (pIPinTo <> nil) then
BEGIN
hr := pIPinTo.QueryPinInfo(pInfo);
if (hr = NoError) then
BEGIN
if pinfo.dir = PINDIR_INPUT then
BEGIN
DeleteBelow(pInfo.pFilter);
pIGraphBuilder.Disconnect(pIPinTo);
pIGraphBuilder.Disconnect(pIPinFrom);
pIGraphBuilder.RemoveFilter(pInfo.pFilter);
ENd;
END;
END;
END;
END;
END; {DeleteBelow}
PROCEDURE TVideoSample.DeleteCaptureGraph;
BEGIN
pIBFVideoSource.Stop;
DeleteBelow(pIBFVideoSource);
END;
procedure TVideoSample.CloseInterfaces;
begin
if (pISampleGrabber <> nil) then
pISampleGrabber.SetCallback(nil, 1);
// Stop previewing data
if (pIMediaControl <> nil) then
pIMediaControl.StopWhenReady();
g_psCurrent := PS_Stopped;
// Stop receiving events
if (pIMediaEventEx <> nil) then
pIMediaEventEx.SetNotifyWindow(OAHWND(nil), WM_GRAPHNOTIFY, 0);
// Relinquish ownership (IMPORTANT!) of the video window.
// Failing to call put_Owner can lead to assert failures within
// the video renderer, as it still assumes that it has a valid
// parent window.
if (pIVideoWindow<>nil) then
begin
pIVideoWindow.put_Visible(FALSE);
pIVideoWindow.put_Owner(OAHWND(nil));
end;
{$ifdef REGISTER_FILTERGRAPH}
// Remove filter graph from the running object table
if (g_dwGraphRegister<>nil) then
RemoveGraphFromRot(g_dwGraphRegister);
{$endif}
end;
function TVideoSample.GetImageBuffer(VAR pb : pbytearray; var Size: integer): HResult;
VAR
NewSize : integer;
begin
Result := pISampleGrabber.GetCurrentBuffer(NewSize, nil);
if (Result <> S_OK) then
EXIT;
if (pb <> nil) then
begin
if Size <> NewSize then
begin
try
FreeMem(pb, Size);
except
end;
pb := nil;
Size := 0;
end;
end;
Size := NewSize;
IF Result = S_OK THEN
BEGIN
if pb = nil then
GetMem(pb, NewSize);