-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
FMX.Media.Win.pas
1377 lines (1226 loc) · 40 KB
/
FMX.Media.Win.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
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2012-2023 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit FMX.Media.Win;
interface
{$SCOPEDENUMS ON}
uses
System.Win.ComObj, System.Variants, System.Classes, System.SysUtils, System.Math, System.Types, System.SyncObjs,
Winapi.Windows, Winapi.DirectShow9, Winapi.Direct3D9, Winapi.ActiveX, FMX.Context.DX9, FMX.Types, FMX.Types3D,
FMX.Forms, FMX.Media, FMX.Platform.Win, FMX.Graphics, FMX.Consts;
type
{ TWindowsCaptureDeviceManager }
TWindowsCaptureDeviceManager = class(TCaptureDeviceManager)
public
constructor Create; override;
destructor Destroy; override;
end;
{ TWindowsCaptureDevice }
TWindowsAudioCaptureDevice = class(TAudioCaptureDevice)
private
FMoniker: IMoniker;
FBaseFilter: IBaseFilter;
FGraphBuilder: IGraphBuilder;
FCaptureGraphBuilder: ICaptureGraphBuilder2;
FMediaControl: IMediaControl;
protected
procedure DoStartCapture; override;
procedure DoStopCapture; override;
function GetDeviceProperty(const Prop: TCaptureDevice.TProperty): string; override;
function GetDeviceState: TCaptureDeviceState; override;
function GetFilterString: string; override;
public
constructor Create(AManager: TCaptureDeviceManager; const AMoniker: IMoniker; const ADefault: Boolean); reintroduce;
destructor Destroy; override;
end;
{ TVMRRenderer }
TVMRRenderer = class(TInterfacedPersistent, IVMRSurfaceAllocator9, IVMRImagePresenter9)
private
FVideoTexture: IDirect3DTexture9; // must be RenderTarget to allow GPU copy
FSysMemSurface: IDirect3DSurface9;
FSurface: IDirect3DSurface9;
FSurfaceAllocatorNotify: IVMRSurfaceAllocatorNotify9;
FBaseFilter: IBaseFilter;
FVMRFilterConfig: IVMRFilterConfig9;
FSampleBufferReady: TSampleBufferReadyEvent;
FRunning: Boolean;
FIsSkipFrames: Boolean;
FRequestedBufferSize: TPoint;
FBufferLoadTime: TMediaTime;
FBufferLoaded: Boolean;
FIsFinishedProcessingEvent: TEvent;
{ IVMRSurfaceAllocator9 }
function InitializeDevice(dwUserID: DWORD; lpAllocInfo: PVMR9AllocationInfo;
var lpNumBuffers: DWORD): HResult; stdcall;
function TerminateDevice(dwID: DWORD): HResult; stdcall;
function GetSurface(dwUserID: DWORD; SurfaceIndex: DWORD; SurfaceFlags: DWORD;
out lplpSurface: IDirect3DSurface9): HResult; stdcall;
function AdviseNotify(lpIVMRSurfAllocNotify: IVMRSurfaceAllocatorNotify9): HResult; stdcall;
{ IVMRImagePresenter9 }
function StartPresenting(dwUserID: DWORD): HResult; stdcall;
function StopPresenting(dwUserID: DWORD): HResult; stdcall;
function PresentImage(dwUserID: DWORD; lpPresInfo: PVMR9PresentationInfo): HResult; stdcall;
{ }
function AddToGraph(const FGraphBuilder: IGraphBuilder): Boolean;
function LoadBufferToSystemMemory: Boolean;
procedure SampleBufferToBitmap(const ABitmap: TBitmap; const ASetSize: Boolean);
{ sync }
procedure Sync;
public
constructor Create;
destructor Destroy; override;
procedure SetSkipFrames;
end;
{ TWindowsCaptureDevice }
TWindowsVideoCaptureDevice = class(TVideoCaptureDevice)
private const
FrameDurationScale = 10000000;
private
FMoniker: IMoniker;
FBaseFilter: IBaseFilter;
FGraphBuilder: IGraphBuilder;
FCaptureGraphBuilder: ICaptureGraphBuilder2;
FMediaControl: IMediaControl;
FVMRRenderer: TVMRRenderer;
procedure VMRRendererSampleReady(Sender: TObject; const ATime: TMediaTime);
protected
procedure DoStartCapture; override;
procedure DoStopCapture; override;
procedure DoSampleBufferToBitmap(const ABitmap: TBitmap; const ASetSize: Boolean); override;
function GetDeviceProperty(const Prop: TCaptureDevice.TProperty): string; override;
function GetDeviceState: TCaptureDeviceState; override;
/// <summary>Inherited from TVideoCaptureDevice.</summary>
function GetCaptureSetting: TVideoCaptureSetting; override;
/// <summary>Inherited from TVideoCaptureDevice.</summary>
function DoSetCaptureSetting(const ASetting: TVideoCaptureSetting): Boolean; override;
/// <summary>Inherited from TVideoCaptureDevice.</summary>
function DoGetAvailableCaptureSettings: TArray<TVideoCaptureSetting>; override;
/// <summary>Inherited from TVideoCaptureDevice.</summary>
procedure DoSetQuality(const Value: TVideoCaptureQuality); override;
public
constructor Create(AManager: TCaptureDeviceManager; const AMoniker: IMoniker; const ADefault: Boolean); reintroduce;
destructor Destroy; override;
end;
{ TWindowsMedia }
TWindowsMedia = class(TMedia)
private
FGraphBuilder: IGraphBuilder;
FMediaControl: IMediaControl;
FMediaSeeking: IMediaSeeking;
FBasicAudio: IBasicAudio;
FVMR: IBaseFilter;
FVMRFilterConfig9: IVMRFilterConfig9;
FVMRWindowlessControl9: IVMRWindowlessControl9;
FVMRFilterConfig7: IVMRFilterConfig;
FVMRWindowlessControl7: IVMRWindowlessControl;
FWnd: HWND;
FWaitCompletionThread: TThread;
FMediaState: TMediaState;
{ Initialization }
procedure InitWnd;
procedure DestroyWnd;
function InitMediaControl: Boolean;
function InitGraphTree: Boolean;
function InitVideoMixingRenderer9: Boolean;
function LocateVideoMixingRenderer9: Boolean;
function InitVideoMixingRenderer7: Boolean;
function LocateVideoMixingRenderer7: Boolean;
{ Playback thread listener }
procedure StartWaitCompletionThread;
procedure StopAndFreeWaitCompletionThread;
procedure WaitCompletionThreadTerminated(Sender: TObject);
protected
function QueryInterface(const IID: TGUID; out Obj): HResult; override;
function GetDuration: TMediaTime; override;
function GetCurrent: TMediaTime; override;
procedure SetCurrent(const Value: TMediaTime); override;
function GetVideoSize: TPointF; override;
function GetMediaState: TMediaState; override;
function GetVolume: Single; override;
procedure SetVolume(const Value: Single); override;
procedure UpdateMediaFromControl; override;
procedure DoPlay; override;
procedure DoStop; override;
public
constructor Create(const AFileName: string); override;
destructor Destroy; override;
end;
/// <summary>This thread is waiting for completion of playback of a media file.</summary>
TWaitMediaCompletionThread = class(TThread)
private
FMediaEvent: IMediaEvent;
protected
procedure Execute; override;
public
constructor Create(const AMediaEvent: IMediaEvent);
end;
TWindowsMediaCodec = class(TCustomMediaCodec)
public
function CreateFromFile(const AFileName: string): TMedia; override;
end;
implementation
uses
System.RTLConsts, System.SysConst, System.Generics.Collections, Winapi.UrlMon;
const
MinAllowedVolume = -10000;
{ TWindowsCaptureDeviceManager }
constructor TWindowsCaptureDeviceManager.Create;
var
Moniker: IMoniker;
DevEnum: ICreateDevEnum;
Enum: IEnumMoniker;
Default: Boolean;
begin
inherited;
CoCreateInstance(CLSID_SystemDeviceEnum, nil, CLSCTX_INPROC_SERVER,
IID_ICreateDevEnum, DevEnum);
if DevEnum <> nil then
begin
// audio devices
Default := True;
DevEnum.CreateClassEnumerator(CLSID_AudioInputDeviceCategory, Enum, 0);
if Enum <> nil then
while (Enum.Next(1, Moniker, nil) = S_OK) do
begin
TWindowsAudioCaptureDevice.Create(Self, Moniker, Default);
Default := False;
end;
Enum := nil;
// video devices
Default := True;
DevEnum.CreateClassEnumerator(CLSID_VideoInputDeviceCategory, Enum, 0);
if Enum <> nil then
while (Enum.Next(1, Moniker, nil) = S_OK) do
begin
TWindowsVideoCaptureDevice.Create(Self, Moniker, Default);
Default := False;
end;
end;
end;
destructor TWindowsCaptureDeviceManager.Destroy;
begin
inherited;
end;
{ TWindowsAudioCaptureDevice }
constructor TWindowsAudioCaptureDevice.Create(AManager: TCaptureDeviceManager;
const AMoniker: IMoniker; const ADefault: Boolean);
begin
inherited Create(AManager, ADefault);
if AMoniker = nil then
raise EArgumentNilException.CreateResFmt(@SParamIsNil, ['AMoniker']);
FMoniker := AMoniker;
end;
destructor TWindowsAudioCaptureDevice.Destroy;
begin
inherited;
end;
procedure InitBaseFilter(const Self: TWindowsAudioCaptureDevice); forward; overload;
const //{3C78B8E2-6C4D-11d1-ADE2-0000F8754B99}
CLSID_WavDest: TGUID = '{8A667154-F9CB-11D2-AD8A-0060B0575ABC}';
procedure InitAudioFilter(const Self: TWindowsAudioCaptureDevice);
var
HR: HResult;
begin
if Self.FBaseFilter <> nil then
Exit;
HR := Self.FMoniker.BindToObject(nil, nil, IID_IBaseFilter, Self.FBaseFilter);
//HR := coCreateInstance(CLSID_WavDest, nil, CLSCTX_INPROC_SERVER, IID_IBaseFilter, Self.FBaseFilter);
if Failed(HR) then
raise ECaptureDeviceException.CreateRes(@SCannotCreateDirectShowCaptureFilter);
end;
procedure TWindowsAudioCaptureDevice.DoStartCapture;
var
HR: HResult;
ppf: IBaseFilter;
sink: IFileSinkfilter;
FailedToRun: Boolean;
begin
InitAudioFilter(Self);
FailedToRun := True;
// Create GraphBuilder
HR := CoCreateInstance(CLSID_CaptureGraphBuilder2, nil, CLSCTX_INPROC_SERVER,
IID_ICaptureGraphBuilder2, FCaptureGraphBuilder);
if Succeeded(HR) then
begin
HR := CoCreateInstance(CLSID_FilterGraph, nil, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, FGraphBuilder);
if Succeeded(HR) then
begin
FCaptureGraphBuilder.SetFiltergraph(FGraphBuilder);
// Get IMediaControl
FGraphBuilder.QueryInterface(IID_IMediaControl, FMediaControl);
HR := FGraphBuilder.AddFilter(FBaseFilter, 'Capture Filter');
if Succeeded(HR) then
begin
HR := FCaptureGraphBuilder.SetOutputFileName(MEDIASUBTYPE_WAVE, PChar(FFileName), ppf, sink);
if Succeeded(HR) then
begin
HR := FCaptureGraphBuilder.RenderStream(@PIN_CATEGORY_CAPTURE, @MEDIATYPE_Audio, FBaseFilter, nil, ppf);
if Succeeded(HR) then
begin
if FMediaControl <> nil then
begin
HR := FMediaControl.Run;
FailedToRun := Failed(HR);
if not FailedToRun then
Exit; // Success
end;
end;
end;
end;
end;
end;
FCaptureGraphBuilder := nil;
FGraphBuilder := nil;
FMediaControl := nil;
if FailedToRun then
raise ECaptureDeviceException.CreateRes(@SCannotRunDirectShowFilterGraph);
end;
procedure TWindowsAudioCaptureDevice.DoStopCapture;
begin
if FMediaControl <> nil then
begin
FMediaControl.StopWhenReady;
FCaptureGraphBuilder := nil;
FGraphBuilder := nil;
FMediaControl := nil;
end;
end;
function TWindowsAudioCaptureDevice.GetDeviceProperty(const Prop: TCaptureDevice.TProperty): string;
var
PropBag: IPropertyBag;
V: OleVariant;
begin
FMoniker.BindToStorage(nil, nil, IPropertyBag, PropBag);
if PropBag <> nil then
begin
case Prop of
TProperty.Description:
begin
PropBag.Read('Description', V, nil);
Result := V;
end;
TProperty.Name:
begin
PropBag.Read('FriendlyName', V, nil);
Result := V;
end;
TProperty.UniqueID:
begin
PropBag.Read('WaveInID', V, nil);
Result := V;
end;
else
Result := '';
end;
end
else
Result := '';
end;
function TWindowsAudioCaptureDevice.GetDeviceState: TCaptureDeviceState;
begin
if FMediaControl <> nil then
Result := TCaptureDeviceState.Capturing
else
Result := TCaptureDeviceState.Stopped;
end;
function TWindowsAudioCaptureDevice.GetFilterString: string;
begin
Result := SVWAVFiles + '(*.wav)|*.wav';
end;
procedure InitBaseFilter(const Self: TWindowsAudioCaptureDevice);
var
HR: HResult;
begin
if Self.FBaseFilter <> nil then
Exit;
HR := Self.FMoniker.BindToObject(nil, nil, IID_IBaseFilter, Self.FBaseFilter);
if Failed(HR) then
raise ECaptureDeviceException.CreateRes(@SCannotCreateDirectShowCaptureFilter);
end;
{ TVMRRenderer }
constructor TVMRRenderer.Create;
begin
inherited Create;
FIsFinishedProcessingEvent := TEvent.Create;
FIsFinishedProcessingEvent.SetEvent;
FIsSkipFrames := False;
end;
destructor TVMRRenderer.Destroy;
begin
FreeAndNil(FIsFinishedProcessingEvent);
FVideoTexture := nil;
FSysMemSurface := nil;
FSurfaceAllocatorNotify := nil;
FBaseFilter := nil;
FVMRFilterConfig := nil;
inherited;
end;
function TVMRRenderer.AddToGraph(const FGraphBuilder: IGraphBuilder): Boolean;
var
HR: HResult;
begin
// Create VMR
Result := True;
HR := CoCreateInstance(CLSID_VideoMixingRenderer9, nil, CLSCTX_INPROC, IID_IBaseFilter, FBaseFilter);
if Succeeded(HR) then
begin
FBaseFilter.QueryInterface(IVMRFilterConfig9, FVMRFilterConfig);
HR := FVMRFilterConfig.SetRenderingMode(VMR9Mode_Renderless);
if Succeeded(HR) then
begin
FBaseFilter.QueryInterface(IVMRSurfaceAllocatorNotify9, FSurfaceAllocatorNotify);
HR := FSurfaceAllocatorNotify.AdviseSurfaceAllocator(Cardinal(Self), Self);
if Succeeded(HR) then
begin
IVMRSurfaceAllocator9(Self).AdviseNotify(FSurfaceAllocatorNotify);
HR := FGraphBuilder.AddFilter(FBaseFilter, 'Video Mixing Renderer9');
if Succeeded(HR) then
Exit; // Success
end;
end;
end;
Result := False;
FVMRFilterConfig := nil;
FBaseFilter := nil;
end;
{ IVMRSurfaceAllocator9 }
function TVMRRenderer.GetSurface(dwUserID, SurfaceIndex, SurfaceFlags: DWORD; out lplpSurface: IDirect3DSurface9): HResult;
begin
if FSurface <> nil then
begin
lplpSurface := FSurface;
Result := S_OK;
end
else
Result := E_FAIL;
end;
function TVMRRenderer.InitializeDevice(dwUserID: DWORD; lpAllocInfo: PVMR9AllocationInfo; var lpNumBuffers: DWORD): HResult;
begin
Result := E_NOTIMPL;
if TCustomDX9Context.SharedDevice <> nil then
Result := FSurfaceAllocatorNotify.AllocateSurfaceHelper(lpAllocInfo, lpNumBuffers, FSurface);
end;
function TVMRRenderer.TerminateDevice(dwID: DWORD): HResult;
begin
FVideoTexture := nil;
FSysMemSurface := nil;
FSurface := nil;
Result := S_OK;
end;
function TVMRRenderer.AdviseNotify(lpIVMRSurfAllocNotify: IVMRSurfaceAllocatorNotify9): HResult;
begin
Result := E_NOTIMPL;
if TCustomDX9Context.SharedDevice <> nil then
Result := lpIVMRSurfAllocNotify.SetD3DDevice(TCustomDX9Context.SharedDevice, TCustomDX9Context.Direct3D9Obj.GetAdapterMonitor(D3DADAPTER_DEFAULT));
end;
{ IVMRImagePresenter9 }
function TVMRRenderer.StartPresenting(dwUserID: DWORD): HResult;
begin
Result := S_OK;
FRunning := True;
FRequestedBufferSize := TPoint.Zero;
FBufferLoaded := False;
end;
function TVMRRenderer.StopPresenting(dwUserID: DWORD): HResult;
begin
FRunning := False;
Result := S_OK;
end;
function TVMRRenderer.PresentImage(dwUserID: DWORD; lpPresInfo: PVMR9PresentationInfo): HResult;
begin
TMonitor.Enter(Self);
try
if FIsSkipFrames then
Exit(S_OK);
finally
TMonitor.Exit(Self);
end;
if FRunning and not FBufferLoaded then
begin
FIsFinishedProcessingEvent.ResetEvent;
try
if LoadBufferToSystemMemory then
begin
FBufferLoadTime := lpPresInfo.rtStart;
FBufferLoaded := True;
TThread.Synchronize(nil, Sync);
end;
finally
FIsFinishedProcessingEvent.SetEvent;
end;
end;
Result := S_OK;
end;
function TVMRRenderer.LoadBufferToSystemMemory: Boolean;
var
Device: IDirect3DDevice9;
Desc: TD3DSurfaceDesc;
CopyRect: TRect;
VideoSurface: IDirect3DSurface9;
begin
Result := False;
if (FSurface <> nil) and Succeeded(FSurface.GetDesc(Desc)) then
begin
Device := TCustomDX9Context.SharedDevice;
if not FRequestedBufferSize.IsZero then
CopyRect := TRect.Create(0, 0, FRequestedBufferSize.X, FRequestedBufferSize.Y)
else
CopyRect := TRect.Create(0, 0, Desc.Width, Desc.Height);
if (FVideoTexture = nil) or (Integer(Desc.Width) <> CopyRect.Width) or
(Integer(Desc.Height) <> CopyRect.Height) then
begin
FSysMemSurface := nil;
FVideoTexture := nil;
if Failed(Device.CreateTexture(CopyRect.Width, CopyRect.Height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8,
D3DPOOL_DEFAULT, FVideoTexture, nil)) then
Exit;
if Failed(Device.CreateOffscreenPlainSurface(CopyRect.Width, CopyRect.Height, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM,
FSysMemSurface, nil)) then
begin
FVideoTexture := nil;
Exit;
end;
end;
if Succeeded(FVideoTexture.GetSurfaceLevel(0, VideoSurface)) then
begin
if Failed(Device.StretchRect(FSurface, nil, VideoSurface, @CopyRect, D3DTEXF_LINEAR)) then
Exit;
Result := Succeeded(Device.GetRenderTargetData(VideoSurface, FSysMemSurface));
end;
end;
end;
procedure TVMRRenderer.SampleBufferToBitmap(const ABitmap: TBitmap; const ASetSize: Boolean);
procedure MoveResetAlpha(Source, Dest: Pointer; Count: Integer);
begin
while Count > 0 do
begin
PLongWord(Dest)^ := PLongWord(Source)^ or $FF000000;
Inc(NativeInt(Source), 4);
Inc(NativeInt(Dest), 4);
Dec(Count);
end;
end;
var
Desc: TD3DSurfaceDesc;
DescValid: Boolean;
Lock: TD3DLockedRect;
Map: TBitmapData;
I: Integer;
begin
if not ASetSize and ABitmap.IsEmpty then
raise EBitmapIncorrectSize.Create(SBitmapIncorrectSize);
if FSurface <> nil then
begin
if FVideoTexture <> nil then
DescValid := Succeeded(FVideoTexture.GetLevelDesc(0, Desc))
else
DescValid := Succeeded(FSurface.GetDesc(Desc));
if not DescValid then
raise EBitmapIncorrectSize.Create(SRetrieveSurfaceDescription);
if ASetSize then
begin
ABitmap.SetSize(Desc.Width, Desc.Height);
FRequestedBufferSize := TPoint.Zero;
end
else if (Integer(Desc.Width) <> ABitmap.Width) or (Integer(Desc.Height) <> ABitmap.Height) then
begin
FRequestedBufferSize := TPoint.Create(ABitmap.Width, ABitmap.Height);
// Buffer that was loaded previously has incorrect size, therefore it needs to be reloaded again here.
if not LoadBufferToSystemMemory then
raise ERetrieveSurfaceContents.Create(SRetrieveSurfaceContents);
end;
if Failed(FSysMemSurface.LockRect(Lock, nil, D3DLOCK_READONLY)) then
raise ERetrieveSurfaceContents.Create(SRetrieveSurfaceContents);
try
if not ABitmap.Map(TMapAccess.Write, Map) then
raise EAcquireBitmapAccess.Create(SAcquireBitmapAccess);
try
for I := 0 to ABitmap.Height - 1 do
MoveResetAlpha(Pointer(NativeInt(Lock.pBits) + Lock.Pitch * I), Map.GetScanline(I), Desc.Width);
finally
ABitmap.Unmap(Map);
end;
finally
FSysMemSurface.UnlockRect;
end;
end;
end;
procedure TVMRRenderer.SetSkipFrames;
begin
TMonitor.Enter(Self);
try
FIsSkipFrames := True;
finally
TMonitor.Exit(Self);
end;
// When we process camera frame we synchronize rendered frame with Main UI Thread and for this purpose
// we use TThread.Synchronize. When user stops camera, it uses synchronouse method IMediaControl.Stop,
// which blocks UI thread and as result main thread cannot make synchronization and we get dead lock.
// For avoiding it we need to invoke CheckSynchronize while current frame is processed.
while FRunning and (FIsFinishedProcessingEvent.WaitFor(20) = TWaitResult.wrTimeout) do
CheckSynchronize;
end;
procedure TVMRRenderer.Sync;
begin
if FBufferLoaded then
begin
if Assigned(FSampleBufferReady) then
FSampleBufferReady(Self, FBufferLoadTime);
FBufferLoaded := False;
end;
end;
{ TWindowsVideoCaptureDevice }
function PinMatchesCategory(APin: IPin; ACategory: TGuid): Boolean;
var
LSet: IKsPropertySet;
PinCategory: TGuid;
Value: DWORD;
LResult: HRESULT;
begin
Result := False;
if Supports(APin, IKsPropertySet, LSet) then
begin
LResult := LSet.Get(AMPROPSETID_Pin, AMPROPERTY_PIN_CATEGORY, nil, 0, PinCategory, SizeOf(TGuid), Value);
if Succeeded(LResult) and (Value = SizeOf(TGuid)) then
Result := (PinCategory = ACategory);
end;
end;
function GetStreamConfig(const APin: IPin): IAMStreamConfig;
begin
Supports(APin, IAMStreamConfig, Result);
end;
function GetCapturePin(const AFilter: IBaseFilter): IPin;
var
PinsEnum: IEnumPins;
Pin: IPin;
Config: IAMStreamConfig;
begin
Result := nil;
AFilter.EnumPins(PinsEnum);
if PinsEnum <> nil then
while PinsEnum.Next(1, Pin, nil) = S_OK do
if PinMatchesCategory(Pin, PIN_CATEGORY_CAPTURE) then
begin
if Supports(Pin, IAMStreamConfig, Config) then
Exit(Pin);
end;
end;
constructor TWindowsVideoCaptureDevice.Create(AManager: TCaptureDeviceManager;
const AMoniker: IMoniker; const ADefault: Boolean);
begin
inherited Create(AManager, ADefault);
if AMoniker = nil then
raise EArgumentNilException.CreateResFmt(@SParamIsNil, ['AMoniker']);
FMoniker := AMoniker;
end;
destructor TWindowsVideoCaptureDevice.Destroy;
begin
inherited;
end;
procedure InitBaseFilter(const Self: TWindowsVideoCaptureDevice); forward; overload;
procedure TWindowsVideoCaptureDevice.DoStartCapture;
var
HR: HResult;
FailedToRun: Boolean;
begin
InitBaseFilter(Self);
FailedToRun := False;
// Create GraphBuilder
HR := CoCreateInstance(CLSID_CaptureGraphBuilder2, nil, CLSCTX_INPROC_SERVER,
IID_ICaptureGraphBuilder2, FCaptureGraphBuilder);
if Succeeded(HR) then
begin
HR := CoCreateInstance(CLSID_FilterGraph, nil, CLSCTX_INPROC_SERVER, IID_IFilterGraph2, FGraphBuilder);
if Succeeded(HR) then
begin
FCaptureGraphBuilder.SetFiltergraph(FGraphBuilder);
// Get IMediaControl
FGraphBuilder.QueryInterface(IID_IMediaControl, FMediaControl);
// Set Capture
HR := FGraphBuilder.AddFilter(FBaseFilter, 'Capture');
if Succeeded(HR) then
begin
// Create VMR
FVMRRenderer := TVMRRenderer.Create;
FVMRRenderer.FSampleBufferReady := VMRRendererSampleReady;
FVMRRenderer.AddToGraph(FGraphBuilder);
// Start
HR := FCaptureGraphBuilder.RenderStream(@PIN_CATEGORY_CAPTURE, @MEDIATYPE_Video, FBaseFilter, nil, FVMRRenderer.FBaseFilter);
if Succeeded(HR) then
begin
if FMediaControl <> nil then
begin
HR := FMediaControl.Run;
FailedToRun := Failed(HR);
if not FailedToRun then
Exit; // Success
end;
end;
end;
end;
end;
FMediaControl := nil;
FCaptureGraphBuilder := nil;
FGraphBuilder := nil;
FreeAndNil(FVMRRenderer);
if FailedToRun then
raise ECaptureDeviceException.CreateRes(@SCannotRunDirectShowFilterGraph);
end;
procedure TWindowsVideoCaptureDevice.DoStopCapture;
begin
if (FMediaControl <> nil) then
begin
FVMRRenderer.SetSkipFrames;
FMediaControl.StopWhenReady;
FMediaControl := nil;
FCaptureGraphBuilder := nil;
FGraphBuilder := nil;
FreeAndNil(FVMRRenderer);
end;
end;
function TWindowsVideoCaptureDevice.DoGetAvailableCaptureSettings: TArray<TVideoCaptureSetting>;
var
MediaEnum: IEnumMediaTypes;
Pin: IPin;
MediaType: PAMMediaType;
OldMediaType: PAMMediaType;
MediaHeader: PVideoInfoHeader;
List: TList<TVideoCaptureSetting>;
Setting: TVideoCaptureSetting;
Config: IAMStreamConfig;
begin
InitBaseFilter(Self);
SetLength(Result, 0);
List := TList<TVideoCaptureSetting>.Create;
try
Pin := GetCapturePin(FBaseFilter);
if Pin <> nil then
begin
Config := GetStreamConfig(Pin);
Config.GetFormat(OldMediaType);
try
Config.SetFormat(nil);
Pin.EnumMediaTypes(MediaEnum);
if MediaEnum <> nil then
while MediaEnum.Next(1, MediaType, nil) = S_OK do
if (MediaType.formattype = FORMAT_VideoInfo) and (MediaType.cbFormat >= SizeOf(VIDEOINFOHEADER)) and
(MediaType.pbFormat <> nil) then
begin
MediaHeader := MediaType.pbFormat;
Setting.Width := MediaHeader.bmiHeader.biWidth;
Setting.Height := MediaHeader.bmiHeader.biHeight;
Setting.FrameRate := FrameDurationScale / MediaHeader.AvgTimePerFrame;
if not List.Contains(Setting) then
List.Add(Setting);
end;
finally
Config.SetFormat(OldMediaType);
end;
end;
Result := List.ToArray;
finally
List.Free;
end;
end;
function TWindowsVideoCaptureDevice.DoSetCaptureSetting(const ASetting: TVideoCaptureSetting): Boolean;
var
MediaEnum: IEnumMediaTypes;
Pin: IPin;
MediaType, SelectedMediaType: PAMMediaType;
MediaHeader: PVideoInfoHeader;
Found: Boolean;
Config: IAMStreamConfig;
DesiredAvgDuration: Double;
begin
InitBaseFilter(Self);
Found := False;
Result := False;
DesiredAvgDuration := FrameDurationScale / ASetting.FrameRate;
Pin := GetCapturePin(FBaseFilter);
if Pin <> nil then
begin
// We store the current configuration in order to reset it if there was any problem
Config := GetStreamConfig(Pin);
Config.GetFormat(SelectedMediaType);
try
Config.SetFormat(nil);
Pin.EnumMediaTypes(MediaEnum);
if MediaEnum <> nil then
while (Found = False) and (MediaEnum.Next(1, MediaType, nil) = S_OK) do
begin
if (MediaType.formattype = FORMAT_VideoInfo) and (MediaType.cbFormat >= SizeOf(VIDEOINFOHEADER)) and
(MediaType.pbFormat <> nil) then
begin
MediaHeader := MediaType.pbFormat;
if (MediaHeader.bmiHeader.biWidth = ASetting.Width) and (MediaHeader.bmiHeader.biHeight = ASetting.Height) and
(MediaHeader.AvgTimePerFrame = DesiredAvgDuration) then
begin
// As described in Direct Show, this is an estimation
Found := True;
SelectedMediaType := MediaType;
Break;
end;
end;
end;
finally
Result := Found and Succeeded(Config.SetFormat(SelectedMediaType));
end;
end;
end;
procedure TWindowsVideoCaptureDevice.DoSetQuality(const Value: TVideoCaptureQuality);
var
SettingsList: TArray<TVideoCaptureSetting>;
Priority: TVideoCaptureSettingPriority;
begin
if Value <> TVideoCaptureQuality.CaptureSettings then
begin
Priority := CaptureSettingPriority;
try
CaptureSettingPriority := TVideoCaptureSettingPriority.Resolution;
SettingsList := AvailableCaptureSettings;
finally
CaptureSettingPriority := Priority;
end;
if Length(SettingsList) > 0 then
begin
case Value of
TVideoCaptureQuality.PhotoQuality: CaptureSetting := SettingsList[0];
TVideoCaptureQuality.HighQuality: CaptureSetting := SettingsList[0];
TVideoCaptureQuality.MediumQuality: CaptureSetting := SettingsList[Length(SettingsList) div 2];
TVideoCaptureQuality.LowQuality: CaptureSetting := SettingsList[High(SettingsList)];
end;
end;
end;
inherited;
end;
function TWindowsVideoCaptureDevice.GetCaptureSetting: TVideoCaptureSetting;
var
PinsEnum: IEnumPins;
Pin: IPin;
MediaType: PAMMediaType;
MediaHeader: PVideoInfoHeader;
Config: IAMStreamConfig;
begin
InitBaseFilter(Self);
Result := TVideoCaptureSetting.Create;
FBaseFilter.EnumPins(PinsEnum);
if PinsEnum <> nil then
while (PinsEnum.Next(1, Pin, nil) = S_OK) and Supports(Pin, IAMStreamConfig, Config) do
begin
Config.GetFormat(MediaType);
MediaHeader := MediaType.pbFormat;
Exit(TVideoCaptureSetting.Create(MediaHeader.bmiHeader.biWidth, MediaHeader.bmiHeader.biHeight,
FrameDurationScale / MediaHeader.AvgTimePerFrame));
end;
end;
procedure TWindowsVideoCaptureDevice.DoSampleBufferToBitmap(const ABitmap: TBitmap; const ASetSize: Boolean);
begin
FVMRRenderer.SampleBufferToBitmap(ABitmap, ASetSize);
end;
function TWindowsVideoCaptureDevice.GetDeviceProperty(const Prop: TCaptureDevice.TProperty): string;
var
PropBag: IPropertyBag;
HR: HRESULT;
V: OleVariant;
begin
HR := FMoniker.BindToStorage(nil, nil, IPropertyBag, PropBag);
if Succeeded(HR) then
begin
case Prop of
TProperty.Description:
begin
PropBag.Read('Description', V, nil);
Result := V;
end;
TProperty.Name:
begin
PropBag.Read('FriendlyName', V, nil);
Result := V;
end;
TProperty.UniqueID:
begin
PropBag.Read('DevicePath', V, nil);
Result := V;
end;
else
Result := string.Empty;
end;
end
else
Result := string.Empty;
end;
function TWindowsVideoCaptureDevice.GetDeviceState: TCaptureDeviceState;
begin
if FMediaControl <> nil then
Result := TCaptureDeviceState.Capturing
else
Result := TCaptureDeviceState.Stopped;
end;
procedure TWindowsVideoCaptureDevice.VMRRendererSampleReady(Sender: TObject; const ATime: TMediaTime);
begin
SampleBufferReady(ATime);
end;
procedure InitBaseFilter(const Self: TWindowsVideoCaptureDevice);
var
HR: HResult;
begin
if Self.FBaseFilter <> nil then
Exit;
HR := Self.FMoniker.BindToObject(nil, nil, IID_IBaseFilter, Self.FBaseFilter);
if Failed(HR) then
raise ECaptureDeviceException.CreateRes(@SCannotCreateDirectShowCaptureFilter);
end;
{ TWindowsMedia }
constructor TWindowsMedia.Create(const AFileName: string);
begin
if (not FileExists(AFileName)) and (IsValidURL(nil, PChar(AFileName), 0) <> S_OK) then
raise EFileNotFoundException.Create(SFileNotFound);
inherited;
FMediaState := TMediaState.Unavailable;
InitWnd;
if InitMediaControl and InitVideoMixingRenderer9 then
begin
if not LocateVideoMixingRenderer9 then