Пример #1
0
        private Texture2D PlatformGetTexture()
        {
            // This will return a null texture if
            // the video hasn't started playing yet
            // or the last frame if the video is stopped
            // as per XNA's behavior.
            if (_state != MediaState.Playing)
                return _lastFrame;

            long pts;
            if (!_mediaEngine.HasVideo() || !_mediaEngine.OnVideoStreamTick(out pts))
                return _lastFrame;

            _lastFrame = new Texture2D(Game.Instance.GraphicsDevice,
                                        _currentVideo.Width,
                                        _currentVideo.Height,
                                        false,
                                        SurfaceFormat.Bgra32, 
                                        Texture2D.SurfaceType.RenderTarget);

#if WINDOWS_UAP
			var region = new SharpDX.Mathematics.Interop.RawRectangle(0, 0, _currentVideo.Width, _currentVideo.Height);
#else
			var region = new SharpDX.Rectangle(0, 0, _currentVideo.Width, _currentVideo.Height);
#endif
            _mediaEngine.TransferVideoFrame(_lastFrame._texture, null, region, null);

            return _lastFrame;
        }
Пример #2
0
 private unsafe static int MapOutputRectToInputRectsImpl(IntPtr thisPtr, IntPtr outputRect, IntPtr inputRects, int inputRectsCount)
 {
     try
     {
         var shadow = ToShadow<TransformShadow>(thisPtr);
         var callback = (Transform)shadow.Callback;
         var inputRectangles = new SharpDX.Rectangle[inputRectsCount];
         Utilities.Read(inputRects, inputRectangles, 0, inputRectsCount);
         callback.MapOutputRectangleToInputRectangles(*(SharpDX.Rectangle*)outputRect, inputRectangles);
         Utilities.Write(inputRects, inputRectangles, 0, inputRectsCount);
     }
     catch (Exception exception)
     {
         return (int)SharpDX.Result.GetResultFromException(exception);
     }
     return Result.Ok.Code;
 }
Пример #3
0
		// Method to marshal from native to managed struct
        internal unsafe void __MarshalFrom(ref __Native @ref)
        {            
            this.Start = @ref.Start;
            this.End = @ref.End;
            this.SampleFormat = @ref.SampleFormat;
            this.SrcSurface = @ref.SrcSurface;
            this.SrcRect = @ref.SrcRect;
            this.DstRect = @ref.DstRect;
            fixed (void* __to = &this.Pal[0]) fixed (void* __from = &@ref.Pal) SharpDX.Utilities.CopyMemory((IntPtr) __to, (IntPtr) __from, 16*sizeof ( SharpDX.MediaFoundation.DirectX.AYUVSample8));
            this.PlanarAlpha = @ref.PlanarAlpha;
            this.SampleData = @ref.SampleData;
        }
