/
PlaneScene.cs
2209 lines (1915 loc) · 81.6 KB
/
PlaneScene.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 MediaPortal.ExtensionMethods;
using MediaPortal.GUI.Library;
using MediaPortal.Player.Subtitles;
using MediaPortal.Profile;
using MediaPortal.Util;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using Geometry = MediaPortal.GUI.Library.Geometry;
namespace MediaPortal.Player
{
/// <summary>
/// This class will draw a video texture onscreen when using VMR9 renderless
/// Its controlled by the allocator wrapper
/// Example on how to use:
/// PlaneScene scene = new PlaneScene(GUIGraphicsContext.RenderGUI)
/// scene.Init()
/// ... allocate direct3d texture
/// scene.SetSrcRect(1.0f,1.0f); //change this depending on the texture dimensions
/// scene.SetSurface(texture); //change this depending on the texture dimensions
/// while (playingMovie)
/// {
/// scene.Render(GUIGraphicsContext.DX9Device, videoTextre, videoSize)
/// }
/// scene.ReleaseSurface(texture)
/// scene.Stop();
/// scene.DeInit();
/// </summary>
public class PlaneScene : IVMR9PresentCallback, IRenderLayer
{
#region variables
private bool _stopPainting = false;
private Surface _renderTarget = null;
private long _diffuseColor = 0xFFFFFFFF;
private int _fadeFrameCounter = 0;
private bool _fadingIn = true;
private float _uValue = 1.0f;
private float _vValue = 1.0f;
private Rectangle _rectPrevious;
private Rectangle _subsRect;
private bool _shouldRenderTexture = false;
private bool _lastOverlayVisible = false;
private bool _isEnabled = true;
private Geometry.Type _aspectRatioType;
private static Rectangle _sourceRect, _destinationRect;
private Geometry _geometry = new Geometry();
private VMR9Util _vmr9Util = null;
private VertexBuffer[] _vertexBuffers;
private uint _textureAddress;
private CropSettings _cropSettings;
private bool updateCrop = false; // indicates that _cropSettings has been updated
private int _arVideoWidth = 4;
private int _arVideoHeight = 3;
private int _prevVideoWidth = 0;
private int _prevVideoHeight = 0;
private int _prevArVideoWidth = 0;
private int _prevArVideoHeight = 0;
private static bool _reEntrant = false;
private bool _drawVideoAllowed = true;
private int _debugStep = 0;
private GUIImage _blackImage;
private const int _full3DTABMinHeight = 720 * 2;
private const int _full3DSBSMinWidth = 1280 * 2;
private FrameGrabber grabber = FrameGrabber.GetInstance();
//Additions for Non-Linear Stretch
private bool _useNonLinearStretch = false; //Should we do NLS for this AR?
//These are the partitioning values for the non-linear stretch.
//TODO: Maybe get these from Geometry class.
//The horizontal percentage of the source each partition represents (Should be symmetrical and sum up to 100.0)
private float[] nlsSourcePartitioning = {
6.25f, 9.375f, 12.50f, 6.25f, 12.50f, 6.25f, 12.50f, 6.25f, 12.50f, 9.375f
,
6.25f
};
//The horizontal percentage of the destination to fit each partition into (Should be symmetrical and sum up to 100.0)
private float[] nlsDestPartitioning = {
7.06f, 10.15f, 12.65f, 5.88f, 11.47f, 5.58f, 11.47f, 5.88f, 12.65f, 10.15f,
7.06f
};
private bool _disableLowLatencyMode = false;
private bool _visible = false;
private int _reduceMadvrFrame = 0;
private bool _useReduceMadvrFrame = false;
private string _subEngineType = "";
private readonly object _lockobj = new object();
private bool UiVisible { get; set; }
protected internal Thread WorkerThread = null;
#endregion
#region ctor
public PlaneScene(VMR9Util util)
{
MadVrRenderTarget = null;
// Log.Info("PlaneScene: ctor()");
_textureAddress = 0;
_vmr9Util = util;
// Number of vertex buffers must be same as numer of segments in non-linear stretch
_vertexBuffers = new VertexBuffer[nlsSourcePartitioning.Length];
for (int i = 0; i < _vertexBuffers.Length; i++)
{
_vertexBuffers[i] = new VertexBuffer(typeof (CustomVertex.TransformedColoredTextured),
4,
GUIGraphicsContext.DX9Device,
0,
CustomVertex.TransformedColoredTextured.Format,
GUIGraphicsContext.GetTexturePoolType());
}
_blackImage = new GUIImage(0);
_blackImage.SetFileName("black.png");
_blackImage.AllocResources();
_cropSettings = new CropSettings();
}
#endregion
#region properties
/// <summary>
/// Returns a rectangle specifying the part of the video texture which is
/// shown
/// </summary>
public static Rectangle SourceRect
{
get { return _sourceRect; }
}
/// <summary>
/// Returns a rectangle specifying the video window onscreen
/// </summary>
public static Rectangle DestRect
{
get { return _destinationRect; }
}
public bool DrawVideo
{
get { return _drawVideoAllowed; }
set
{
_drawVideoAllowed = value;
//Log.Info("PlaneScene: video draw allowed:{0}", _drawVideoAllowed);
}
}
public bool DisableLowLatencyMode
{
get { return _disableLowLatencyMode; }
set { _disableLowLatencyMode = value; }
}
public bool Visible
{
get { return _visible; }
set { _visible = value; }
}
public Surface MadVrRenderTarget { get; set; }
public bool Enabled
{
get { return _isEnabled; }
set
{
_isEnabled = value;
//Log.Info("planescene: enabled:{0}", _isEnabled);
}
}
#endregion
#region public members
/// <summary>
/// Stop VMR9 rendering
/// this method will restore the DirectX render target since
/// this might have been changed by the Video Mixing Renderer9
/// </summary>
public void Stop()
{
//Log.Info("PlaneScene: Stop()");
DrawVideo = false;
_stopPainting = true;
}
/// <summary>
/// Set the texture dimensions. Sometimes the video texture is larger then the
/// video resolution. In this case we should copy only a part from the video texture
/// Using this function one can set how much of the video texture should be used
/// </summary>
/// <param name="fU">(0-1) Specifies the width to used of the video texture</param>
/// <param name="fV">(0-1) Specifies the height to used of the video texture</param>
public void SetSrcRect(float fU, float fV)
{
_rectPrevious = new Rectangle(0, 0, 0, 0);
_uValue = fU;
_vValue = fV;
}
/// <summary>
/// Deinitialize. Release the vertex buffer and the render target resources
/// This function should be called at last when playing has been stopped
/// </summary>
public void Deinit()
{
GUIWindowManager.Receivers -= new SendMessageHandler(this.OnMessage);
GUILayerManager.UnRegisterLayer(this);
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
//if (MadVrRenderTarget != null)
//{
// //VMR9 changes the directx 9 render target. Thats why we set it back to what it was
// if (!MadVrRenderTarget.Disposed)
// {
// GUIGraphicsContext.DX9Device.SetRenderTarget(0, MadVrRenderTarget);
// }
// MadVrRenderTarget.Dispose();
// MadVrRenderTarget = null;
//}
}
else if (_renderTarget != null)
{
//VMR9 changes the directx 9 render target. Thats why we set it back to what it was
if (!_renderTarget.Disposed)
{
GUIGraphicsContext.DX9Device.SetRenderTarget(0, _renderTarget);
}
_renderTarget.SafeDispose();
_renderTarget = null;
}
for (int i = 0; i < _vertexBuffers.Length; i++)
{
if (_vertexBuffers[i] != null)
{
_vertexBuffers[i].SafeDispose();
_vertexBuffers[i] = null;
}
}
if (_blackImage != null)
{
_blackImage.SafeDispose();
_blackImage = null;
}
if (grabber != null)
{
lock (GUIGraphicsContext.RenderModeSwitch)
{
grabber.Clean();
}
}
SubtitleRenderer.GetInstance().Clear();
if (GUIGraphicsContext.LastFrames != null)
{
foreach (Texture texture in GUIGraphicsContext.LastFrames)
{
texture.Dispose();
}
GUIGraphicsContext.LastFrames.Clear();
}
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
GUIGraphicsContext.InVmr9Render = false;
if (VMR9Util.g_vmr9 != null)
{
if (GUIGraphicsContext.MadVrRenderTargetVMR9 != null && !GUIGraphicsContext.MadVrRenderTargetVMR9.Disposed)
{
GUIGraphicsContext.DX9Device.SetRenderTarget(0, GUIGraphicsContext.MadVrRenderTargetVMR9);
}
}
}
}
/// <summary>
/// Initialize.
/// This should be called before any other methods.
/// It allocates resources needed
/// </summary>
/// <param name="device">Direct3d devices</param>
public void Init()
{
//Log.Info("PlaneScene: init()");
if (GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR)
{
_renderTarget = GUIGraphicsContext.DX9Device.GetRenderTarget(0);
}
else if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
// Reset 3D
GUIGraphicsContext.NoneDone = false;
GUIGraphicsContext.TopAndBottomDone = false;
GUIGraphicsContext.SideBySideDone = false;
GUIGraphicsContext.SBSLeftDone = false;
GUIGraphicsContext.SBSRightDone = false;
GUIGraphicsContext.TABTopDone = false;
GUIGraphicsContext.TABBottomDone = false;
GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.None;
}
GUILayerManager.RegisterLayer(this, GUILayerManager.LayerType.Video);
GUIWindowManager.Receivers += new SendMessageHandler(this.OnMessage);
using (Settings xmlreader = new MPSettings())
{
try
{
_disableLowLatencyMode = xmlreader.GetValueAsBool("general", "disableLowLatencyMode", true);
_reduceMadvrFrame = xmlreader.GetValueAsInt("general", "reduceMadvrFrame", 0);
_useReduceMadvrFrame = xmlreader.GetValueAsBool("general", "useReduceMadvrFrame", false);
_subEngineType = xmlreader.GetValueAsString("subtitles", "engine", "DirectVobSub");
}
catch (Exception)
{
}
}
}
/// <summary>
/// OnMessage.
/// Handles received GUIMessage's from graphics context.
/// </summary>
/// <param name="message">GUIMessage</param>
private void OnMessage(GUIMessage message)
{
switch (message.Message)
{
case GUIMessage.MessageType.GUI_MSG_PLANESCENE_CROP:
CropSettings cs = message.Object as CropSettings;
if (cs != null)
{
Crop(cs);
}
break;
case GUIMessage.MessageType.GUI_MSG_REGISTER_MADVR_OSD:
if (VMR9Util.g_vmr9 != null)
VMR9Util.g_vmr9.WindowsMessageMp();
break;
case GUIMessage.MessageType.GUI_MSG_MADVRREPOSITION:
if (VMR9Util.g_vmr9 != null)
VMR9Util.g_vmr9.IniMadVrWindowPosition();
break;
}
}
/// <summary>
/// Crop.
/// Crops the current picture..
/// </summary>
/// <param name="message">CropSettings</param>
private void Crop(CropSettings cs)
{
lock (this)
{
_cropSettings = cs;
Log.Info("PlaneScene: Crop: top:{0}, bottom:{1}, left:{2}, right:{3}", cs.Top, cs.Bottom, cs.Left, cs.Right);
updateCrop = true;
}
}
/// <summary>
/// This method calculates the rectangle on screen where the video should be presented
/// this depends on if we are in fullscreen mode or preview mode
/// and on the current aspect ration settings
/// </summary>
/// <param name="videoSize">Size of video stream</param>
/// <returns>
/// true : video window is visible
/// false: video window is not visible
/// </returns>
public bool SetVideoWindow(Size videoSize)
{
lock (GUIGraphicsContext.RenderLock)
{
try
{
if (!GUIGraphicsContext.IsPlayingVideo && !_vmr9Util.InMenu)
{
return false;
}
// check if the aspect ratio belongs to a Full-HD 3D format
GUIGraphicsContext.IsFullHD3DFormat = false;
if (((double) videoSize.Width/videoSize.Height >= 2.5) && (videoSize.Width >= _full3DSBSMinWidth))
// we have Full HD SBS
{
GUIGraphicsContext.IsFullHD3DFormat = true;
}
else if (((double) videoSize.Width/videoSize.Height <= 1.5) && (videoSize.Height >= _full3DTABMinHeight))
// we have Full HD TAB
{
GUIGraphicsContext.IsFullHD3DFormat = true;
}
GUIGraphicsContext.VideoSize = videoSize;
// get the window where the video/tv should be shown
float x = GUIGraphicsContext.VideoWindow.X;
float y = GUIGraphicsContext.VideoWindow.Y;
int nw = GUIGraphicsContext.VideoWindow.Width;
int nh = GUIGraphicsContext.VideoWindow.Height;
//sanity checks
if (nw > GUIGraphicsContext.OverScanWidth)
{
nw = GUIGraphicsContext.OverScanWidth;
}
if (nh > GUIGraphicsContext.OverScanHeight)
{
nh = GUIGraphicsContext.OverScanHeight;
}
//are we supposed to show video in fullscreen or in a preview window?
if (GUIGraphicsContext.IsFullScreenVideo || !GUIGraphicsContext.ShowBackground)
{
//yes fullscreen, then use the entire screen
x = GUIGraphicsContext.OverScanLeft;
y = GUIGraphicsContext.OverScanTop;
nw = GUIGraphicsContext.OverScanWidth;
nh = GUIGraphicsContext.OverScanHeight;
}
//sanity check
if (nw <= 10 || nh <= 10 || x < 0 || y < 0)
{
// Need to resize window video for madVR
if (GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR) //TODO
return false;
}
GUIGraphicsContext.ScaleVideoWindow(ref nw, ref nh, ref x, ref y);
GUIGraphicsContext.VideoReceived();
//did the video window,aspect ratio change? if not
//then we dont need to recalculate and just return the previous settings
//add a delta value of -1 or +1 to check
if (!updateCrop && (int)x == _rectPrevious.X && (int)y == _rectPrevious.Y &&
nw == _rectPrevious.Width && nh == _rectPrevious.Height &&
GUIGraphicsContext.ARType == _aspectRatioType &&
GUIGraphicsContext.Overlay == _lastOverlayVisible && _shouldRenderTexture &&
(_prevVideoWidth == videoSize.Width || _prevVideoWidth == videoSize.Width + 1 ||
_prevVideoWidth == videoSize.Width - 1) &&
(_prevVideoHeight == videoSize.Height || _prevVideoHeight == videoSize.Height + 1 ||
_prevVideoHeight == videoSize.Height - 1) &&
(_prevArVideoWidth == _arVideoWidth || _prevArVideoWidth == _arVideoWidth + 1 ||
_prevArVideoWidth == _arVideoWidth - 1) &&
(_prevArVideoHeight == _arVideoHeight || _prevArVideoHeight == _arVideoHeight + 1 ||
_prevArVideoHeight == _arVideoHeight - 1))
{
//not changed, return previous settings
return _shouldRenderTexture;
}
// Todo why add this hack for XySubFilter subtitle engine
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR &&
_subEngineType.Equals("XySubFilter") && IsFullScreen() && g_Player.Player is VideoPlayerVMR9)
{
Size client = GUIGraphicsContext.form.ClientSize;
if (client.Width == videoSize.Width || _prevVideoWidth == videoSize.Width)
{
return false;
}
}
//settings (position,size,aspect ratio) changed.
//Store these settings and start calucating the new video window
_rectPrevious = new Rectangle((int) x, (int) y, (int) nw, (int) nh);
_subsRect = _rectPrevious;
_aspectRatioType = GUIGraphicsContext.ARType;
_lastOverlayVisible = GUIGraphicsContext.Overlay;
_prevVideoWidth = videoSize.Width;
_prevVideoHeight = videoSize.Height;
_prevArVideoWidth = _arVideoWidth;
_prevArVideoHeight = _arVideoHeight;
//calculate the video window according to the current aspect ratio settings
float fVideoWidth = (float) videoSize.Width;
float fVideoHeight = (float) videoSize.Height;
// if we have a Full-HD 3D video we half the width or height in order
// to provide only the size of one half to the GetWindow call of the
// Geometry class
if (((double) videoSize.Width/videoSize.Height >= 2.5) && (videoSize.Width >= _full3DSBSMinWidth))
// we have Full HD SBS
{
fVideoWidth /= 2;
}
else if (((double) videoSize.Width/videoSize.Height <= 1.5) && (videoSize.Height >= _full3DTABMinHeight))
// we have Full HD TAB
{
fVideoHeight /= 2;
}
_geometry.ImageWidth = (int) fVideoWidth;
_geometry.ImageHeight = (int) fVideoHeight;
_geometry.ScreenWidth = (int) nw;
_geometry.ScreenHeight = (int) nh;
_geometry.ARType = GUIGraphicsContext.ARType;
_geometry.PixelRatio = GUIGraphicsContext.PixelRatio;
// if the width or height was altered because of a Full-HD 3D format we recalculate
// the width to allow the GetWindowCall to operate with the correct aspect ratio
if (GUIGraphicsContext.IsFullHD3DFormat)
{
_arVideoWidth = (int) ((float) _geometry.ImageWidth/_geometry.ImageHeight*_arVideoHeight);
}
_geometry.GetWindow(_arVideoWidth, _arVideoHeight, out _sourceRect, out _destinationRect,
out _useNonLinearStretch, _cropSettings);
updateCrop = false;
_destinationRect.X += (int) x;
_destinationRect.Y += (int) y;
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
// Force VideoWindow to be refreshed with madVR when switching from video size like 16:9 to 4:3
GUIGraphicsContext.UpdateVideoWindow = true;
GUIGraphicsContext.VideoWindowChanged();
}
else
{
//sanity check
if (_destinationRect.Width < 10)
{
return false;
}
if (_destinationRect.Height < 10)
{
return false;
}
if (_sourceRect.Width < 10)
{
return false;
}
if (_sourceRect.Height < 10)
{
return false;
}
}
Log.Debug("PlaneScene: crop T, B : {0}, {1}", _cropSettings.Top, _cropSettings.Bottom);
Log.Debug("PlaneScene: crop L, R : {0}, {1}", _cropSettings.Left, _cropSettings.Right);
Log.Info("PlaneScene: video WxH : {0}x{1}", videoSize.Width, videoSize.Height);
Log.Debug("PlaneScene: video AR : {0}:{1}", _arVideoWidth, _arVideoHeight);
Log.Info("PlaneScene: screen WxH : {0}x{1}", nw, nh);
Log.Debug("PlaneScene: AR type : {0}", GUIGraphicsContext.ARType);
Log.Debug("PlaneScene: PixelRatio : {0}", GUIGraphicsContext.PixelRatio);
Log.Debug("PlaneScene: src : ({0},{1})-({2},{3})",
_sourceRect.X, _sourceRect.Y, _sourceRect.X + _sourceRect.Width, _sourceRect.Y + _sourceRect.Height);
Log.Debug("PlaneScene: dst : ({0},{1})-({2},{3})",
_destinationRect.X, _destinationRect.Y, _destinationRect.X + _destinationRect.Width,
_destinationRect.Y + _destinationRect.Height);
// Comment that part because it steal focus of other window
//if (GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR)
//{
// Util.Utils.SwitchFocus();
//}
return true;
}
catch (Exception ex)
{
Log.Error(ex);
return false;
}
}
}
public void Repaint()
{
if (GUIGraphicsContext.CurrentState == GUIGraphicsContext.State.STOPPING ||
GUIGraphicsContext.CurrentState == GUIGraphicsContext.State.LOST)
{
return;
}
if (!_isEnabled)
{
return;
}
if (_stopPainting)
{
return;
}
try
{
if (!GUIGraphicsContext.InVmr9Render && GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR)
{
InternalPresentImage(_vmr9Util.VideoWidth, _vmr9Util.VideoHeight, _arVideoWidth, _arVideoHeight, true);
}
}
catch (Exception ex)
{
Log.Error("planescene:Unhandled exception in {0} {1} {2}",
ex.Message, ex.Source, ex.StackTrace);
}
}
#endregion
#region IVMR9Callback Members
public int PresentImage(Int16 width, Int16 height, Int16 arWidth, Int16 arHeight, uint pTexture, uint pSurface)
{
lock (GUIGraphicsContext.RenderLock)
{
try
{
// Alert the frame grabber that it has a chance to grab a video frame
// if it likes (method returns immediately otherwise
if (GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR)
grabber.OnFrame(width, height, arWidth, arHeight, pSurface, FrameGrabber.FrameSource.Video);
_textureAddress = pTexture;
if (pTexture == 0)
{
Log.Debug("PlaneScene: PresentImage() dispose surfaces");
_vmr9Util.VideoWidth = 0;
_vmr9Util.VideoHeight = 0;
_vmr9Util.VideoAspectRatioX = 0;
_vmr9Util.VideoAspectRatioY = 0;
_arVideoWidth = 0;
_arVideoHeight = 0;
return 0;
}
if (GUIGraphicsContext.CurrentState == GUIGraphicsContext.State.STOPPING)
{
return 0;
}
_vmr9Util.FreeFrameCounter++;
if (!_drawVideoAllowed || !_isEnabled)
{
Log.Info("planescene:PresentImage() frame:{0} enabled:{1} allowed:{2}", _vmr9Util.FrameCounter, _isEnabled,
_drawVideoAllowed);
_vmr9Util.FrameCounter++;
return 0;
}
_vmr9Util.FrameCounter++;
// Log.Info("vmr9:present image()");
if (GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR)
InternalPresentImage(width, height, arWidth, arHeight, false);
// Log.Info("vmr9:present image() done");
}
catch (Exception ex)
{
Log.Error("Planescene: Error in PresentImage - {0}", ex.ToString());
}
}
return 0;
}
public void RenderFrame(Int16 width, Int16 height, Int16 arWidth, Int16 arHeight, IntPtr pSurface)
{
IntPtr ptrMadVr = pSurface;
Surface surfaceMadVr = new Surface(ptrMadVr);
Size client = GUIGraphicsContext.form.ClientSize;
try
{
unsafe
{
lock (GUIGraphicsContext.RenderModeSwitch)
{
if (grabber != null)
grabber.OnFrame((short)client.Width, (short)client.Height, (short)client.Width, (short)client.Height, (uint)surfaceMadVr.UnmanagedComPointer,
FrameGrabber.FrameSource.Video);
}
}
surfaceMadVr.ReleaseGraphics();
surfaceMadVr.Dispose();
}
catch (Exception ex)
{
surfaceMadVr.ReleaseGraphics();
surfaceMadVr.Dispose();
}
}
//internal void WorkerThreadStart()
//{
// WorkerThread = new Thread(new ThreadStart(madVRGrab));
// WorkerThread.IsBackground = true;
// GUIGraphicsContext.WorkerThreadStart = true;
// WorkerThread.Name = "Grab Frame thread";
// WorkerThread.Priority = ThreadPriority.AboveNormal;
// WorkerThread.Start();
//}
//private void madVRGrab()
//{
// while (true)
// {
// if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR &&
// GUIGraphicsContext.Vmr9Active)
// {
// if (VMR9Util.g_vmr9 != null)
// {
// Thread.Sleep(10);
// VMR9Util.g_vmr9.MadVrGrabFrame();
// }
// }
// }
//}
public void GrabMadVrScreenshot(IntPtr pTargetmadVrDib)
{
IntPtr pdib = pTargetmadVrDib;
try
{
if (pTargetmadVrDib != IntPtr.Zero)
{
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("Planescene: 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);
// Save screenshot from DIB
Win32API.BITMAPINFOHEADER bmih = (Win32API.BITMAPINFOHEADER) Marshal.PtrToStructure(pdib, typeof (Win32API.BITMAPINFOHEADER));
IntPtr pixels = IntPtr.Add(pdib, bmih.biSize);
Bitmap result = new Bitmap(bmih.biWidth, bmih.biHeight, bmih.biWidth*4, PixelFormat.Format32bppRgb, pixels);
result.RotateFlip(RotateFlipType.RotateNoneFlipY);
result.Save(fileName + ".jpg", ImageFormat.Jpeg);
result.SafeDispose();
}
}
catch
{
pdib = IntPtr.Zero;
pTargetmadVrDib = IntPtr.Zero;
Log.Info("Planescene : madVR grabbing image window failed");
}
finally
{
pdib = IntPtr.Zero;
pTargetmadVrDib = IntPtr.Zero;
}
}
public void GrabMadVrFrame(IntPtr pTargetmadVrDib)
{
lock (GUIGraphicsContext.RenderModeSwitch)
{
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
if (pTargetmadVrDib != IntPtr.Zero)
{
if (grabber != null)
{
grabber.OnFrame(1920, 1080, 0, 0, pTargetmadVrDib, FrameGrabber.FrameSource.Video);
}
}
}
}
}
public void GrabMadVrCurrentFrame(IntPtr pTargetmadVrDib)
{
lock (GUIGraphicsContext.RenderModeSwitch)
{
if (GUIGraphicsContext.madVRCurrentFrameBitmap != null)
{
GUIGraphicsContext.madVRCurrentFrameBitmap.Dispose();
GUIGraphicsContext.madVRCurrentFrameBitmap = null;
}
if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
{
// 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);
// IMPORTANT: Closes and disposes the stream
// If this is not done we get a memory leak!
b.Dispose();
}
}
}
}
}
public int ReduceMadvrFrame()
{
if (_useReduceMadvrFrame)
{
return _reduceMadvrFrame;
}
return 0;
}
public bool IsUiVisible()
{
return UiVisible;
}
public bool IsFullScreen()
{
return GUIGraphicsContext.IsFullScreenVideo;
}
public int RenderGui(Int16 width, Int16 height, Int16 arWidth, Int16 arHeight)
{
return RenderLayers(GUILayers.under, width, height, arWidth, arHeight);
}
public int RenderOverlay(Int16 width, Int16 height, Int16 arWidth, Int16 arHeight)
{
return RenderLayers(GUILayers.over, width, height, arWidth, arHeight);
}
private int RenderLayers(GUILayers layers, Int16 width, Int16 height, Int16 arWidth, Int16 arHeight)
{
UiVisible = false;
//lock (GUIGraphicsContext.RenderMadVrLock)
{
try
{
if (_reEntrant)
{
return -1;
}
if (GUIGraphicsContext.CurrentState == GUIGraphicsContext.State.LOST)
{
//Log.Error("1");
return -1;
}
if (_stopPainting)
{
//Log.Error("2");
return -1;
}
if (GUIGraphicsContext.IsSwitchingToNewSkin)
{
//Log.Error("3");
return -1;
}
if (GUIWindowManager.IsSwitchingToNewWindow && !_vmr9Util.InMenu)
{
//Log.Error("4");
return -1; // (0) -> S_OK, (1) -> S_FALSE; //dont present video during window transitions
}
// Disable for now and added back to g_player
//if (VMR9Util.g_vmr9 != null)
//{
// VMR9Util.g_vmr9.StartMadVrPaused();
//}
_reEntrant = true;
GUIGraphicsContext.InVmr9Render = true;
if (VMR9Util.g_vmr9 != null) VMR9Util.g_vmr9.PlaneSceneMadvrTimer = DateTime.Now;
if (width > 0 && height > 0)
{
_vmr9Util.VideoWidth = width;
_vmr9Util.VideoHeight = height;
_vmr9Util.VideoAspectRatioX = arWidth;
_vmr9Util.VideoAspectRatioY = arHeight;
_arVideoWidth = arWidth;
_arVideoHeight = arHeight;
//Log.Debug("PlaneScene width {0}, height {1}", width, height);
Size nativeSize = new Size(width, height);
if (GUIGraphicsContext.Render3DMode != GUIGraphicsContext.eRender3DMode.SideBySideTo2D &&
GUIGraphicsContext.Render3DMode != GUIGraphicsContext.eRender3DMode.TopAndBottomTo2D)
{
_shouldRenderTexture = SetVideoWindow(nativeSize);
}
}
lock (GUIGraphicsContext.RenderModeSwitch)
{
// in case of GUIGraphicsContext.BlankScreen == true always use old method
// for painting blank screen
if (GUIGraphicsContext.BlankScreen ||
GUIGraphicsContext.Render3DMode == GUIGraphicsContext.eRender3DMode.None ||
GUIGraphicsContext.Render3DMode == GUIGraphicsContext.eRender3DMode.SideBySideTo2D ||
GUIGraphicsContext.Render3DMode == GUIGraphicsContext.eRender3DMode.TopAndBottomTo2D ||
GUIGraphicsContext.Render3DMode == GUIGraphicsContext.eRender3DMode.SideBySideFrom2D)
{
if (GUIGraphicsContext.Render3DMode == GUIGraphicsContext.eRender3DMode.SideBySideFrom2D)
// convert 2D to 3D
{
// left half
// right half
}
else // normal 2D output
{
// old output path or force 3D material to 2D by blitting only left/top halp
GUIGraphicsContext.Render3DModeHalf = GUIGraphicsContext.eRender3DModeHalf.None;
if (GUIGraphicsContext.Render3DMode == GUIGraphicsContext.eRender3DMode.SideBySideTo2D)
GUIGraphicsContext.Render3DModeHalf = GUIGraphicsContext.eRender3DModeHalf.SBSLeft;
if (GUIGraphicsContext.Render3DMode == GUIGraphicsContext.eRender3DMode.TopAndBottomTo2D)
GUIGraphicsContext.Render3DModeHalf = GUIGraphicsContext.eRender3DModeHalf.TABTop;
if (GUIGraphicsContext.Render3DMode == GUIGraphicsContext.eRender3DMode.SideBySide)
GUIGraphicsContext.Render3DModeHalf = GUIGraphicsContext.eRender3DModeHalf.None;
if (GUIGraphicsContext.Render3DMode == GUIGraphicsContext.eRender3DMode.TopAndBottom)
GUIGraphicsContext.Render3DModeHalf = GUIGraphicsContext.eRender3DModeHalf.None;
if (GUIGraphicsContext.Render3DMode == GUIGraphicsContext.eRender3DMode.None)
{
GUIGraphicsContext.Render3DModeHalf = GUIGraphicsContext.eRender3DModeHalf.None;
if (!GUIGraphicsContext.NoneDone)
{
// Get Client size
Size client = GUIGraphicsContext.form.ClientSize;
VMR9Util.g_vmr9?.MadVrScreenResize(GUIGraphicsContext.form.Location.X,
GUIGraphicsContext.form.Location.Y, client.Width, client.Height, true);
VMR9Util.g_vmr9?.MadVr3DSizeLeft(0, 0, client.Width, client.Height);
VMR9Util.g_vmr9?.MadVr3DSizeRight(0, 0, client.Width, client.Height);
VMR9Util.g_vmr9?.MadVr3DOnOff(false);
GUIGraphicsContext.NoneDone = true;
GUIGraphicsContext.TopAndBottomDone = false;
GUIGraphicsContext.SideBySideDone = false;
GUIGraphicsContext.SBSLeftDone = false;
GUIGraphicsContext.SBSRightDone = false;
GUIGraphicsContext.TABTopDone = false;
GUIGraphicsContext.TABBottomDone = false;
// Force VideoWindow to be refreshed with madVR when switching from video size like 16:9 to 4:3
GUIGraphicsContext.UpdateVideoWindow = true;
GUIGraphicsContext.VideoWindowChanged();
// Force a madVR refresh to resize MP window
g_Player.RefreshMadVrVideo();