public Result ProcessFrame(Action <DataBox, Texture2DDescription> processAction, int timeoutInMilliseconds = 5)
        {
            //截屏,可能失败
            using OutputDuplication duplicatedOutput = output1.DuplicateOutput(device);
            var result = duplicatedOutput.TryAcquireNextFrame(timeoutInMilliseconds, out OutputDuplicateFrameInformation duplicateFrameInformation, out SharpDX.DXGI.Resource screenResource);

            if (!result.Success)
            {
                return(result);
            }

            using Texture2D screenTexture2D = screenResource.QueryInterface <Texture2D>();

            //复制数据
            device.ImmediateContext.CopyResource(screenTexture2D, screenTexture);
            DataBox mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None);

            processAction?.Invoke(mapSource, textureDesc);

            //释放资源
            device.ImmediateContext.UnmapSubresource(screenTexture, 0);
            screenResource.Dispose();
            duplicatedOutput.ReleaseFrame();

            return(result);
        }
Beispiel #2
0
 public Wiring()
 {
     _factory = new Factory1();
     // Only works as long as you're only using one graphics card. So, TODO to change this someday.
     _adapter = _factory.GetAdapter1(0);
     // Create device from Adapter
     Device = new Device(_adapter, DeviceCreationFlags.Debug);
     // Works only with a single monitor. I'm only using one monitor, so I'm ignoring this. But, TODO.
     _output  = _adapter.GetOutput(0);
     _output1 = _output.QueryInterface <Output1>();
     Height   = _output.Description.DesktopBounds.Bottom - _output.Description.DesktopBounds.Top;
     Width    = _output.Description.DesktopBounds.Right - _output.Description.DesktopBounds.Left;
     Texture  = new Texture2D(Device, new Texture2DDescription
     {
         CpuAccessFlags    = CpuAccessFlags.Read,
         BindFlags         = BindFlags.None,
         Format            = Format.B8G8R8A8_UNorm,
         Width             = Width,
         Height            = Height,
         OptionFlags       = ResourceOptionFlags.None,
         MipLevels         = 1,
         ArraySize         = 1,
         SampleDescription = { Count = 1, Quality = 0 },
         Usage             = ResourceUsage.Staging
     });
     OutputDuplication = _output1.DuplicateOutput(Device);
 }
        private void InitDesktopDuplicator()
        {
            // Duplicate the output
            _duplicatedOutput = _output1.DuplicateOutput(_device);

            _desktopDuplicatorInvalid = false;
        }
Beispiel #4
0
        private void Initialize()
        {
            factory = new Factory1();
            //Get first adapter
            adapter = factory.GetAdapter1(0);
            //Get device from adapter
            device = new SharpDX.Direct3D11.Device(adapter);
            //Get front buffer of the adapter
            output  = adapter.GetOutput(0);
            output1 = output.QueryInterface <Output1>();

            // Width/Height of desktop to capture
            int width  = output.Description.DesktopBounds.Right;
            int height = output.Description.DesktopBounds.Bottom;

            size = new Vector2Int(width, height);

            // Create Staging texture CPU-accessible
            textureDesc = new Texture2DDescription {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = width,
                Height            = height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };
            screenTexture    = new Texture2D(device, textureDesc);
            duplicatedOutput = output1.DuplicateOutput(device);
        }
Beispiel #5
0
        private void Initialize()
        {
            _factory = new Factory1();

            var adapterOutput = _factory.Adapters1
                                .Select(adapter => new { adapter, adapter.Outputs })
                                .SelectMany(_ => _.Outputs.Select(output => new { _.adapter, output }))
                                .FirstOrDefault(_ => _.output.Description.MonitorHandle == Screen.HMon) ?? throw new InvalidOperationException();

            _device  = new Device(adapterOutput.adapter);
            _output  = adapterOutput.output;
            _adapter = adapterOutput.adapter;
            _output1 = _output.QueryInterface <Output1>();

            _screenTexture = new Texture2D(_device, new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = _width,
                Height            = _height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            });

            _duplicatedOutput = _output1.DuplicateOutput(_device);
        }