Пример #4
0
        private Glyph ImportGlyph(Factory factory, FontFace fontFace, char character, FontMetrics fontMetrics, float fontSize, bool activateAntiAliasDetection)
        {
            var indices = fontFace.GetGlyphIndices(new int[] {character});

            var metrics = fontFace.GetDesignGlyphMetrics(indices, false);
            var metric = metrics[0];

            var width = (float)(metric.AdvanceWidth - metric.LeftSideBearing - metric.RightSideBearing) / fontMetrics.DesignUnitsPerEm * fontSize;
            var height = (float)(metric.AdvanceHeight - metric.TopSideBearing - metric.BottomSideBearing) / fontMetrics.DesignUnitsPerEm * fontSize;

            var xOffset = (float)metric.LeftSideBearing / fontMetrics.DesignUnitsPerEm * fontSize;
            var yOffset = (float)(metric.TopSideBearing - metric.VerticalOriginY) / fontMetrics.DesignUnitsPerEm * fontSize;

            var advanceWidth = (float)(metric.AdvanceWidth) / fontMetrics.DesignUnitsPerEm * fontSize;
            var advanceHeight = (float)(metric.AdvanceHeight) / fontMetrics.DesignUnitsPerEm * fontSize;

            var pixelWidth = (int)Math.Ceiling(width + 2);
            var pixelHeight = (int)Math.Ceiling(height + 2);

            Bitmap bitmap;
            if(char.IsWhiteSpace(character))
            {
                bitmap = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
            }
            else
            {
                var glyphRun = new GlyphRun()
                               {
                                   FontFace = fontFace,
                                   Advances = new[] { (float)Math.Round(advanceWidth) },
                                   FontSize = fontSize,
                                   BidiLevel = 0,
                                   Indices = indices,
                                   IsSideways = false,
                                   Offsets = new[] {new GlyphOffset()}
                               };

                var matrix = SharpDX.Matrix.Identity;
                matrix.M41 = -(float)Math.Floor(xOffset - 1);
                matrix.M42 = -(float)Math.Floor(yOffset - 1);

                RenderingMode renderingMode;
                if (activateAntiAliasDetection)
                {
                    var rtParams = new RenderingParams(factory);
                    renderingMode = fontFace.GetRecommendedRenderingMode(fontSize, 1.0f, MeasuringMode.Natural, rtParams);
                    rtParams.Dispose();
                }
                else
                {
                    renderingMode = RenderingMode.Aliased;
                }

                using(var runAnalysis = new GlyphRunAnalysis(factory,
                    glyphRun,
                    1.0f,
                    matrix,
                    renderingMode,
                    MeasuringMode.Natural,
                    0.0f,
                    0.0f))
                {
                    var bounds = new SharpDX.Rectangle(0, 0, pixelWidth, pixelHeight);
                    bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);

                    if(renderingMode == RenderingMode.Aliased)
                    {
                        var texture = new byte[bounds.Width * bounds.Height];
                        runAnalysis.CreateAlphaTexture(TextureType.Aliased1x1, bounds, texture, texture.Length);
                        bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
                        for (int y = 0; y < bounds.Height; y++)
                        {
                            for (int x = 0; x < bounds.Width; x++)
                            {
                                int pixelX = y * bounds.Width + x;
                                var grey = texture[pixelX];
                                var color = Color.FromArgb(grey, grey, grey);

                                bitmap.SetPixel(x, y, color);
                            }
                        }
                    }
                    else
                    {
                        var texture = new byte[bounds.Width * bounds.Height * 3];
                        runAnalysis.CreateAlphaTexture(TextureType.Cleartype3x1, bounds, texture, texture.Length);
                        for (int y = 0; y < bounds.Height; y++)
                        {
                            for (int x = 0; x < bounds.Width; x++)
                            {
                                int pixelX = (y * bounds.Width + x) * 3;
                                var red = texture[pixelX];
                                var green = texture[pixelX + 1];
                                var blue = texture[pixelX + 2];
                                var color = Color.FromArgb(red, green, blue);

                                bitmap.SetPixel(x, y, color);
                            }
                        }
                    }

                    //var positionUnderline = (float)fontMetrics.UnderlinePosition / fontMetrics.DesignUnitsPerEm * fontSize;
                    //var positionUnderlineSize = (float)fontMetrics.UnderlineThickness / fontMetrics.DesignUnitsPerEm * fontSize;
                }
            }

            var glyph = new Glyph(character, bitmap)
                        {
                            XOffset = (float)Math.Floor(xOffset-1),
                            XAdvance = (float)Math.Round(advanceWidth),
                            YOffset = (float)Math.Floor(yOffset-1),
                        };
            return glyph;
        }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            MyChildRenderItem.RenderDataStruct Item = (MyChildRenderItem.RenderDataStruct)value;
            if (Item.FontSize != AppSettings.dFontSize)
            {
                Item.sizeFunc(); //cannot react this late
                Item = (MyChildRenderItem.RenderDataStruct)value;
            }
            int pixelWidth = (int)Item.Width, pixelHeight = (int)Item.Height;
            SurfaceImageSource newSource = new SurfaceImageSource(pixelWidth, pixelHeight, false);
            //SharpDX.Direct3D11.Device D3DDev = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport);
            //SharpDX.DXGI.Device DXDev = D3DDev.QueryInterface<SharpDX.DXGI.Device>();
#if WINDOWS_PHONE_APP || !STORETOOLKIT
            SharpDX.DXGI.ISurfaceImageSourceNativeWithD2D surfaceImageSourceNative = SharpDX.ComObject.As<SharpDX.DXGI.ISurfaceImageSourceNativeWithD2D>(newSource);
#else
            SharpDX.DXGI.ISurfaceImageSourceNative surfaceImageSourceNative = SharpDX.ComObject.As<SharpDX.DXGI.ISurfaceImageSourceNative>(newSource);
