/
VMR9.cs
2393 lines (2170 loc) · 84.8 KB
/
VMR9.cs
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
#region Copyright (C) 2005-2011 Team MediaPortal
// Copyright (C) 2005-2011 Team MediaPortal
// http://www.team-mediaportal.com
//
// MediaPortal 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 2 of the License, or
// (at your option) any later version.
//
// MediaPortal 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 MediaPortal. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using DirectShowLib;
using DShowNET.Helper;
using MediaPortal.Configuration;
using MediaPortal.ExtensionMethods;
using MediaPortal.GUI.Library;
using MediaPortal.Player.LAV;
using MediaPortal.Profile;
using MediaPortal.Util;
using Microsoft.DirectX.Direct3D;
using Action = MediaPortal.GUI.Library.Action;
using Filter = Microsoft.DirectX.Direct3D.Filter;
using Geometry = MediaPortal.GUI.Library.Geometry;
namespace MediaPortal.Player
{
/// <summary>
/// General helper class to add the Video Mixing Render9 filter to a graph
/// , set it to renderless mode and provide it our own allocator/presentor
/// This will allow us to render the video to a direct3d texture
/// which we can use to draw the transparent OSD on top of it
/// Some classes which work together:
/// VMR9Util : general helper class
/// AllocatorWrapper.cs : implements our own allocator/presentor for vmr9 by implementing
/// IVMRSurfaceAllocator9 and IVMRImagePresenter9
/// PlaneScene.cs : class which draws the video texture onscreen and mixes it with the GUI, OSD,...
/// </summary>
/// // {324FAA1F-7DA6-4778-833B-3993D8FF4151}
#region IVMR9PresentCallback interface
[ComVisible(true), ComImport,
Guid("324FAA1F-7DA6-4778-833B-3993D8FF4151"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMR9PresentCallback
{
[PreserveSig]
int PresentImage(Int16 cx, Int16 cy, Int16 arx, Int16 ary, uint pImage, uint pTexture);
//called by EVR presenter, before sample is rendered
//used to synchronize subtitle's clock
[PreserveSig]
void SetSampleTime(Int64 nsSampleTime);
[PreserveSig]
int RenderGui(Int16 cx, Int16 cy, Int16 arx, Int16 ary);
[PreserveSig]
int RenderOverlay(Int16 cx, Int16 cy, Int16 arx, Int16 ary);
[PreserveSig]
void SetRenderTarget(IntPtr target);
[PreserveSig]
void SetSubtitleDevice(IntPtr device);
[PreserveSig]
void RenderSubtitle(long frameStart, int left, int top, int right, int bottom, int width, int height, int xOffsetInPixels);
[PreserveSig]
void RenderSubtitleEx(long frameStart, Rectangle viewportRect, Rectangle croppedVideoRect, int xOffsetInPixels);
[PreserveSig]
void RenderFrame(Int16 cx, Int16 cy, Int16 arx, Int16 ary, IntPtr pSurface);
[PreserveSig]
void GrabMadVrScreenshot(IntPtr pTargetmadVrDib);
[PreserveSig]
void GrabMadVrFrame(IntPtr pTargetmadVrDib);
[PreserveSig]
void GrabMadVrCurrentFrame(IntPtr pTargetmadVrDib);
[PreserveSig]
void ForceOsdUpdate(bool pForce);
[PreserveSig]
bool IsFullScreen();
[PreserveSig]
bool IsUiVisible();
[PreserveSig]
void RestoreDeviceSurface(IntPtr pSurfaceDevice);
[PreserveSig]
int ReduceMadvrFrame();
[PreserveSig]
void DestroyHWnd(uint phWnd);
}
#endregion
public class VMR9Util : IDisposable
{
#region imports
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern unsafe bool Vmr9Init(IVMR9PresentCallback callback, uint dwD3DDevice, IBaseFilter vmr9Filter,
uint monitor);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern unsafe void Vmr9Deinit();
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern unsafe void Vmr9SetDeinterlaceMode(Int16 mode);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern unsafe void Vmr9SetDeinterlacePrefs(uint dwMethod);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern unsafe bool EvrInit(IVMR9PresentCallback callback, uint dwD3DDevice,
ref IBaseFilter vmr9Filter, uint monitor, int monitorIdx,
bool disVsyncCorr, bool disMparCorr);
//, uint dwWindow);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern unsafe void EvrDeinit();
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern unsafe void EVRDrawStats(bool enable);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern unsafe void EVRResetStatCounters();
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern unsafe void EVRNotifyRateChange(double pRate);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern unsafe void EVRNotifyDVDMenuState(bool pIsInMenu);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern unsafe double EVRGetVideoFPS(int fpsSource);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern unsafe void EVRUpdateDisplayFPS();
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int MadInit(IVMR9PresentCallback callback, int xposition, int yposition,
int width, int height, uint dwD3DDevice, uint parent,
ref IBaseFilter madFilter, IGraphBuilder mPGraphbuilder);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void MadDeinit(bool releasedFilter);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void MadStopping();
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void MadVrPaused(bool paused);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void MadVrRepeatFrameSend();
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void MadVrGrabFrameSend();
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void MadVrGrabCurrentFrameSend();
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void MadVrGrabScreenshotSend();
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void MadVrWindowPosition();
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void MadVr3DRight(int x, int y, int width, int height);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void MadVr3DLeft(int x, int y, int width, int height);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void MadVr3DEnable(bool Enable);
[DllImport("dshowhelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void MadVrScreenResizeForce(int x, int y, int width, int height, bool displayChange);
[DllImport("user32.dll")]
static extern bool DestroyWindow(IntPtr hWnd);
#endregion
#region static vars
public static VMR9Util g_vmr9 = null;
private static int _instanceCounter = 0;
public static readonly AutoResetEvent finished = new AutoResetEvent(false);
#endregion
#region enums
private enum Vmr9PlayState
{
Playing,
Repaint
}
#endregion
#region vars
internal PlaneScene _scene = null;
private bool _useVmr9 = false;
private bool _inMadVrExclusiveMode = false;
private bool _inMenu = false;
private IRender _renderFrame;
internal IBaseFilter _vmr9Filter = null;
private int _videoHeight, _videoWidth;
private int _videoAspectRatioX, _videoAspectRatioY;
private IQualProp _qualityInterface = null;
private int _frameCounter = 0;
private DateTime _repaintTimer = DateTime.Now;
private IVMRMixerBitmap9 _vmr9MixerBitmapInterface = null;
private IGraphBuilder _graphBuilder = null;
private bool _isVmr9Initialized = false;
private bool _isCurrentStopping = false;
private int _threadId;
private Vmr9PlayState currentVmr9State = Vmr9PlayState.Playing;
private string pixelAdaptive = "";
private string verticalStretch = "";
private string medianFiltering = "";
private int _freeframeCounter = 0;
protected bool UseMadVideoRenderer; // is madVR used?
protected bool UseEVRMadVRForTV;
protected bool UseMadVideoRenderer3D;
protected bool UseEnhancedVideoRenderer;
protected bool NoAudioResetCheckBox;
protected internal DateTime playbackTimer;
protected internal DateTime PlaneSceneMadvrTimer = new DateTime(0);
protected IVideoWindow videoWinMadVr;
internal readonly object _syncRoot = new Object();
internal bool _exitThread = false;
#endregion
#region ctor
/// <summary>
/// Constructor
/// </summary>
public VMR9Util()
{
_useVmr9 = true;
if (!GUIGraphicsContext.VMR9Allowed)
{
Log.Info("VMR9: ctor() - VMR9 not allowed");
_useVmr9 = false;
return;
}
_renderFrame = GUIGraphicsContext.RenderGUI;
if (GUIGraphicsContext.DX9Device == null)
{
_useVmr9 = false;
Log.Warn("VMR9: ctor() - DX9Device == null!");
}
if (_renderFrame == null)
{
_useVmr9 = false;
Log.Debug("VMR9: ctor() _renderFrame == null");
}
if (g_vmr9 != null || (GUIGraphicsContext.Vmr9Active && GUIGraphicsContext.Vmr9ActivePlaylist))
{
_useVmr9 = false;
Log.Info("VMR9: ctor() VMR9 already active");
}
}
#endregion
#region properties
public bool UseVmr9
{
get { return _useVmr9; }
}
public bool InMadVrExclusiveMode
{
get
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
_inMadVrExclusiveMode = MadvrInterface.InExclusiveMode(_vmr9Filter);
Log.Debug("VMR9 : madVR InExclusiveMode {0}", _inMadVrExclusiveMode);
return _inMadVrExclusiveMode;
}
return _inMadVrExclusiveMode;
}
}
public int FrameCounter
{
get { return _frameCounter; }
set { _frameCounter = value; }
}
public int FreeFrameCounter
{
get { return _freeframeCounter; }
set { _freeframeCounter = value; }
}
public bool InMenu
{
get { return _inMenu; }
}
/// <summary>
/// returns the width of the video
/// </summary>
public int VideoWidth
{
get { return _videoWidth; }
set { _videoWidth = value; }
}
/// <summary>
/// returns the height of the video
/// </summary>
public int VideoHeight
{
get { return _videoHeight; }
set { _videoHeight = value; }
}
/// <summary>
/// returns the width of the video
/// </summary>
public int VideoAspectRatioX
{
get { return _videoAspectRatioX; }
set { _videoAspectRatioX = value; }
}
/// <summary>
/// returns the height of the video
/// </summary>
public int VideoAspectRatioY
{
get { return _videoAspectRatioY; }
set { _videoAspectRatioY = value; }
}
public IPin PinConnectedTo
{
get
{
if (!_isVmr9Initialized)
{
return null;
}
if (_vmr9Filter == null || !_useVmr9)
{
return null;
}
IPin pinIn, pinConnected;
pinIn = DsFindPin.ByDirection(_vmr9Filter, PinDirection.Input, 0);
if (pinIn == null)
{
//no input pin found, vmr9 is not possible
return null;
}
pinIn.ConnectedTo(out pinConnected);
DirectShowUtil.ReleaseComObject(pinIn);
return pinConnected;
}
}
public IPin PinConnectedInput
{
get
{
if (!_isVmr9Initialized)
{
return null;
}
if (_vmr9Filter == null || !_useVmr9)
{
return null;
}
var pinIn = DsFindPin.ByDirection(_vmr9Filter, PinDirection.Input, 0);
if (pinIn == null)
{
//no input pin found, vmr9 is not possible
return null;
}
return pinIn;
}
}
/// <summary>
/// This method returns true if VMR9 is enabled AND WORKING!
/// this allows players to check if if VMR9 is working after setting up the playing graph
/// by checking if VMR9 is possible they can for example fallback to the overlay device
/// </summary>
public bool IsVMR9Connected
{
get
{
if (!_isVmr9Initialized)
{
return false;
}
// check if vmr9 is enabled and if initialized
if (_vmr9Filter == null || !_useVmr9)
{
Log.Warn("VMR9: Not used or no filter:{0} {1:x}", _useVmr9, _vmr9Filter);
return false;
}
int hr = 0;
//get the VMR9 input pin#0 is connected
for (int i = 0; i < 3; ++i)
{
IPin pinIn, pinConnected;
pinIn = DsFindPin.ByDirection(_vmr9Filter, PinDirection.Input, i);
if (pinIn == null)
{
//no input pin found, vmr9 is not possible
Log.Warn("VMR9: No input pin {0} found", i);
continue;
}
//check if the input is connected to a video decoder
hr = pinIn.ConnectedTo(out pinConnected);
if (pinConnected == null)
{
//no pin is not connected so vmr9 is not possible
Log.Warn("VMR9: Pin: {0} not connected: {1:x}", i, hr);
}
else
{
//Log.Info("vmr9: pin:{0} is connected",i);
if (pinIn != null)
{
DirectShowUtil.ReleaseComObject(pinIn);
}
if (pinConnected != null)
{
DirectShowUtil.ReleaseComObject(pinConnected);
}
return true;
}
if (pinIn != null)
{
DirectShowUtil.ReleaseComObject(pinIn);
}
if (pinConnected != null)
{
DirectShowUtil.ReleaseComObject(pinConnected);
}
}
return false;
} //get {
}
public bool DisableLowLatencyMode
{
get { return _scene != null && _scene.DisableLowLatencyMode; }
set { if (_scene != null) _scene.DisableLowLatencyMode = value; }
}
public bool Visible
{
get { return _scene != null && _scene.Visible; }
set { if (_scene != null) _scene.Visible = value; }
}
public void SceneMadVr()
{
if (_scene != null)
{
Size nativeSize = new Size(3, 3);
_scene.SetVideoWindow(nativeSize);
}
}
public IBaseFilter Vmr9Filter
{
get { return _vmr9Filter; }
}
//public bool IsVMR9Connected
public bool isCurrentStopping
{
get { return _isCurrentStopping; }
}
#endregion
#region public members
/// <summary>
/// Restore original refresh rate for madVR
/// </summary>
public void RestoreDisplayModeNow()
{
Log.Debug("VMR9: Restore DisplayMode Now for madVR");
if (VMR9Util.g_vmr9 != null)
{
if (_vmr9Filter != null) MadvrInterface.restoreDisplayModeNow(_vmr9Filter);
}
}
/// <summary>
/// Register madVR WindowsMessageMP
/// </summary>
public void WindowsMessageMp()
{
// Needed to enable 3D (TODO why is needed ?)
Log.Debug("VMR9: Delayed OSD Callback");
RegisterOsd();
if (VMR9Util.g_vmr9 != null) VMR9Util.g_vmr9.SetMpFullscreenWindow();
}
/// <summary>
/// Register madVR StartMadVrPaused
/// </summary>
public void StartMadVrPaused()
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
MadVrPaused(g_Player.Paused);
}
}
/// <summary>
/// Send call to repeat frame for madVR
/// </summary>
public void MadVrRepeatFrame()
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
MadVrRepeatFrameSend();
}
}
/// <summary>
/// Send call to grabbing screenshot for madVR
/// </summary>
public void MadVrGrabScreenshot()
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
MadVrGrabScreenshotSend();
}
}
///// <summary>
///// Send call to grabbing frame for madVR
///// </summary>
//public void MadVrGrabFrame()
//{
// if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
// {
// MadVrGrabFrameSend();
// }
//}
/// <summary>
/// Send call to grabbing current frame for madVR
/// </summary>
public void MadVrGrabCurrentFrame()
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
MadVrGrabCurrentFrameSend();
}
}
/// <summary>
/// Send call to set madVR window position
/// </summary>
public void IniMadVrWindowPosition()
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
Log.Debug("VMR9 : madVR reposition window");
MadVrWindowPosition();
}
}
/// <summary>
/// Grabe Frame madVR
/// </summary>
public void GrabScreenshotThreaded()
{
Thread ActivateThemeThread = new Thread(new ThreadStart(GrabScreenshot));
ActivateThemeThread.Name = "Grab screenshot in thread";
ActivateThemeThread.IsBackground = true;
ActivateThemeThread.Priority = ThreadPriority.Normal;
ActivateThemeThread.Start();
}
/// <summary>
/// Grabe Frame madVR
/// </summary>
public void GrabScreenshot()
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
IntPtr pTargetmadVrDib = IntPtr.Zero;
try
{
if (_graphBuilder != null)
{
string directory = string.Format("{0}\\MediaPortal Screenshots\\{1:0000}-{2:00}-{3:00}",
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
if (!Directory.Exists(directory))
{
Log.Info("Main: Taking screenshot - Creating directory: {0}", directory);
Directory.CreateDirectory(directory);
}
string fileName = string.Format("{0}\\madVR - {1:00}-{2:00}-{3:00}", directory, DateTime.Now.Hour,
DateTime.Now.Minute, DateTime.Now.Second);
// First take the buffersize
var basicVideo = _vmr9Filter as IBasicVideo;
int buffersize = 0;
basicVideo?.GetCurrentImage(ref buffersize, IntPtr.Zero);
// Allocate memory
pTargetmadVrDib = Win32API.GlobalLock(Marshal.AllocHGlobal(buffersize));
// Take the pointer
basicVideo?.GetCurrentImage(ref buffersize, pTargetmadVrDib);
Log.Debug("VMR9 : madVR grabbing image window");
// Save screenshot from DIB
IntPtr pdib = pTargetmadVrDib;
Win32API.BITMAPINFOHEADER bmih =
(Win32API.BITMAPINFOHEADER) Marshal.PtrToStructure(pdib, typeof (Win32API.BITMAPINFOHEADER));
IntPtr pixels = IntPtr.Add(pdib, bmih.biSize);
Bitmap tmpBmp = new Bitmap(bmih.biWidth, bmih.biHeight, bmih.biWidth*4, PixelFormat.Format32bppRgb, pixels);
Bitmap result = new Bitmap(tmpBmp);
result.RotateFlip(RotateFlipType.RotateNoneFlipY);
result.Save(fileName + ".jpg", ImageFormat.Jpeg);
result.Dispose();
tmpBmp.Dispose();
}
}
catch
{
Marshal.FreeHGlobal(pTargetmadVrDib);
Log.Info("VMR9 : madVR grabbing image window failed");
}
finally
{
Win32API.LocalFree(pTargetmadVrDib);
pTargetmadVrDib = IntPtr.Zero;
}
}
}
/// <summary>
/// Grabe Frame madVR
/// Needed to be used on MP main thread
/// </summary>
public void GrabCurrentFrame()
{
lock (this)
{
IntPtr pTargetmadVrDib = IntPtr.Zero;
try
{
// Send the DIB to C#
if (GUIGraphicsContext.madVRCurrentFrameBitmap != null)
{
GUIGraphicsContext.madVRCurrentFrameBitmap.Dispose();
GUIGraphicsContext.madVRCurrentFrameBitmap = null;
}
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
if (pTargetmadVrDib != IntPtr.Zero)
{
Win32API.LocalFree(pTargetmadVrDib);
pTargetmadVrDib = IntPtr.Zero;
}
IMadVRFrameGrabber pMadVrFrame = _vmr9Filter as IMadVRFrameGrabber;
pMadVrFrame?.GrabFrame(MadvrInterface.ZOOM_ENCODED_SIZE,
MadvrInterface.FLAGS_NO_SUBTITLES | MadvrInterface.FLAGS_NO_ARTIFACT_REMOVAL |
MadvrInterface.FLAGS_NO_IMAGE_ENHANCEMENTS | MadvrInterface.FLAGS_NO_UPSCALING_REFINEMENTS |
MadvrInterface.FLAGS_NO_HDR_SDR_CONVERSION,
MadvrInterface.CHROMA_UPSCALING_NGU_AA, MadvrInterface.IMAGE_DOWNSCALING_SSIM1D100,
MadvrInterface.IMAGE_UPSCALING_NGU_SHARP_GRAIN, 0, out pTargetmadVrDib,
IntPtr.Zero);
// Convert DIB to Bitmap
// pTargetmadVrDib is a DIB
if (pTargetmadVrDib != IntPtr.Zero)
{
Win32API.BITMAPINFOHEADER bmih =
(Win32API.BITMAPINFOHEADER) Marshal.PtrToStructure(pTargetmadVrDib, typeof (Win32API.BITMAPINFOHEADER));
IntPtr pixels = IntPtr.Add(pTargetmadVrDib, bmih.biSize);
using (
Bitmap b = new Bitmap(bmih.biWidth, bmih.biHeight, bmih.biWidth*4, PixelFormat.Format32bppRgb, pixels))
{
GUIGraphicsContext.madVRCurrentFrameBitmap = new Bitmap(b);
GUIGraphicsContext.madVRCurrentFrameBitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
// IMPORTANT: Closes and disposes the stream
// If this is not done we get a memory leak!
b.Dispose();
}
}
}
}
catch (Exception ex)
{
Marshal.FreeHGlobal(pTargetmadVrDib);
Log.Info("VMR9 : madVR grabbing current frame failed");
}
}
}
/// <summary>
/// Send Right 3D for madVR
/// </summary>
public void MadVr3DSizeRight(int x, int y, int width, int height)
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
MadVr3DRight(x, y, width, height);
}
}
/// <summary>
/// Send Left 3D for madVR
/// </summary>
public void MadVr3DSizeLeft(int x, int y, int width, int height)
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
MadVr3DLeft(x, y, width, height);
}
}
/// <summary>
/// Send 3D enable for madVR
/// </summary>
public void MadVr3DOnOff(bool Enable)
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
MadVr3DEnable(Enable);
}
}
/// <summary>
/// Send screen resize for madVR
/// </summary>
public void MadVrScreenResize(int x, int y, int width, int height, bool displayChange)
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
MadVrScreenResizeForce(x, y, width, height, displayChange);
Log.Debug("VMR9: MadVrScreenResizeForce : X: {0}, Y: {1},Width: {2},Height: {3}", x, y, width, height);
}
}
/// <summary>
/// Register madVR OSD callback
/// </summary>
public void RegisterOsd()
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
if (UseMadVideoRenderer3D && !g_Player.IsTimeShifting)
{
// Sending message to force unfocus/focus for 3D.
var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_UNFOCUS_FOCUS, 0, 0, 0, 0, 0, null);
GUIWindowManager.SendThreadMessage(msg);
Log.Debug("VMR9: send message for madVR refresh force");
}
}
}
/// <summary>
/// Set MP Window for madVR when using 3D Trick
/// </summary>
public void SetMpFullscreenWindow()
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
if (UseMadVideoRenderer3D)
{
try
{
// Sending message to force unfocus/focus for 3D.
IVideoWindow videoWin = _vmr9Filter as IVideoWindow;
if (videoWin != null)
{
videoWin.put_Owner(GUIGraphicsContext.MadVrHWnd != IntPtr.Zero // TODO
? GUIGraphicsContext.MadVrHWnd
: GUIGraphicsContext.form.Handle);
videoWin.put_WindowStyle((WindowStyle) ((int) WindowStyle.Child + (int) WindowStyle.ClipChildren + (int) WindowStyle.ClipSiblings));
videoWin.put_MessageDrain(GUIGraphicsContext.MadVrHWnd != IntPtr.Zero
? GUIGraphicsContext.MadVrHWnd
: GUIGraphicsContext.form.Handle);
}
UseMadVideoRenderer3D = false;
}
catch (Exception)
{
UseMadVideoRenderer3D = false;
}
Log.Debug("VMR9: madVR SetMpFullscreenWindow()");
}
}
}
public void ShutdownMadVr()
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
Log.Debug("VMR9: ShutdownMadVr() 1");
bool releasedFilter = false;
try
{
if (_vmr9Filter != null)
{
IPin outpout;
_vmr9Filter.FindPin("video", out outpout);
DirectShowUtil.ReleaseComObject(outpout);
}
}
catch (Exception)
{
// filter already released
releasedFilter = true;
_vmr9Filter = null;
}
MadDeinit(releasedFilter);
GUIGraphicsContext.MadVrStop = false;
VMR9Util.finished.Set();
Log.Debug("VMR9: ShutdownMadVr() 2");
}
}
/// <summary>
/// Add VMR9 filter to graph and configure it
/// </summary>
/// <param name="graphBuilder"></param>
public bool AddVMR9(IGraphBuilder graphBuilder)
{
try
{
// Read settings
using (Settings xmlreader = new MPSettings())
{
UseMadVideoRenderer = xmlreader.GetValueAsBool("general", "useMadVideoRenderer", false);
UseEVRMadVRForTV = xmlreader.GetValueAsBool("general", "useEVRMadVRForTV", false);
UseMadVideoRenderer3D = xmlreader.GetValueAsBool("general", "useMadVideoRenderer3D", false);
UseEnhancedVideoRenderer = xmlreader.GetValueAsBool("general", "useEVRenderer", false);
NoAudioResetCheckBox = xmlreader.GetValueAsBool("audiodelay", "noaudioresetzero", false);
}
Log.Debug("VMR9: addvmr9 - thread : {0}", Thread.CurrentThread.Name);
if (!_useVmr9)
{
Log.Debug("VMR9: addvmr9 - vmr9 is deactivated");
return false;
}
if (_isVmr9Initialized)
{
Log.Debug("VMR9: addvmr9: vmr9 has already been initialized");
return false;
}
if (_instanceCounter != 0)
{
Log.Error("VMR9: Multiple instances of VMR9 running!!!");
throw new Exception("VMR9Helper: Multiple instances of VMR9 running!!!");
}
HResult hr;
IntPtr hMonitor = Manager.GetAdapterMonitor(GUIGraphicsContext.DX9Device.DeviceCaps.AdapterOrdinal);
IntPtr upDevice = DirectShowUtil.GetUnmanagedDevice(GUIGraphicsContext.DX9Device);
_scene = new PlaneScene(this);
// Check if need to set EVR for LiveTV when using madVR
if (UseMadVideoRenderer)
{
if (UseEVRMadVRForTV && g_Player.IsTimeShifting)
{
GUIGraphicsContext.VideoRenderer = GUIGraphicsContext.VideoRendererType.EVR;
// Keep current RenderTarget to trying to restore D3D GUI from madVR but release it if already init previously
if (GUIGraphicsContext.MadVrRenderTargetVmr9 != null && !GUIGraphicsContext.MadVrRenderTargetVmr9.Disposed)
{
GUIGraphicsContext.DX9Device?.SetRenderTarget(0, GUIGraphicsContext.MadVrRenderTargetVmr9);
GUIGraphicsContext.MadVrRenderTargetVmr9.Dispose();
GUIGraphicsContext.MadVrRenderTargetVmr9 = null;
}
}
else
{
GUIGraphicsContext.VideoRenderer = GUIGraphicsContext.VideoRendererType.madVR;
}
}
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
// Render Blank screen to avoid old GUI Window displayed on stop.
GUIGraphicsContext.BlankScreen = true;
// Process frames to clear D3D dialog window
for (int i = 0; i < 20; i++)
{
GUIWindowManager.MadVrProcess();
}
// Keep current RenderTarget to trying to restore D3D GUI from madVR but release it if already init previously
if (GUIGraphicsContext.MadVrRenderTargetVmr9 != null && !GUIGraphicsContext.MadVrRenderTargetVmr9.Disposed)
{
GUIGraphicsContext.DX9Device?.SetRenderTarget(0, GUIGraphicsContext.MadVrRenderTargetVmr9);
GUIGraphicsContext.MadVrRenderTargetVmr9.Dispose();
GUIGraphicsContext.MadVrRenderTargetVmr9 = null;
}
// Send action message to refresh screen
var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_MADVR_SCREEN_REFRESH, 0, 0, 0, 0, 0, GUIGraphicsContext.DX9Device.GetRenderTarget(0))
{
Param1 = 1 // Adding VMR9
};
GUIWindowManager.SendThreadMessage(msg);
}
_scene.Init();
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.EVR)
{
// Fix RDP Screen out of bound (force to use AdapterOrdinal to 0 if adapter number are out of bounds)
int adapterOrdinal = GUIGraphicsContext.DX9Device.DeviceCaps.AdapterOrdinal;
if (adapterOrdinal >= Screen.AllScreens.Length)
{
adapterOrdinal = Screen.AllScreens.Length - 1;
Log.Info("VMR9: adapter number out of bounds");
}
if (GUIGraphicsContext.currentMonitorIdx != -1)
{
if ((OSInfo.OSInfo.Win7OrLater() &&
Screen.AllScreens[adapterOrdinal].Primary) || OSInfo.OSInfo.Win8OrLater())
{
EvrInit(_scene, (uint) upDevice.ToInt32(), ref _vmr9Filter, (uint) hMonitor.ToInt32(),
GUIGraphicsContext.currentMonitorIdx, false, false);
}
else
{
EvrInit(_scene, (uint) upDevice.ToInt32(), ref _vmr9Filter, (uint) hMonitor.ToInt32(),
GUIGraphicsContext.currentMonitorIdx, true, true);
Log.Debug("VMR9: force disable vsync and bias correction for Win7 or lower - current primary is : {0}",
Screen.AllScreens[adapterOrdinal].Primary);
}
}
else
{
if ((OSInfo.OSInfo.Win7OrLater() &&
Screen.AllScreens[adapterOrdinal].Primary) || OSInfo.OSInfo.Win8OrLater())
{
EvrInit(_scene, (uint) upDevice.ToInt32(), ref _vmr9Filter, (uint) hMonitor.ToInt32(),
adapterOrdinal, false, false);