Beispiel #6
0
        /// <summary>
        /// Init some variables one times to spend execution time.
        /// </summary>
        public DirectX()
        {
            try
            {
                factory = new Factory1();
                adapter = factory.GetAdapter1(numAdapter);
                device  = new Device(adapter);
                output  = adapter.GetOutput(numOutput);
                output1 = output.QueryInterface <Output1>();
                // get screen wize

                textureDesc = new Texture2DDescription
                {
                    CpuAccessFlags = CpuAccessFlags.Read,
                    BindFlags      = BindFlags.None,
                    Format         = Format.B8G8R8A8_UNorm,
                    Width          = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Right - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Left,
                    Height         = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Bottom - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Top,

                    OptionFlags       = ResourceOptionFlags.None,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Staging
                };

                screenTexture    = new Texture2D(device, textureDesc);
                duplicatedOutput = output1.DuplicateOutput(device);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #7
0
        public void Init()
        {
            lock (_syncLock)
            {
                try
                {
                    _acquireTask?.Wait();
                }
                catch { }

                _acquireTask = null;
                _deskDupl?.Dispose();

                try
                {
                    _deskDupl = _output.DuplicateOutput(_device);
                }
                catch (SharpDXException e) when(e.Descriptor == ResultCode.NotCurrentlyAvailable)
                {
                    throw new Exception(
                              "There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.",
                              e);
                }
                catch (SharpDXException e) when(e.Descriptor == ResultCode.Unsupported)
                {
                    throw new NotSupportedException(
                              "Desktop Duplication is not supported on this system.\nIf you have multiple graphic cards, try running Captura on integrated graphics.",
                              e);
                }
            }
        }
Beispiel #8
0
        public SharpDX.DataStream CaptureScreen()
        {
            // try to get duplicated frame within given time
            try
            {
                OutputDuplicateFrameInformation duplicateFrameInformation;
                duplicatedOutput.AcquireNextFrame(1000, out duplicateFrameInformation, out screenResource);

                // copy resource into memory that can be accessed by the CPU
                device.ImmediateContext.CopyResource(screenResource.QueryInterface <SharpDX.Direct3D11.Resource>(), screenTexture);
                // cast from texture to surface, so we can access its bytes
                screenSurface = screenTexture.QueryInterface <SharpDX.DXGI.Surface>();

                // map the resource to access it
                screenSurface.Map(MapFlags.Read, out dataStream);

                // seek within the stream and read one byte
                //dataStream.Position = 4;
                //dataStream.ReadByte();

                // free resources
                //dataStream.Close();
                screenSurface.Unmap();
                screenSurface.Dispose();
                screenResource.Dispose();
                duplicatedOutput.ReleaseFrame();
                return(dataStream);
            }
            catch (SharpDX.SharpDXException e)
            {
                device  = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware);
                factory = new Factory1();
                // creating CPU-accessible texture resource
                texdes = new SharpDX.Direct3D11.Texture2DDescription();
                texdes.CpuAccessFlags            = SharpDX.Direct3D11.CpuAccessFlags.Read;
                texdes.BindFlags                 = SharpDX.Direct3D11.BindFlags.None;
                texdes.Format                    = Format.B8G8R8A8_UNorm;
                texdes.Height                    = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Height;
                texdes.Width                     = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Width;
                texdes.OptionFlags               = SharpDX.Direct3D11.ResourceOptionFlags.None;
                texdes.MipLevels                 = 1;
                texdes.ArraySize                 = 1;
                texdes.SampleDescription.Count   = 1;
                texdes.SampleDescription.Quality = 0;
                texdes.Usage                     = SharpDX.Direct3D11.ResourceUsage.Staging;
                screenTexture                    = new SharpDX.Direct3D11.Texture2D(device, texdes);

                // duplicate output stuff
                output = new Output1(factory.Adapters1[numAdapter].Outputs[numOutput].NativePointer);
                try
                {
                    duplicatedOutput = output.DuplicateOutput(device);
                }
                catch { }
                return(CaptureScreen());
            }
        }
Beispiel #9
0
        /// <summary>
        /// Duplicates the output of the specified monitor on the specified graphics adapter.
        /// </summary>
        /// <param name="whichGraphicsCardAdapter">The adapter which contains the desired outputs.</param>
        /// <param name="whichOutputDevice">The output device to duplicate (i.e. monitor). Begins with zero, which seems to correspond to the primary monitor.</param>
        public DesktopDuplicator(int whichGraphicsCardAdapter, int whichOutputDevice, VSyncLevel vSync)
        {
            this.vSync = vSync;
            this.mWhichOutputDevice = whichOutputDevice;
            Adapter1 adapter;

            try
            {
                adapter = new Factory1().GetAdapter1(whichGraphicsCardAdapter);
            }
            catch (SharpDXException)
            {
                throw new DesktopDuplicationException("Could not find the specified graphics card adapter.");
            }
            this.mDevice = new Device(adapter, DeviceCreationFlags.SingleThreaded | DeviceCreationFlags.PreventAlteringLayerSettingsFromRegistry);

            Output output;

            try
            {
                output = adapter.GetOutput(whichOutputDevice);
            }
            catch (SharpDXException)
            {
                throw new DesktopDuplicationException("Could not find the specified output device.");
            }
            outputStream             = output.QueryInterface <Output1>();
            this.mOutputDescription  = output.Description;
            this.mTextureDescription = new Texture2DDescription()
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = this.mOutputDescription.DesktopBounds.Right,
                Height            = this.mOutputDescription.DesktopBounds.Bottom,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };

            try
            {
                this.mDeskDuplication = outputStream.DuplicateOutput(mDevice);
            }
            catch (SharpDXException err)
            {
                if (err.ResultCode.Code == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable.Result.Code)
                {
                    throw new DesktopDuplicationException("There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.");
                }
            }
        }
Beispiel #10
0
        public void Init()
        {
            Dispose();

            factory = new Factory1();

            //Get first adapter
            adapter = factory.Adapters1.FirstOrDefault(x => x.Outputs.Length > 0);
            //Get device from adapter
            device = new SharpDX.Direct3D11.Device(adapter);
            //Get front buffer of the adapter
            if (adapter.GetOutputCount() < SelectedScreen + 1)
            {
                SelectedScreen = 0;
            }
            output  = adapter.GetOutput(SelectedScreen);
            output1 = output.QueryInterface <Output1>();

            // Width/Height of desktop to capture
            var bounds    = output1.Description.DesktopBounds;
            var newWidth  = bounds.Right - bounds.Left;
            var newHeight = bounds.Bottom - bounds.Top;

            CurrentScreenBounds = new Rectangle(bounds.Left, bounds.Top, newWidth, newHeight);
            if (newWidth != width || newHeight != height)
            {
                ScreenChanged?.Invoke(this, CurrentScreenBounds);
            }
            width  = newWidth;
            height = newHeight;

            CurrentFrame  = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            PreviousFrame = new Bitmap(width, height, PixelFormat.Format32bppArgb);

            // Create Staging texture CPU-accessible
            textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = width,
                Height            = height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };
            screenTexture    = new Texture2D(device, textureDesc);
            duplicatedOutput = output1.DuplicateOutput(device);

            NeedsInit = false;
        }