#endif
            SharpDX.Rectangle rt = new SharpDX.Rectangle(0, 0, pixelWidth, pixelHeight);
#if WINDOWS_PHONE_APP || !STORETOOLKIT
            SharpDX.Point pt;
            IntPtr obj;
            surfaceImageSourceNative.Device = TextShaping.Dev2D;
            surfaceImageSourceNative.BeginDraw(rt, new Guid("e8f7fe7a-191c-466d-ad95-975678bda998"), out obj, out pt); //d2d1_1.h
            SharpDX.Direct2D1.DeviceContext devcxt = SharpDX.ComObject.As<SharpDX.Direct2D1.DeviceContext>(obj);
#else
            SharpDX.DrawingPoint pt;
            surfaceImageSourceNative.Device = TextShaping.DXDev;
            SharpDX.DXGI.Surface surf = surfaceImageSourceNative.BeginDraw(rt, out pt);
            SharpDX.Direct2D1.DeviceContext devcxt = new SharpDX.Direct2D1.DeviceContext(surf);
            //SharpDX.Direct2D1.Bitmap1 bmp = new SharpDX.Direct2D1.Bitmap1(devcxt, surf, new SharpDX.Direct2D1.BitmapProperties1() { DpiX = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().RawDpiX, DpiY = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().RawDpiY, PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), BitmapOptions = SharpDX.Direct2D1.BitmapOptions.CannotDraw | SharpDX.Direct2D1.BitmapOptions.Target });
            //devcxt.Target = bmp;
            devcxt.BeginDraw();
#endif
            devcxt.Clear(new SharpDX.Color4(Windows.UI.Colors.White.R / 255.0f, Windows.UI.Colors.White.G / 255.0f, Windows.UI.Colors.White.B / 255.0f, Windows.UI.Colors.Transparent.A / 255.0f));
            SharpDX.Direct2D1.Layer lyr = new SharpDX.Direct2D1.Layer(devcxt);
            //SharpDX.RectangleF.Infinite
            devcxt.PushLayer(new SharpDX.Direct2D1.LayerParameters1(new SharpDX.RectangleF(float.NegativeInfinity, float.NegativeInfinity, float.PositiveInfinity, float.PositiveInfinity), null, SharpDX.Direct2D1.AntialiasMode.PerPrimitive, SharpDX.Matrix3x2.Identity, 1.0f, null, SharpDX.Direct2D1.LayerOptions1.None), lyr);
            devcxt.PushAxisAlignedClip(new SharpDX.RectangleF(pt.X, pt.Y, pt.X + pixelWidth, pt.Y + pixelHeight), SharpDX.Direct2D1.AntialiasMode.PerPrimitive);
            devcxt.Transform = SharpDX.Matrix3x2.Translation(pt.X, pt.Y);
            SharpDX.DirectWrite.GlyphRun gr = new SharpDX.DirectWrite.GlyphRun();
            gr.FontFace = TextShaping.DWFontFace;
            gr.FontSize = (float)TopLevelFontSize;
            gr.BidiLevel = -1;
            int curlen = 0;
            for (int ct = 0; ct < Item.ItemRuns.Count(); ct++)
            {
                int newlen = curlen + Item.ItemRuns[ct].ItemText.Length;
                gr.Indices = Item.indices.Skip(Item.clusters[curlen]).TakeWhile((indice, idx) => ct == Item.ItemRuns.Count() - 1 || idx < Item.clusters[newlen]).ToArray();
                gr.Offsets = Item.offsets.Skip(Item.clusters[curlen]).TakeWhile((offset, idx) => ct == Item.ItemRuns.Count() - 1 || idx < Item.clusters[newlen]).ToArray();
                gr.Advances = Item.advances.Skip(Item.clusters[curlen]).TakeWhile((advance, idx) => ct == Item.ItemRuns.Count() - 1 || idx < Item.clusters[newlen]).ToArray();
                if (Item.ItemRuns[ct].ItemText[0] == XMLRender.ArabicData.ArabicEndOfAyah) gr.Advances[0] = 0;
                SharpDX.Direct2D1.SolidColorBrush brsh = new SharpDX.Direct2D1.SolidColorBrush(devcxt, new SharpDX.Color4(XMLRender.Utility.ColorR(Item.ItemRuns[ct].Clr) / 255.0f, XMLRender.Utility.ColorG(Item.ItemRuns[ct].Clr) / 255.0f, XMLRender.Utility.ColorB(Item.ItemRuns[ct].Clr) / 255.0f, 0xFF / 255.0f));
                devcxt.DrawGlyphRun(new SharpDX.Vector2((float) pt.X + (float)pixelWidth + Item.offsets[0].AdvanceOffset - (Item.clusters[curlen] == 0 ? 0 : Item.advances.Take(Item.clusters[curlen]).Sum()), Item.BaseLine), gr, brsh, SharpDX.Direct2D1.MeasuringMode.Natural);
                brsh.Dispose();
                curlen = newlen;
            }
            devcxt.Transform = SharpDX.Matrix3x2.Identity;
            devcxt.PopAxisAlignedClip();
            devcxt.PopLayer();
#if WINDOWS_PHONE_APP || !STORETOOLKIT
            gr.Dispose();
#else
            gr.FontFace = null;
#endif
#if WINDOWS_PHONE_APP || !STORETOOLKIT
#else
            devcxt.EndDraw();
            devcxt.Target = null;
            //bmp.Dispose();
#endif
            devcxt.Dispose();
#if WINDOWS_PHONE_APP || !STORETOOLKIT
#else
            surf.Dispose();
#endif
            surfaceImageSourceNative.EndDraw();
            surfaceImageSourceNative.Device = null;
            surfaceImageSourceNative.Dispose();
            //DXDev.Dispose();
            //D3DDev.Dispose();
            return newSource;
        }
Пример #6
0
 /// <summary>
 /// Get the vector2 array that if draw line on that collection drawed an ellipse.
 /// </summary>
 /// <param name="rectangle"></param>
 /// <returns></returns>
 public static List <SharpDX.Vector2> GetFillEllipseArray(SharpDX.Rectangle rectangle)
 {
     return(GetFillEllipseArray(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height));
 }
Пример #7
0
 /// <summary>
 /// Releases the GDI device context (DC) associated with the current surface and allows rendering using Direct3D.
 /// </summary>
 /// <remarks>
 /// Use the ReleaseDC method to release the DC and indicate that your application has finished all GDI rendering to this surface.   You must call the ReleaseDC method before you perform addition rendering using Direct3D. Prior to resizing buffers all outstanding DCs must be released.
 /// </remarks>
 /// <param name="dirtyRect">A reference to a <see cref="SharpDX.Rectangle"/> structure that identifies the dirty region of the surface.   A dirty region is any part of the surface that you have used for GDI rendering and that you want to preserve.  This is used as a performance hint to graphics subsystem in certain scenarios.  Do not use this parameter to restrict rendering to the specified rectangular region. The area specified by the <see cref="SharpDX.Rectangle"/> will be used as a performance hint to indicate what areas have been manipulated by GDI rendering. </param>
 /// <returns>If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. </returns>
 /// <unmanaged>HRESULT IDXGISurface1::ReleaseDC([In, Optional] RECT* pDirtyRect)</unmanaged>
 public void ReleaseDC(SharpDX.Rectangle dirtyRect)
 {
     ReleaseDC_(dirtyRect);
 }