Beispiel #11
0
        public DirectScreenshot(GPGPU gpu, int screenWidth, int screenHeight)
        {
            OutputFileName = "ScreenCapture.bmp";
            const int numAdapter = 0;
            const int numOutput  = 0;

            _gpu      = gpu;
            rgbValues = gpu.Allocate <GPUColorBGRA>(screenWidth * screenHeight);
            // Create DXGI Factory1
            factory = new Factory1();
            adapter = factory.GetAdapter1(numAdapter);

            // Create device from Adapter
            device = new Device(adapter);

            // Get DXGI.Output
            output  = adapter.GetOutput(numOutput);
            output1 = output.QueryInterface <Output1>();

            // Width/Height of desktop to capture
            width  = screenWidth;
            height = screenHeight;


            // Create Staging texture CPU-accessible
            textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = width,
                Height            = height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };
            screenTexture = new Texture2D(device, textureDesc);

            // Duplicate the output
            duplicatedOutput = output1.DuplicateOutput(device);

            var screenResource = BeginCapture(out var pp);

            screenResource.Dispose();
            duplicatedOutput.ReleaseFrame();
        }
 private OutputDuplication CreateOutputDuplication(Output1 output1)
 {
     try
     {
         return(output1.DuplicateOutput(_device));
     }
     catch (SharpDXException ex)
     {
         if (ex.ResultCode.Code == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable.Result.Code)
         {
             throw new DesktopDuplicationException(
                       "There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.");
         }
         throw;
     }
 }
        /// <summary>
        /// Init some variables one times to spend execution time.
        /// </summary>
        public DirectX()
        {
            try
            {
                factory = new Factory1();
                adapter = factory.GetAdapter1(numAdapter);
                device  = new Device(adapter);
                output  = adapter.GetOutput(numOutput);
                output1 = output.QueryInterface <Output1>();
                // get screen wize

                textureDesc = new Texture2DDescription
                {
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    BindFlags         = BindFlags.None,
                    Format            = Format.B8G8R8A8_UNorm,
                    Width             = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Right - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Left,
                    Height            = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Bottom - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Top,
                    OptionFlags       = ResourceOptionFlags.None,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Staging
                };

                screenTexture = new Texture2D(device, textureDesc);
                try
                {
                    duplicatedOutput = output1.DuplicateOutput(device);
                }
                catch (SharpDXException e)
                {
                    if (e.ResultCode.Code == SharpDX.DXGI.ResultCode.Unsupported.Result.Code)
                    {
                        throw new System.ApplicationException("Your system does not support DirectX 11.2 (normally on windows 7). Please use 'Use GDI Capture' option to prevent this error!");
                    }
                    else
                    {
                        throw e;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #14
0
 private void Reset()
 {
     using (Factory1 DXGIfactory = new Factory1())
     {
         Adapter1 adapter;
         if (DXGIfactory.Adapters1[0].Outputs.Length == 0)
         {
             adapter = DXGIfactory.Adapters1[1];
         }
         else
         {
             adapter = DXGIfactory.Adapters1[0];
         }
         Output1 output = adapter.Outputs[0].QueryInterface <Output1>();
         this.duplicatedOutput = output.DuplicateOutput(this.device);
     }
 }
Beispiel #15
0
        /*Multi-Thread Variable*/

        /// <summary>
        /// Create LocalCapture to capture screen (by DXGI.)
        /// </summary>
        /// <param name="bitmapBuffer">Communication pipe with other threads. It stores some processing Mat and some unused Mat</param>
        /// <param name="numOutput"># of output device (i.e. monitor).</param>
        /// <param name="numAdapter"># of output adapter (i.e. iGPU). </param>
        public LocalCapture(BitmapBuffer bitmapBuffer, int numOutput = 0, int numAdapter = 0)
        {
            // Create DXGI Factory1
            factory = new Factory1();
            adapter = factory.GetAdapter1(numAdapter);

            // Create device from Adapter
            device = new Device(adapter);

            // Get DXGI.Output
            output  = adapter.GetOutput(numOutput);
            output1 = output.QueryInterface <Output1>();


            // Width/Height of desktop to capture
            width  = ((Rectangle)output.Description.DesktopBounds).Width;
            height = ((Rectangle)output.Description.DesktopBounds).Height;

            // Create Staging texture CPU-accessible
            textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = width,
                Height            = height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };
            screenTexture = new Texture2D(device, textureDesc);

            // Duplicate the output
            duplicatedOutput = output1.DuplicateOutput(device);

            //Create enough UnusedMat
            for (int i = 0; i < PreCreateMatCount; ++i)
            {
                bitmapBuffer.PushUnusedMat(CreateSuitableMat());
            }

            //Save the buffer
            this.bitmapBuffer = bitmapBuffer;
        }
Beispiel #16
0
        public CompressScreen(bool _dxMode)
        {
            this.screenBounds = Screen.PrimaryScreen.Bounds;

            prev = new Bitmap(screenBounds.Width, screenBounds.Height, PixelFormat.Format32bppArgb);
            cur  = new Bitmap(screenBounds.Width, screenBounds.Height, PixelFormat.Format32bppArgb);

            using (Graphics g = Graphics.FromImage(prev))
            {
                g.Clear(Color.Black);
            }

            compressionBuffer = new byte[screenBounds.Width * screenBounds.Height * 4];

            int backBufSize = LZ4.LZ4Codec.MaximumOutputLength(compressionBuffer.Length) + 4;

            compressedScreen = new CompressedScreen(backBufSize);

            //directX Constructor

            if (_dxMode == true)
            {
                factory     = new Factory1();
                adapter     = factory.GetAdapter1(0);
                device      = new SharpDX.Direct3D11.Device(adapter);
                output      = adapter.GetOutput(0);
                output1     = output.QueryInterface <Output1>();
                textureDesc = new Texture2DDescription
                {
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    BindFlags         = BindFlags.None,
                    Format            = Format.B8G8R8A8_UNorm,
                    Width             = screenBounds.Width,
                    Height            = screenBounds.Height,
                    OptionFlags       = ResourceOptionFlags.None,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Staging
                };
                screenTexture    = new Texture2D(device, textureDesc);
                duplicatedOutput = output1.DuplicateOutput(device);
            }
        }
            public DXSnapperInput(Factory1 factory, int adapterIndex, int outputIndex, Rectangle captureRectangle)
            {
                _adapter = factory.GetAdapter1(adapterIndex);
                _device  = new SharpDX.Direct3D11.Device(_adapter);
                _output  = _adapter.GetOutput(outputIndex);
                var outputBounds = _output.Description.DesktopBounds.ToGDIRect();

                var intersection = Rectangle.Intersect(outputBounds, captureRectangle);

                if (intersection.IsEmpty)
                {
                    Dispose();
                    throw new ArgumentOutOfRangeException(nameof(captureRectangle), $"Output {outputIndex} for adapter {adapterIndex} {FormatRectangle(outputBounds)} doesn't intersect with capture rectangle {FormatRectangle(captureRectangle)}");
                }

                _textureDescription = new Texture2DDescription
                {
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    BindFlags         = BindFlags.None,
                    Format            = sourcePixelFormat,
                    Height            = outputBounds.Height,
                    Width             = outputBounds.Width,
                    OptionFlags       = ResourceOptionFlags.None,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription =
                    {
                        Count   = 1,
                        Quality = 0
                    },
                    Usage = ResourceUsage.Staging,
                };
                _screenTexture    = new Texture2D(_device, _textureDescription);
                _output1          = _output.QueryInterface <Output1>();
                _duplicatedOutput = _output1.DuplicateOutput(_device);

                _destXOffset   = intersection.Left - captureRectangle.Left;
                _destYOffset   = intersection.Top - captureRectangle.Top;
                _sourceXOffset = intersection.Left - outputBounds.Left;
                _sourceYOffset = intersection.Top - outputBounds.Top;
                _width         = intersection.Width;
                _height        = intersection.Height;
            }
Beispiel #18
0
        public DesktopDuplicator(Adapter1 adapter, Output1 output, Rectangle Rect)
        {
            Global.logger.Info("Starting desktop duplicator");
            _rect   = Rect;
            _device = new Device(adapter);
            var textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = _rect.Width,
                Height            = _rect.Height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };

            _deskDupl            = output.DuplicateOutput(_device);
            _desktopImageTexture = new Texture2D(_device, textureDesc);
        }
        public DXScreenCapture()
        {
            // Create DXGI Factory1
            if (device == null)
            {
                factory = new Factory1();
                adapter = factory.GetAdapter1(numAdapter);

                // Create device from Adapter
                device = new Device(adapter);
            }
            if (output1 == null)
            {
                // Get DXGI.Output
                var output = adapter.GetOutput(numOutput);
                output1 = output.QueryInterface <Output1>();

                // Duplicate the output
                duplicatedOutput = output1.DuplicateOutput(device);
            }

            // Create Staging texture CPU-accessible
            textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = width,
                Height            = height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };

            screenTexture = new Texture2D(device, textureDesc);
        }
Beispiel #20
0
        public DXGIScreenshot()
        {
            // Create DXGI Factory1
            factory = new Factory1();
            adapter = factory.GetAdapter1(numAdapter);

            // Create device from Adapter
            device = new Device(adapter);

            // Get DXGI.Output
            output  = adapter.GetOutput(numOutput);
            output1 = output.QueryInterface <Output1>();

            // Width/Height of desktop to capture
            this.Width  = ((Rectangle)output.Description.DesktopBounds).Width;
            this.Height = ((Rectangle)output.Description.DesktopBounds).Height;

            // Create Staging texture CPU-accessible
            var textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = Width,
                Height            = Height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };

            screenTexture = new Texture2D(device, textureDesc);

            // Duplicate the output
            duplicatedOutput = output1.DuplicateOutput(device);
        }