Пример #8
0
        private Glyph ImportGlyph(Factory factory, FontFace fontFace, char character, FontMetrics fontMetrics, float fontSize, FontAntiAliasMode antiAliasMode)
        {
            var indices = fontFace.GetGlyphIndices(new int[] { character });

            var metrics = fontFace.GetDesignGlyphMetrics(indices, false);
            var metric  = metrics[0];

            var width  = (float)(metric.AdvanceWidth - metric.LeftSideBearing - metric.RightSideBearing) / fontMetrics.DesignUnitsPerEm * fontSize;
            var height = (float)(metric.AdvanceHeight - metric.TopSideBearing - metric.BottomSideBearing) / fontMetrics.DesignUnitsPerEm * fontSize;

            var xOffset = (float)metric.LeftSideBearing / fontMetrics.DesignUnitsPerEm * fontSize;
            var yOffset = (float)(metric.TopSideBearing - metric.VerticalOriginY) / fontMetrics.DesignUnitsPerEm * fontSize;

            var advanceWidth  = (float)metric.AdvanceWidth / fontMetrics.DesignUnitsPerEm * fontSize;
            var advanceHeight = (float)metric.AdvanceHeight / fontMetrics.DesignUnitsPerEm * fontSize;

            var pixelWidth  = (int)Math.Ceiling(width + 4);
            var pixelHeight = (int)Math.Ceiling(height + 4);

            var matrix = SharpDX.Matrix.Identity;

            matrix.M41 = -(float)Math.Floor(xOffset) + 1;
            matrix.M42 = -(float)Math.Floor(yOffset) + 1;

            Bitmap bitmap;

            if (char.IsWhiteSpace(character))
            {
                bitmap = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
            }
            else
            {
                var glyphRun = new GlyphRun()
                {
                    FontFace   = fontFace,
                    Advances   = new[] { (float)Math.Ceiling(advanceWidth) },
                    FontSize   = fontSize,
                    BidiLevel  = 0,
                    Indices    = indices,
                    IsSideways = false,
                    Offsets    = new[] { new GlyphOffset() }
                };


                RenderingMode renderingMode;
                if (antiAliasMode != FontAntiAliasMode.Aliased)
                {
                    var rtParams = new RenderingParams(factory);
                    renderingMode = fontFace.GetRecommendedRenderingMode(fontSize, 1.0f, MeasuringMode.Natural, rtParams);
                    rtParams.Dispose();
                }
                else
                {
                    renderingMode = RenderingMode.Aliased;
                }

                using (var runAnalysis = new GlyphRunAnalysis(factory,
                                                              glyphRun,
                                                              1.0f,
                                                              matrix,
                                                              renderingMode,
                                                              MeasuringMode.Natural,
                                                              0.0f,
                                                              0.0f))
                {
                    var bounds = new SharpDX.Rectangle(0, 0, pixelWidth, pixelHeight);
                    bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);

                    if (renderingMode == RenderingMode.Aliased)
                    {
                        var texture = new byte[bounds.Width * bounds.Height];
                        runAnalysis.CreateAlphaTexture(TextureType.Aliased1x1, bounds, texture, texture.Length);
                        for (int y = 0; y < bounds.Height; y++)
                        {
                            for (int x = 0; x < bounds.Width; x++)
                            {
                                int pixelX = y * bounds.Width + x;
                                var grey   = texture[pixelX];
                                var color  = Color.FromArgb(grey, grey, grey);

                                bitmap.SetPixel(x, y, color);
                            }
                        }
                    }
                    else
                    {
                        var texture = new byte[bounds.Width * bounds.Height * 3];
                        runAnalysis.CreateAlphaTexture(TextureType.Cleartype3x1, bounds, texture, texture.Length);
                        for (int y = 0; y < bounds.Height; y++)
                        {
                            for (int x = 0; x < bounds.Width; x++)
                            {
                                int pixelX = (y * bounds.Width + x) * 3;
                                var red    = LinearToGamma(texture[pixelX]);
                                var green  = LinearToGamma(texture[pixelX + 1]);
                                var blue   = LinearToGamma(texture[pixelX + 2]);
                                var color  = Color.FromArgb(red, green, blue);

                                bitmap.SetPixel(x, y, color);
                            }
                        }
                    }
                }
            }

            var glyph = new Glyph(character, bitmap)
            {
                XOffset  = -matrix.M41,
                XAdvance = advanceWidth,
                YOffset  = -matrix.M42,
            };

            return(glyph);
        }
Пример #9
0
        private void PresentInternal(Rectangle source, Rectangle destination, IntPtr window)
        {
            this.EnsureCanPresent();
            this.EnsureWindowHandle(window);

            try
            {
                SharpDX.Rectangle dxSource = new SharpDX.Rectangle(source.Left, source.Top, source.Right, source.Bottom);
                SharpDX.Rectangle dxDestination = new SharpDX.Rectangle(destination.Left, destination.Top, destination.Right, destination.Bottom);
                this.InternalDevice.Present(dxSource, dxDestination, window);
            }
            catch (SharpDX.SharpDXException)
            {
                this.IsDeviceLost = true;
            }
        }
Пример #10
0
        public void display(VideoFrame videoFrame, Color backColor, RenderMode mode)
        {
            
            lock (renderLock)
            {
                if (device == null) return;          

                SharpDX.Result deviceStatus = device.TestCooperativeLevel();
          
                if (deviceStatus.Success == true)
                {
                    try
                    {
                        SharpDX.ColorBGRA backColorDX = new SharpDX.ColorBGRA(backColor.R,
                            backColor.G, backColor.B, backColor.A);

                        device.Clear(D3D.ClearFlags.Target, backColorDX, 1.0f, 0);

                        if (mode == RenderMode.CLEAR_SCREEN)
                        {
                            device.Present();
                            return;
                        }           

                        device.BeginScene();
                 
                        SharpDX.Rectangle videoSourceRect = new SharpDX.Rectangle();

                        if (mode == RenderMode.NORMAL)
                        {

                            videoSourceRect = new SharpDX.Rectangle(0, 0, videoFrame.Width, videoFrame.Height);

                            SharpDX.DataRectangle stream = offscreen.LockRectangle(LockFlags.None);

                            videoFrame.copyFrameDataToSurface(stream.DataPointer, stream.Pitch);

                            offscreen.UnlockRectangle();

                        }
                        else if (mode == RenderMode.PAUSED)
                        {
                            videoSourceRect = new SharpDX.Rectangle(0, 0, offscreen.Description.Width, offscreen.Description.Height);
                        }
                                          
                        videoDestRect = getVideoDestRect(backBuffer);

                        device.StretchRectangle(offscreen, videoSourceRect,
                            backBuffer, videoDestRect, D3D.TextureFilter.Linear);

                        drawText();

                        device.EndScene();
                        device.Present();

                        RenderMode = mode;

                    }
                    catch (SharpDX.SharpDXException)
                    {

                        //log.Info("lost direct3d device", e);
                        deviceStatus = device.TestCooperativeLevel();
                    }
                }

                if (deviceStatus.Code == D3D.ResultCode.DeviceLost.Result)
                {

                    //Can't Reset yet, wait for a bit

                }
                else if (deviceStatus.Code == D3D.ResultCode.DeviceNotReset.Result)
                {
                    
                    resetDevice();
                }
            }
        }
Пример #11
0
        private void drawText()
        {
            
            if (DisplayInfoText && !String.IsNullOrEmpty(InfoText))
            {
                //SharpDX.Rectangle size = infoFont.MeasureText(null, InfoText, FontDrawFlags.Left);
                //Rectangle.
                
                    //AABBGGRR
                infoFont.DrawText(null, InfoText, 5, 0, SharpDX.ColorBGRA.FromRgba(0xFFFFFFFF));
            }

            if (DisplaySubtitles && SubtitleItem != null && SubtitleItem.Lines.Count > 0)
            {                
                String lines = SubtitleItem.Lines[0];
                for(int i = 1; i < SubtitleItem.Lines.Count; i++)
                {
                    lines += "\n" + SubtitleItem.Lines[i];
                }
               
                SharpDX.Rectangle fontRect = subtitleFont.MeasureText(null, lines, FontDrawFlags.Center);
                
                fontRect.X = backBuffer.Description.Width / 2 + fontRect.X;
                fontRect.Y = videoDestRect.BottomLeft.Y - fontRect.Height - subtitleBottomMargin;
            
                SharpDX.Rectangle shadowRect = new SharpDX.Rectangle(fontRect.X + subtitleShadowOffset, fontRect.Y + subtitleShadowOffset, fontRect.Width, fontRect.Height);

                subtitleFont.DrawText(null, lines, shadowRect, FontDrawFlags.Center, SharpDX.ColorBGRA.FromRgba(0xCC000000));
                subtitleFont.DrawText(null, lines, fontRect, FontDrawFlags.Center, SharpDX.ColorBGRA.FromRgba(0xFFF9FBFB));                
            }
            
        }        
Пример #12
0
        SharpDX.Rectangle getVideoDestRect(D3D.Surface backBuffer)
        {
            Rectangle screenRect = new Rectangle(0, 0, backBuffer.Description.Width, backBuffer.Description.Height);
            Rectangle videoRect = calcOutputAspectRatio(new Rectangle(0, 0, videoWidth, videoHeight));

            Rectangle scaledVideo = Utils.stretchRectangle(videoRect, screenRect);

            Rectangle scaledCenteredVideo = Utils.centerRectangle(screenRect, scaledVideo);

            SharpDX.Rectangle scaledCenteredVideoDx = new SharpDX.Rectangle(scaledCenteredVideo.X,
                           scaledCenteredVideo.Y, scaledCenteredVideo.Width, scaledCenteredVideo.Height);

            return (scaledCenteredVideoDx);
        }