Beispiel #21
0
        public DesktopDuplicator(Rectangle Rect, bool IncludeCursor, Adapter1 Adapter, Output1 Output)
        {
            _rect          = Rect;
            _includeCursor = IncludeCursor;

            _device = new Device(Adapter);

            var textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = _rect.Width,
                Height            = _rect.Height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };

            try
            {
                _deskDupl = Output.DuplicateOutput(_device);
            }
            catch (SharpDXException e) when(e.Descriptor == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable)
            {
                throw new Exception("There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.", e);
            }
            catch (SharpDXException e) when(e.Descriptor == SharpDX.DXGI.ResultCode.Unsupported)
            {
                throw new NotSupportedException("Desktop Duplication is not supported on this system.\nIf you have multiple graphic cards, try running Captura on integrated graphics.", e);
            }

            _desktopImageTexture = new Texture2D(_device, textureDesc);
        }
Beispiel #22
0
        public Dx11ScreenCapture()
        {
            // create device and factory
            device  = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware);
            factory = new Factory1();
            // creating CPU-accessible texture resource
            texdes = new SharpDX.Direct3D11.Texture2DDescription();
            texdes.CpuAccessFlags            = SharpDX.Direct3D11.CpuAccessFlags.Read;
            texdes.BindFlags                 = SharpDX.Direct3D11.BindFlags.None;
            texdes.Format                    = Format.B8G8R8A8_UNorm;
            texdes.Height                    = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Height;
            texdes.Width                     = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Width;
            texdes.OptionFlags               = SharpDX.Direct3D11.ResourceOptionFlags.None;
            texdes.MipLevels                 = 1;
            texdes.ArraySize                 = 1;
            texdes.SampleDescription.Count   = 1;
            texdes.SampleDescription.Quality = 0;
            texdes.Usage                     = SharpDX.Direct3D11.ResourceUsage.Staging;
            screenTexture                    = new SharpDX.Direct3D11.Texture2D(device, texdes);

            // duplicate output stuff
            output           = new Output1(factory.Adapters1[numAdapter].Outputs[numOutput].NativePointer);
            duplicatedOutput = output.DuplicateOutput(device);
        }
        public SC_SharpDX_ScreenCapture(int adapter, int numOutput, SharpDX.Direct3D11.Device device_)
        {
            //_textureByteArray[0] = 0;
            imageptrList      = new IntPtr[num_cols * num_rows];
            _frameCaptureData = new SC_SharpDX_ScreenFrame();

            arrayOfTexture2DFrac = new Texture2D[num_cols * num_rows];

            pastearray    = new int[num_cols * num_rows];
            pastearrayTwo = new int[num_cols * num_rows];

            arrayOfBytesTwo = new byte[_textureDescriptionFinal.Width * _textureDescriptionFinal.Height];

            _lastShaderResourceViewArray = new ShaderResourceView[num_cols * num_rows];
            _ShaderResourceViewArray     = new ShaderResourceView[num_cols * num_rows];


            _numAdapter = adapter;
            _numOutput  = numOutput;


            try
            {
                using (var _factory = new SharpDX.DXGI.Factory1())
                {
                    this._adapter = _factory.GetAdapter1(_numAdapter);
                }
            }
            catch (SharpDXException ex)
            {
                Console.WriteLine(ex.ToString());
                return;
            }

            try
            {
                //this._device = new Device(_adapter);
                //this._device = sccsVD4VE_LightNWithoutVr.SC_Console_DIRECTX._dxDevice.Device;

                this._device = device_;
            }
            catch (SharpDXException ex)
            {
                Console.WriteLine(ex.ToString());
                return;
            }

            try
            {
                //initializeOutput();
                using (var _output = _adapter.GetOutput(_numOutput))
                {
                    // Width/Height of desktop to capture
                    //getDesktopBoundaries();
                    _width  = ((SharpDX.Rectangle)_output.Description.DesktopBounds).Width;
                    _height = ((SharpDX.Rectangle)_output.Description.DesktopBounds).Height;
                    _frameCaptureData.width  = _width;
                    _frameCaptureData.height = _height;
                    this._output1            = _output.QueryInterface <Output1>();
                }
            }
            catch (SharpDXException ex)
            {
                Console.WriteLine(ex.ToString());
                return;
            }

            try
            {
                //duplicateOutput();
                this._outputDuplication = _output1.DuplicateOutput(_device);
            }
            catch (SharpDXException ex)
            {
                Console.WriteLine(ex.ToString());
                return;
            }

            try
            {
                //getTextureDescription();
                this._textureDescription = new Texture2DDescription
                {
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    BindFlags         = BindFlags.None,//BindFlags.None, //| BindFlags.RenderTarget
                    Format            = Format.B8G8R8A8_UNorm,
                    Width             = _width,
                    Height            = _height,
                    OptionFlags       = ResourceOptionFlags.None,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Staging
                };

                this._textureDescriptionFinal = new Texture2DDescription
                {
                    CpuAccessFlags    = CpuAccessFlags.None,
                    BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget,
                    Format            = Format.B8G8R8A8_UNorm,
                    Width             = _width,
                    Height            = _height,
                    OptionFlags       = ResourceOptionFlags.GenerateMipMaps,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Default
                };



                wid = _textureDescriptionFinal.Width / num_cols;
                hgt = _textureDescriptionFinal.Height / num_rows;

                /*this._textureDescriptionFinalFrac = new Texture2DDescription
                 * {
                 *  CpuAccessFlags = CpuAccessFlags.None,
                 *  BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget,
                 *  Format = Format.B8G8R8A8_UNorm,
                 *  Width = wid,
                 *  Height = hgt,
                 *  OptionFlags = ResourceOptionFlags.GenerateMipMaps,
                 *  MipLevels = 1,
                 *  ArraySize = 1,
                 *  SampleDescription = { Count = 1, Quality = 0 },
                 *  Usage = ResourceUsage.Default
                 * };*/

                this._textureDescriptionFinalFrac = new Texture2DDescription
                {
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    BindFlags         = BindFlags.None,//BindFlags.None, //| BindFlags.RenderTarget
                    Format            = Format.B8G8R8A8_UNorm,
                    Width             = wid,
                    Height            = hgt,
                    OptionFlags       = ResourceOptionFlags.None,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Staging
                };



                piece     = new Bitmap(wid, hgt);
                gr        = Graphics.FromImage(piece);
                dest_rect = new System.Drawing.Rectangle(0, 0, wid, hgt);

                strider = wid * 4;

                for (int i = 0; i < arrayOfImage.Length; i++)
                {
                    arrayOfImage[i] = new int[wid * hgt * 4];
                }

                for (int i = 0; i < arrayOfBytes.Length; i++)
                {
                    arrayOfBytes[i] = new byte[wid * hgt * 4];
                }


                piece     = new System.Drawing.Bitmap(wid, hgt);
                dest_rect = new System.Drawing.Rectangle(0, 0, wid, hgt);

                //int num_rows = _textureDescriptionFinal.Height / hgt;
                //int num_cols = _textureDescriptionFinal.Width / wid;
                source_rect = new System.Drawing.Rectangle(0, 0, wid, hgt);


                for (int tex2D = 0; tex2D < 10 * 10; tex2D++)
                {
                    arrayOfTexture2DFrac[tex2D] = new Texture2D(_device, _textureDescriptionFinalFrac);
                }
            }
            catch (SharpDXException ex)
            {
                Console.WriteLine(ex.ToString());
                return;
            }

            _texture2D      = new Texture2D(_device, _textureDescription);
            _texture2DFinal = new Texture2D(_device, _textureDescriptionFinal);

            resourceViewDescription = new ShaderResourceViewDescription
            {
                Format    = _texture2DFinal.Description.Format,
                Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource
                {
                    MipLevels       = -1,
                    MostDetailedMip = 0
                }
            };

            _bitmap = new System.Drawing.Bitmap(_width, _height, PixelFormat.Format32bppArgb);
            var boundsRect = new System.Drawing.Rectangle(0, 0, _width, _height);
            var bmpData    = _bitmap.LockBits(boundsRect, ImageLockMode.ReadOnly, _bitmap.PixelFormat);

            _bytesTotal = Math.Abs(bmpData.Stride) * _bitmap.Height;
            _bitmap.UnlockBits(bmpData);
            _textureByteArray = new byte[_bytesTotal];



            /*try
             * {
             *
             * }
             * catch (SharpDXException ex)
             * {
             *  Console.WriteLine(ex.ToString());
             *  return;
             * }*/
        }