Пример #13
0
        public void createScreenShot(String screenShotName, double positionSeconds, String videoLocation, int offsetSeconds)
        {
            lock (renderLock)
            {
                if (device == null) return;

                int width = offscreen.Description.Width;
                int height = offscreen.Description.Height;

                Rectangle sourceSize = new Rectangle(0, 0, width, height);
                Rectangle destSize = calcOutputAspectRatio(sourceSize);

                if (screenShot.Description.Width != destSize.Width ||
                    screenShot.Description.Height != destSize.Height)
                {
                    Utils.removeAndDispose(ref screenShot); 

                    screenShot = D3D.Surface.CreateRenderTarget(device,
                        destSize.Width,
                        destSize.Height,
                        D3D.Format.A8R8G8B8,
                        MultisampleType.None,
                        0,
                        true);
                }

                SharpDX.Rectangle sourceSizeDX = new SharpDX.Rectangle(0, 0, sourceSize.Width, sourceSize.Height);
                SharpDX.Rectangle destSizeDX = new SharpDX.Rectangle(0, 0, destSize.Width, destSize.Height);

                device.StretchRectangle(offscreen, sourceSizeDX,
                    screenShot, destSizeDX, D3D.TextureFilter.Linear);

                SharpDX.DataRectangle stream = screenShot.LockRectangle(destSizeDX, D3D.LockFlags.ReadOnly);
                try
                {
                    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                    BitmapMetadata metaData = new BitmapMetadata("jpg");

                    UriBuilder uri = new UriBuilder(new Uri(videoLocation).AbsoluteUri);
                 
                    int seconds = (int)Math.Floor(Math.Max(positionSeconds + offsetSeconds, 0));

                    TimeSpan time = new TimeSpan(0, 0, seconds);
                    String timeString = "";

                    if (time.Days > 0)
                    {
                        timeString += time.Days + "d";
                    }

                    if(time.Hours > 0) {
                        timeString += time.Hours + "h";
                    }

                    if(time.Minutes > 0) {
                        timeString += time.Minutes + "m";
                    }

                    timeString += time.Seconds + "s";

                    uri.Query = "t=" + timeString;

                    metaData.ApplicationName = "MediaViewer v1.0";             
                    metaData.Title = uri.ToString();
                    metaData.DateTaken = DateTime.Now.ToString("R");

                    BitmapSource image = System.Windows.Media.Imaging.BitmapSource.Create(
                        destSize.Width,
                        destSize.Height,
                        96,
                        96,
                        System.Windows.Media.PixelFormats.Bgra32,
                        null,
                        stream.DataPointer,
                        height * stream.Pitch,
                        stream.Pitch
                    );

                    float scale = ImageUtils.resizeRectangle(destSize.Width, destSize.Height, Constants.MAX_THUMBNAIL_WIDTH, Constants.MAX_THUMBNAIL_HEIGHT);

                    TransformedBitmap thumbnail = new TransformedBitmap(image, new System.Windows.Media.ScaleTransform(scale,scale));
                   
                    encoder.Frames.Add(BitmapFrame.Create(image, thumbnail, metaData, null));
                                                                        
                    FileStream outputFile = new FileStream(screenShotName, FileMode.Create);
                    //encoder.QualityLevel = asyncState.JpegQuality;
                    encoder.Save(outputFile);

                    outputFile.Close();
                                  
                    System.Media.SystemSounds.Exclamation.Play();
                }
                catch (Exception e)
                {                  
                    throw new VideoPlayerException("Error creating screenshot: " + e.Message, e);
                }
                finally
                {
                    screenShot.UnlockRectangle();
                }
            }
        }