Beispiel #24
0
        internal void Initialize()
        {
            adapter = DeviceEnumerator.GetAdapter(int.Parse(Settings.Model.AdapterId));
            output  = adapter.GetOutput1(Settings.Model.DisplayId);

            var scale        = Settings.Model.Scale;
            var bounds       = output.Description.DesktopBounds;
            var outputWidth  = bounds.Right - bounds.Left;
            var outputHeight = bounds.Bottom - bounds.Top;

            renderBounds = new Rectangle(0, 0, outputWidth / scale, outputHeight / scale);
            fpsLocation  = new RectangleF(renderBounds.Width - 92, renderBounds.Height - 19, renderBounds.Width, renderBounds.Height);

            device = new Device(adapter, DeviceCreationFlags.PreventAlteringLayerSettingsFromRegistry
                                | DeviceCreationFlags.SingleThreaded
                                | DeviceCreationFlags.BgraSupport);

            gpuTexture = new Texture2D(device, new TextureDescription()
            {
                CpuAccessFlags    = CpuAccessFlags.None,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = outputWidth,
                Height            = outputHeight,
                OptionFlags       = ResourceOptionFlags.GenerateMipMaps,
                MipLevels         = (int)Math.Log2(scale) + 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Default
            });

            cpuTexture = new Texture2D(device, new TextureDescription()
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = renderBounds.Width,
                Height            = renderBounds.Height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            });

            renderDescription = new SwapChainDescription1()
            {
                BufferCount       = 1,
                Width             = renderBounds.Width,
                Stereo            = false,
                Height            = renderBounds.Height,
                Format            = Format.B8G8R8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.Discard
            };

            memBuffer       = new byte[renderBounds.Height * renderBounds.Width * 4];
            pinnedMemBuffer = GCHandle.Alloc(memBuffer, GCHandleType.Pinned);
            ptrMemBuffer    = pinnedMemBuffer.AddrOfPinnedObject();

            generateRecPoints();
            Settings.Model.PropertyChanged += LedsChanged;

            duplicator = output.DuplicateOutput(device);
            scaler     = new ShaderResourceView(device, gpuTexture);
        }