Пример #14
0
        void aquireResources()
        {

            if (videoWidth == 0 || videoHeight == 0)
            {
                throw new VideoPlayerException("Cannot instantiate D3D surface with a width or height of 0 pixels");
            }

            D3D.Format pixelFormat = makeFourCC('Y', 'V', '1', '2');

            offscreen = D3D.Surface.CreateOffscreenPlain(device,
                videoWidth,
                videoHeight,
                pixelFormat,
                D3D.Pool.Default);

            screenShot = D3D.Surface.CreateOffscreenPlain(device,
                videoWidth,
                videoHeight,
                D3D.Format.A8R8G8B8,
                D3D.Pool.Default);

            backBuffer = device.GetBackBuffer(0, 0);

            FontDescription fontDescription = new FontDescription();
            fontDescription.FaceName = "TimesNewRoman";
            fontDescription.Height = 15;         

            infoFont = new D3D.Font(device, fontDescription);

            fontDescription = new FontDescription();
            fontDescription.FaceName = "Arial";

            videoDestRect = getVideoDestRect(backBuffer);
       
            fontDescription.Height = videoDestRect.Height / 14;
             
            fontDescription.Quality = FontQuality.Antialiased;

            subtitleShadowOffset = fontDescription.Height / 18;
            subtitleBottomMargin = videoDestRect.Height / 12;

            subtitleFont = new D3D.Font(device, fontDescription);
        }
Пример #15
0
 private SharpDX.DataRectangle LockRenderTarget(Surface _renderTargetCopy, out SharpDX.Rectangle rect)
 {
     if (_requestCopy.RegionToCapture.Height > 0 && _requestCopy.RegionToCapture.Width > 0)
     {
         rect = new SharpDX.Rectangle(_requestCopy.RegionToCapture.Left, _requestCopy.RegionToCapture.Top, _requestCopy.RegionToCapture.Width, _requestCopy.RegionToCapture.Height);
     }
     else
     {
         rect = new SharpDX.Rectangle(0, 0, _renderTargetCopy.Description.Width, _renderTargetCopy.Description.Height);
     }
     return _renderTargetCopy.LockRectangle(rect, LockFlags.ReadOnly);
 }
Пример #16
0
 /// <summary>
 /// Initialzies a new instance of <see cref="BoundsAdjustmentTransform"/> class
 /// </summary>
 /// <param name="context">The effect context</param>
 /// <param name="outputRectangle">The output rectangle region used for this transformation</param>
 /// <unmanaged>HRESULT ID2D1EffectContext::CreateBoundsAdjustmentTransform([In] const RECT* outputRectangle,[Out, Fast] ID2D1BoundsAdjustmentTransform** transform)</unmanaged>
 public BoundsAdjustmentTransform(EffectContext context, SharpDX.Rectangle outputRectangle) : base(IntPtr.Zero)
 {
     context.CreateBoundsAdjustmentTransform(outputRectangle, this);
 }
Пример #17
0
        public unsafe bool TryGetCaptured(IDeviceContext context, IntRectangle clientRectangle, FrameType frameType, int colorDiffThreshold, int mostDetailedMip, out GpuRawFrame capturedFrame)
        {
            stopwatch.Restart();

            var result = texturePool.Extract(clientRectangle.Width, clientRectangle.Height);
            var resultTexture = result.Item;

            d3dDevice.GetFrontBufferData(0, d3dSurface1);
            var sdxRectangle = new Rectangle(clientRectangle.X, clientRectangle.Y, clientRectangle.X + clientRectangle.Width, clientRectangle.Y + clientRectangle.Height);

            var lockedRectangle = d3dSurface1.LockRectangle(sdxRectangle, LockFlags.ReadOnly);
            var mappedSubresource = context.Map(resultTexture, 0, MapType.WriteDiscard, MapFlags.None);
            {
                int commonRowPitch = Math.Min(mappedSubresource.RowPitch, lockedRectangle.Pitch);
                Parallel.For(0, clientRectangle.Height, i =>
                    Memory.CopyBulk(
                        (byte*)mappedSubresource.Data + i * mappedSubresource.RowPitch,
                        (byte*)lockedRectangle.DataPointer + i * lockedRectangle.Pitch,
                        commonRowPitch));
            }
            context.Unmap(resultTexture, 0);
            d3dSurface1.UnlockRectangle();

            var frameInfo = new FrameInfo(frameType, (float)Stopwatch.GetTimestamp() / Stopwatch.Frequency,
                mostDetailedMip, colorDiffThreshold, clientRectangle.Width, clientRectangle.Height,
                Cursor.Position.X - clientRectangle.X, Cursor.Position.Y - clientRectangle.Y);
            capturedFrame = new GpuRawFrame(frameInfo, result);

            stopwatch.Stop();
            statistics.OnCapture(stopwatch.Elapsed.TotalMilliseconds);

            return true;
        }
Пример #18
0
 internal static extern bool GetClientRect(IntPtr hWnd, out SharpDX.Rectangle lpRect);