Beispiel #25
0
        public ProjectionMappingSample(string[] args)
        {
            // load ensemble.xml
            string path      = args[0];
            string directory = Path.GetDirectoryName(path);

            ensemble = RoomAliveToolkit.ProjectorCameraEnsemble.FromFile(path);

            // create d3d device
            var factory = new Factory1();
            var adapter = factory.Adapters[0];

            // When using DeviceCreationFlags.Debug on Windows 10, ensure that "Graphics Tools" are installed via Settings/System/Apps & features/Manage optional features.
            // Also, when debugging in VS, "Enable native code debugging" must be selected on the project.
            device = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.None);

            // shaders
            depthAndColorShader       = new DepthAndColorShader(device);
            projectiveTexturingShader = new ProjectiveTexturingShader(device);
            passThroughShader         = new PassThrough(device, userViewTextureWidth, userViewTextureHeight);
            radialWobbleShader        = new RadialWobble(device, userViewTextureWidth, userViewTextureHeight);
            meshShader      = new MeshShader(device);
            fromUIntPS      = new FromUIntPS(device, Kinect2Calibration.depthImageWidth, Kinect2Calibration.depthImageHeight);
            bilateralFilter = new BilateralFilter(device, Kinect2Calibration.depthImageWidth, Kinect2Calibration.depthImageHeight);

            // create device objects for each camera
            foreach (var camera in ensemble.cameras)
            {
                cameraDeviceResources[camera] = new CameraDeviceResource(device, camera, renderLock, directory);
            }

            // one user view
            // user view render target, depth buffer, viewport for user view
            var userViewTextureDesc = new Texture2DDescription()
            {
                Width             = userViewTextureWidth,
                Height            = userViewTextureHeight,
                MipLevels         = 1, // revisit this; we may benefit from mipmapping?
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
            };
            var userViewRenderTarget = new Texture2D(device, userViewTextureDesc);

            userViewRenderTargetView = new RenderTargetView(device, userViewRenderTarget);
            userViewSRV = new ShaderResourceView(device, userViewRenderTarget);

            var filteredUserViewRenderTarget = new Texture2D(device, userViewTextureDesc);

            filteredUserViewRenderTargetView = new RenderTargetView(device, filteredUserViewRenderTarget);
            filteredUserViewSRV = new ShaderResourceView(device, filteredUserViewRenderTarget);

            // user view depth buffer
            var userViewDpethBufferDesc = new Texture2DDescription()
            {
                Width             = userViewTextureWidth,
                Height            = userViewTextureHeight,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.D32_Float, // necessary?
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None
            };
            var userViewDepthStencil = new Texture2D(device, userViewDpethBufferDesc);

            userViewDepthStencilView = new DepthStencilView(device, userViewDepthStencil);

            // user view viewport
            userViewViewport = new Viewport(0, 0, userViewTextureWidth, userViewTextureHeight, 0f, 1f);

            // create a form for each projector
            foreach (var projector in ensemble.projectors)
            {
                var form = new ProjectorForm(factory, device, renderLock, projector);
                if (fullScreenEnabled)
                {
                    form.FullScreen = fullScreenEnabled; // TODO: fix this so can be called after Show
                }
                form.Show();
                projectorForms.Add(form);
            }

            // example 3d object
            var mesh = Mesh.FromOBJFile("Content/FloorPlan.obj");

            meshDeviceResources = new MeshDeviceResources(device, imagingFactory, mesh);

            // desktop duplication
            var output = new Output1(factory.Adapters[0].Outputs[0].NativePointer); // TODO: change adapter and output number

            outputDuplication = output.DuplicateOutput(device);


            userViewForm      = new Form1(factory, device, renderLock);
            userViewForm.Text = "User View";
            userViewForm.Show();


            userViewForm.videoPanel1.MouseClick += videoPanel1_MouseClick;

            // connect to local camera to acquire head position
            if (localHeadTrackingEnabled)
            {
                localKinectSensor = KinectSensor.GetDefault();
                bodyFrameReader   = localKinectSensor.BodyFrameSource.OpenReader();
                localKinectSensor.Open();
                Console.WriteLine("connected to local camera");
                new System.Threading.Thread(LocalBodyLoop).Start();
            }


            if (liveDepthEnabled)
            {
                foreach (var cameraDeviceResource in cameraDeviceResources.Values)
                {
                    cameraDeviceResource.StartLive();
                }
            }


            new System.Threading.Thread(RenderLoop).Start();
        }
Beispiel #26
0
        public void Start()
        {
            _isRunning = true;

            const int numAdapter = 0;
            const int numOutput  = 0;

            Factory1 factory = new Factory1();
            Adapter1 adapter = factory.GetAdapter1(numAdapter);
            Device   device  = new Device(adapter);

            Output  output  = adapter.GetOutput(numOutput);
            Output1 output1 = output.QueryInterface <Output1>();

            int width  = ((Rectangle)output.Description.DesktopBounds).Width;
            int height = ((Rectangle)output.Description.DesktopBounds).Height;

            Texture2DDescription textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = width,
                Height            = height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };
            Texture2D screenTexture = new Texture2D(device, textureDesc);

            OutputDuplication duplicatedOutput = output1.DuplicateOutput(device);

            while (_isRunning)
            {
                try
                {
                    Resource screenResource;

                    duplicatedOutput.TryAcquireNextFrame(10000, out _, out screenResource);

                    using Texture2D screenTexture2D = screenResource.QueryInterface <Texture2D>();

                    device.ImmediateContext.CopyResource(screenTexture2D, screenTexture);

                    DataBox mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, MapFlags.None);

                    int radius = 2;

                    unsafe
                    {
                        uint *sourcePtr = (uint *)mapSource.DataPointer;
                        for (int i = 0; i < _ledDevice.LedStrips.Count; i++)
                        {
                            // Right, Top, Left, Bottom
                            for (int p = 0; p < 10; p++)
                            {
                                Color color;
                                if (i == 0)
                                {
                                    color = Screen.GetAverageColor(sourcePtr, 1919, MathExt.Clamp(1080 - (108 * p), 0, 1079), radius);
                                }
                                else if (i == 1)
                                {
                                    color = Screen.GetAverageColor(sourcePtr, MathExt.Clamp(1620 - (300 + (132 * p)), 300, 1620), 0, radius);
                                }
                                else if (i == 2)
                                {
                                    color = Screen.GetAverageColor(sourcePtr, 0, MathExt.Clamp(108 * p, 0, 1079), radius);
                                }
                                else
                                {
                                    color = Screen.GetAverageColor(sourcePtr, MathExt.Clamp(300 + (132 * p), 300, 1620), 1079, radius);
                                }

                                _ledDevice.LedStrips[i].Leds[p].SetColor(_ledDevice.LedStrips[i].Leds[p].Color.Average(color));
                            }
                        }
                    }

                    device.ImmediateContext.UnmapSubresource(screenTexture, 0);
                    screenResource.Dispose();
                    duplicatedOutput.ReleaseFrame();
                }
                catch (Exception e)
                {
                    Console.WriteLine($"An error was caught: {e.Message}");
                }
                finally
                {
                }
            }
        }
Beispiel #27
0
 /// <summary>
 /// Destroys and re-recreates the duplicatedOutput object, then returns true if successful. This causes the next captured frame to cover the whole desktop.
 /// </summary>
 /// <returns></returns>
 public bool ResetOutputDuplicator()
 {
     DestroyOutputDuplicator();
     Try.Swallow(() => { duplicatedOutput = screen.DuplicateOutput(device); });
     return(duplicatedOutput != null);
 }
        /// <summary>
        /// Changes the capture settings.
        /// </summary>
        /// <param name="newSettings">The new settings.</param>
        /// <returns></returns>
        public HRESULT ChangeCaptureSettings(CaptureSettings newSettings)
        {
            lock (m_Filter.FilterLock)
            {
                if (m_Filter.IsActive)
                {
                    return(VFW_E_WRONG_STATE);
                }

                m_CaptureSettings = newSettings;

                if (m_Adapter != null)
                {
                    m_Adapter.Dispose();
                }
                m_Adapter = m_Factory.GetAdapter1(m_CaptureSettings.m_Adapter);

                if (m_Adapter == null)
                {
                    return(E_POINTER);
                }

                if (m_Device != null)
                {
                    m_Device.Dispose();
                }
                m_Device = new Device(m_Adapter);

                if (m_Device == null)
                {
                    return(E_POINTER);
                }

                if (m_Output != null)
                {
                    m_Output.Dispose();
                }
                m_Output = m_Adapter.GetOutput(m_CaptureSettings.m_Output).QueryInterface <Output1>();

                if (m_Output == null)
                {
                    return(E_POINTER);
                }

                Texture2DDescription textureDesc = new Texture2DDescription
                {
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    BindFlags         = BindFlags.None,
                    Format            = Format.B8G8R8A8_UNorm,
                    Width             = m_nWidth,
                    Height            = m_nHeight,
                    OptionFlags       = ResourceOptionFlags.None,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Staging
                };

                if (m_ScreenTexture != null)
                {
                    m_ScreenTexture.Dispose();
                }
                m_ScreenTexture = new Texture2D(m_Device, textureDesc);

                if (m_ScreenTexture == null)
                {
                    return(E_POINTER);
                }

                if (m_DuplicatedOutput != null)
                {
                    m_DuplicatedOutput.Dispose();
                }
                m_DuplicatedOutput = m_Output.DuplicateOutput(m_Device);

                if (m_DuplicatedOutput == null)
                {
                    return(E_POINTER);
                }

                return((HRESULT)ReconnectPin());
            }
        }
Beispiel #29
0
    public void Start()
    {
        isRun = true;

        Factory1 factory = new Factory1();
        Adapter1 adapter = factory.GetAdapter1(0);

        SharpDX.Direct3D11.Device device = new SharpDX.Direct3D11.Device(adapter);
        Output  output  = adapter.GetOutput(0);
        Output1 output1 = output.QueryInterface <Output1>();

        int width  = output.Description.DesktopBounds.Right;
        int height = output.Description.DesktopBounds.Bottom;

        Texture2DDescription textureDesc = new Texture2DDescription
        {
            CpuAccessFlags    = CpuAccessFlags.Read,
            BindFlags         = BindFlags.None,
            Format            = Format.B8G8R8A8_UNorm,
            Width             = width,
            Height            = height,
            OptionFlags       = ResourceOptionFlags.None,
            MipLevels         = 1,
            ArraySize         = 1,
            SampleDescription = { Count = 1, Quality = 0 },
            Usage             = ResourceUsage.Staging
        };

        Texture2D screenTexture = new Texture2D(device, textureDesc);

        new Thread(() =>
        {
            using (OutputDuplication duplicatedOutput = output1.DuplicateOutput(device))
            {
                while (isRun)
                {
                    try
                    {
                        duplicatedOutput.AcquireNextFrame(5, out OutputDuplicateFrameInformation duplicateFrameInformation, out SharpDX.DXGI.Resource screenResource);
                        using (Texture2D screenTexture2D = screenResource.QueryInterface <Texture2D>())
                        {
                            device.ImmediateContext.CopyResource(screenTexture2D, screenTexture);
                        }
                        DataBox mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None);

                        //直接传递图像资源指针,节省处理bitmap的时间
                        onScreenRefreshed?.Invoke(mapSource.DataPointer, width);

                        device.ImmediateContext.UnmapSubresource(screenTexture, 0);

                        screenResource.Dispose();
                        duplicatedOutput.ReleaseFrame();
                    }
                    catch (SharpDXException e)
                    {
                        if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
                        {
                            Console.WriteLine(e.Message);
                            Console.WriteLine(e.StackTrace);
                        }
                    }
                }
            }
        }).Start();
    }
Beispiel #30
0
        /// <summary>
        ///   Struct constructor
        /// </summary>
        /// <param name="adapter1">DXGI adapter device instance</param>
        /// <param name="output">DXGI output associated with this source</param>
        /// <param name="region">Region of the DXGI output device</param>
        internal DxgiCaptureSource(Adapter1 adapter1, Output output, Rectangle region)
        {
            Device   = null;
            Adapter1 = adapter1;
            Output   = output;
            Output1  = null;
            Output6  = null;
            Region   = region;

            if (region != output.Description.DesktopBounds)
            {
                Subregion = new ResourceRegion(region.Left - output.Description.DesktopBounds.Left,
                                               region.Top - output.Description.DesktopBounds.Top,
                                               0,
                                               region.Width + region.Left,
                                               region.Height + region.Top,
                                               1);
            }
            else
            {
                Subregion = null;
            }

            try {
                // create device
                Device = new Device(adapter1, DeviceCreationFlags.None, FeatureLevel.Level_11_0)
                {
#if DEBUG
                    DebugName = output.Description.DeviceName + " // " + adapter1.Description.Description
#endif
                };

                DxgiDevice = Device.QueryInterface <SharpDX.DXGI.Device>();

                // create texture
                Texture = new Texture2D(Device, new Texture2DDescription {
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    BindFlags         = BindFlags.None,
                    Format            = Format.B8G8R8A8_UNorm,
                    Width             = region.Width,
                    Height            = region.Height,
                    OptionFlags       = ResourceOptionFlags.None,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Staging
                });

                // duplicate desktop
                try {
                    Format[] formats = { Format.B8G8R8A8_UNorm };
                    Output6     = output.QueryInterface <Output6>();
                    Duplication = Output6.DuplicateOutput1(Device, 0, formats.Length, formats);
                } catch (Exception exception)
                    when(exception is NotSupportedException ||
                         exception.HResult == ResultCode.Unsupported.Result ||
                         exception.HResult == Result.NoInterface.Result)
                    {
                        Output1     = output.QueryInterface <Output1>();
                        Duplication = Output1.DuplicateOutput(Device);
                    }
            } catch (Exception exception)
                when(exception is NotSupportedException ||
                     exception is NotImplementedException ||
                     exception.HResult == ResultCode.Unsupported.Result ||
                     exception.HResult == Result.NotImplemented.Result ||
                     exception.HResult == Result.NoInterface.Result)
                {
                    throw new NotSupportedException("Platform not supported", exception);
                }

            Alive = true;
        }