private static void PlatformInitializeAdapters(out ReadOnlyCollection <GraphicsAdapter> adapters) { var factory = new SharpDX.DXGI.Factory1(); var adapterCount = factory.GetAdapterCount(); var adapterList = new List <GraphicsAdapter>(adapterCount); for (var i = 0; i < adapterCount; i++) { var device = factory.GetAdapter1(i); var monitorCount = device.GetOutputCount(); for (var j = 0; j < monitorCount; j++) { var monitor = device.GetOutput(j); var adapter = CreateAdapter(device, monitor); adapterList.Add(adapter); monitor.Dispose(); } } factory.Dispose(); adapters = new ReadOnlyCollection <GraphicsAdapter>(adapterList); }
private Adapter1 FindAdapter(long adapterId) { Adapter1 adapter1 = null; using (var dxgiFactory = new SharpDX.DXGI.Factory1()) { if (adapterId > 0) { var adapters = dxgiFactory.Adapters1; for (int i = 0; i < adapters.Length; i++) { var _adapter = adapters[i]; if (_adapter.Description1.Luid == adapterId) { adapter1 = _adapter; continue; } _adapter.Dispose(); } } if (adapter1 == null) { adapter1 = dxgiFactory.GetAdapter1(0); } } return(adapter1); }
/// <summary> /// Loads all adapter information and builds up all needed view models in a background thread. /// </summary> private void LoadAdapterInformation() { m_adapters = new List <EngineAdapterInfo>(); int adapterCount = m_dxgiFactory.GetAdapterCount1(); for (int loop = 0; loop < adapterCount; loop++) { try { DXGI.Adapter1 actAdapter = m_dxgiFactory.GetAdapter1(loop); m_adapters.Add(new EngineAdapterInfo(loop, actAdapter)); } catch (Exception) { //No exception handling needed here // .. adapter information simply can not be gathered } } }
/// <summary> /// Initializes a new instance of the <see cref="GraphicsAdapter" /> class. /// </summary> /// <param name="defaultFactory">The default factory.</param> /// <param name="adapterOrdinal">The adapter ordinal.</param> internal GraphicsAdapter(Factory1 defaultFactory, int adapterOrdinal) { this.adapterOrdinal = adapterOrdinal; adapter = defaultFactory.GetAdapter1(adapterOrdinal).DisposeBy(this); description = adapter.Description1; //var nativeOutputs = adapter.Outputs; var count = adapter.GetOutputCount(); outputs = new GraphicsOutput[count]; for (var i = 0; i < outputs.Length; i++) outputs[i] = new GraphicsOutput(this, i).DisposeBy(this); }
/// <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; } }
public GxContext(RenderControl window) { mWindow = window; mFactory = new Factory1(); if (mFactory.Adapters1.Length == 0) throw new InvalidOperationException( "Sorry, but DirectX returned that there is no graphics card installed on your system. Please check if all your drivers are up to date!"); Adapter = mFactory.GetAdapter1(0); if (Adapter.Outputs.Length == 0) throw new InvalidOperationException( "Sorry, but DirectX returned that there is no output (monitor) assigned to the graphics card: \"" + Adapter.Description.Description + "\". Please check if your drivers are OK and if your graphics card and monitor show up in the device manager."); mOutput = Adapter.Outputs[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; } }
public D3D11GraphicsDevice(bool validation, PresentationParameters presentationParameters) : base(GraphicsBackend.Direct3D11, presentationParameters) { #if DEBUG SharpDX.Configuration.EnableObjectTracking = true; SharpDX.Configuration.ThrowOnShaderCompileError = false; #endif // Create factory first. using (var dxgifactory = new DXGI.Factory1()) { var adapterCount = dxgifactory.GetAdapterCount1(); for (var i = 0; i < adapterCount; i++) { var adapter = dxgifactory.GetAdapter1(i); var desc = adapter.Description1; // Don't select the Basic Render Driver adapter. if ((desc.Flags & DXGI.AdapterFlags.Software) != DXGI.AdapterFlags.None) { continue; } var creationFlags = DeviceCreationFlags.BgraSupport /* | DeviceCreationFlags.VideoSupport*/; if (validation) { creationFlags |= DeviceCreationFlags.Debug; } try { D3DDevice = new Device(adapter, creationFlags, s_featureLevels); } catch (SharpDXException) { // Remove debug flag not being supported. creationFlags &= ~DeviceCreationFlags.Debug; D3DDevice = new Device(adapter, creationFlags, s_featureLevels); } Features.VendorId = desc.VendorId; Features.DeviceId = desc.DeviceId; Features.DeviceName = desc.Description; Log.Debug($"Direct3D Adapter ({i}): VID:{desc.VendorId}, PID:{desc.DeviceId} - {desc.Description}"); break; } } FeatureLevel = D3DDevice.FeatureLevel; D3DContext = D3DDevice.ImmediateContext; D3DDevice1 = D3DDevice.QueryInterfaceOrNull <Device1>(); if (D3DDevice1 != null) { D3DContext1 = D3DContext.QueryInterface <DeviceContext1>(); D3DAnnotation = D3DContext.QueryInterface <UserDefinedAnnotation>(); } // Detect multithreading D3DDevice1.CheckThreadingSupport(out _supportsConcurrentResources, out _supportsCommandLists); if (_supportsConcurrentResources && _supportsCommandLists) { Features.Multithreading = true; } // Create queue's GraphicsQueue = new D3D11CommandQueue(this); //ImmediateContext = new D3D11CommandContext(this, Device.ImmediateContext1); _mainSwapchain = new D3D11Swapchain(this, presentationParameters); }
/// <summary> /// Function to return a device object for this video device. /// </summary> /// <returns>The new device object, adapter and factory.</returns> internal Tuple <GI.Factory1, GI.Adapter1, D3D.Device> GetDevice(VideoDeviceType deviceType, DeviceFeatureLevel featureLevel) { GI.Factory1 factory; GI.Adapter1 adapter; D3D.Device device; switch (deviceType) { #if DEBUG case VideoDeviceType.ReferenceRasterizer: device = new D3D.Device(D3DCommon.DriverType.Reference, D3D.DeviceCreationFlags.Debug, D3DCommon.FeatureLevel.Level_11_0) { DebugName = string.Format("{0} D3D11 Device", Name) }; using (var giDevice = device.QueryInterface <GI.Device1>()) { adapter = giDevice.GetParent <GI.Adapter1>(); //giDevice.Adapter; factory = adapter.GetParent <GI.Factory1>(); } break; #endif case VideoDeviceType.Software: // WARP devices can only do SM4_1 or lower. if (featureLevel >= DeviceFeatureLevel.SM5) { featureLevel = DeviceFeatureLevel.SM4_1; } #if DEBUG device = new D3D.Device(D3DCommon.DriverType.Warp, D3D.DeviceCreationFlags.Debug, GetFeatureLevel(featureLevel)) { DebugName = string.Format("{0} D3D11 Device", Name) }; #else device = new D3D.Device(D3DCommon.DriverType.Warp, D3D.DeviceCreationFlags.None, GetFeatureLevel(featureLevel)); #endif using (var giDevice = device.QueryInterface <GI.Device1>()) { adapter = giDevice.GetParent <GI.Adapter1>(); factory = adapter.GetParent <GI.Factory1>(); } break; default: factory = new GI.Factory1(); adapter = factory.GetAdapter1(Index); #if DEBUG device = new D3D.Device(adapter, D3D.DeviceCreationFlags.Debug, GetFeatureLevel(featureLevel)) { DebugName = string.Format("{0} D3D11 Device", Name) }; #else device = new D3D.Device(adapter, D3D.DeviceCreationFlags.None, GetFeatureLevel(HardwareFeatureLevel)); #endif break; } return(new Tuple <GI.Factory1, GI.Adapter1, D3D.Device>(factory, adapter, 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; * }*/ }
public void Init() { logger.Debug("DesktopDuplicationManager::Init(...)"); CaptureMouse = true; this.AllScreensRect = SystemInformation.VirtualScreen; //var rawRect = new RawRectangle //{ // Left = AllScreensRect.Left, // Right = AllScreensRect.Right, // Top = AllScreensRect.Top, // Bottom = AllScreensRect.Bottom, //}; // SetupRegions(rawRect, ) SharpDX.DXGI.Factory1 dxgiFactory = null; Adapter1 adapter = null; Output output = null; try { dxgiFactory = new SharpDX.DXGI.Factory1(); logger.Info(MediaFoundation.DxTool.LogDxAdapters(dxgiFactory.Adapters1)); if (adapter == null) {// первым идет адаптер с которому подключен primary монитор adapter = dxgiFactory.GetAdapter1(0); } AdapterId = adapter.Description.Luid; //logger.Info("Screen source info: " + adapter.Description.Description + " " + output.Description.DeviceName); var deviceCreationFlags = //DeviceCreationFlags.Debug | DeviceCreationFlags.VideoSupport | DeviceCreationFlags.BgraSupport; device = new Device(adapter, deviceCreationFlags); using (var multiThread = device.QueryInterface <SharpDX.Direct3D11.Multithread>()) { multiThread.SetMultithreadProtected(true); } if (deskDupls != null) { //... } deskDupls = new List <_DesktopDuplicator>(); foreach (var _output in adapter.Outputs) { var descr = _output.Description; var desktopBounds = descr.DesktopBounds; var desktopRect = new GDI.Rectangle { X = desktopBounds.Left, Y = desktopBounds.Top, Width = desktopBounds.Right - desktopBounds.Left, Height = desktopBounds.Bottom - desktopBounds.Top, }; _DesktopDuplicator deskDupl = new _DesktopDuplicator(device); deskDupl.Init(_output, desktopRect); deskDupl.CaptureMouse = this.CaptureMouse; deskDupls.Add(deskDupl); //var rect = GDI.Rectangle.Intersect(desktopRect, SrcRect); //if (rect.Width > 0 && rect.Height > 0) //{ // logger.Info("Screen source info: " + adapter.Description.Description + " " + descr.DeviceName); // DesktopDuplicator deskDupl = new DesktopDuplicator(device); // deskDupl.Init(_output, SrcRect); // deskDupl.CaptureMouse = this.CaptureMouse; // deskDupls.Add(deskDupl); //} //else //{ // logger.Debug("No common area: " + descr.DeviceName + " " + SrcRect.ToString()); // continue; //} _output.Dispose(); } } finally { if (adapter != null) { adapter.Dispose(); adapter = null; } if (output != null) { output.Dispose(); output = null; } if (dxgiFactory != null) { dxgiFactory.Dispose(); dxgiFactory = null; } } compositionTexture = new Texture2D(device, new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.None, BindFlags = BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = AllScreensRect.Width, Height = AllScreensRect.Height, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Default, }); initialized = true; }
public static Bitmap CaptureScreen() { // # of graphics card adapter const int numAdapter = 0; // # of output device (i.e. monitor) const int numOutput = 1; // Create DXGI Factory1 var factory = new Factory1(); var adapter = factory.GetAdapter1(numAdapter); // Create device from Adapter var device = new Device(adapter); // Get DXGI.Output var output = adapter.GetOutput(numOutput); var output1 = output.QueryInterface<Output1>(); // Width/Height of desktop to capture int width = ((Rectangle)output.Description.DesktopBounds).Width; //width = 1024; int height = ((Rectangle)output.Description.DesktopBounds).Height; //height = 1024; // 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 }; var screenTexture = new Texture2D(device, textureDesc); // Duplicate the output var duplicatedOutput = output1.DuplicateOutput(device); bool captureDone = false; Bitmap bitmap = null; for (int i = 0; !captureDone; i++) { try { SharpDX.DXGI.Resource screenResource; OutputDuplicateFrameInformation duplicateFrameInformation; // Try to get duplicated frame within given time duplicatedOutput.AcquireNextFrame(10000, out duplicateFrameInformation, out screenResource); if (i > 0) { // copy resource into memory that can be accessed by the CPU using (var screenTexture2D = screenResource.QueryInterface<Texture2D>()) device.ImmediateContext.CopyResource(screenTexture2D, screenTexture); // Get the desktop capture texture var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, MapFlags.None); // Create Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, PixelFormat.Format32bppArgb); var boundsRect = new System.Drawing.Rectangle(0, 0, width, height); // Copy pixels from screen capture Texture to GDI bitmap var mapDest = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat); var sourcePtr = mapSource.DataPointer; var destPtr = mapDest.Scan0; for (int y = 0; y < height; y++) { // Copy a single line Utilities.CopyMemory(destPtr, sourcePtr, width * 4); // Advance pointers sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch); destPtr = IntPtr.Add(destPtr, mapDest.Stride); } // Release source and dest locks bitmap.UnlockBits(mapDest); device.ImmediateContext.UnmapSubresource(screenTexture, 0); // Capture done captureDone = true; } screenResource.Dispose(); duplicatedOutput.ReleaseFrame(); } catch (SharpDXException e) { if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code) { throw e; } } } duplicatedOutput.Dispose(); screenTexture.Dispose(); output1.Dispose(); output.Dispose(); device.Dispose(); adapter.Dispose(); factory.Dispose(); return bitmap; }
public DemoApplication() { //SharpDX.Configuration.EnableObjectTracking = true; _Form = new RenderForm(); _Timer = new Stopwatch(); _Form.Width = 1280; _Form.Height = 720; _Form.MaximumSize = new System.Drawing.Size(1280, 720); _Form.MinimumSize = new System.Drawing.Size(1280, 720); _Form.MaximizeBox = false; _Form.SizeGripStyle = SizeGripStyle.Hide; _Form.KeyPress += HandleKeyPress; _Form.ClientSizeChanged += HandleClientSizeChanged; _Form.KeyDown += HandleKeyDown; ModeDescription displayMode = new ModeDescription { Width = _Form.ClientSize.Width, Height = _Form.ClientSize.Height, RefreshRate = new Rational(60, 1), Format = Format.R8G8B8A8_UNorm }; SwapChainDescription chainDescription = new SwapChainDescription { ModeDescription = displayMode, SampleDescription = new SampleDescription(1, 0), BufferCount = 2, IsWindowed = true, OutputHandle = _Form.Handle, SwapEffect = SwapEffect.Sequential, Usage = Usage.BackBuffer | Usage.RenderTargetOutput }; _Factory = new Factory1(); int availableAdapters = _Factory.GetAdapterCount1(); if(availableAdapters == 0) { throw new Exception("no adapters are available"); } for(int i = 0; i < availableAdapters; ++i) { #if DEBUG using(Adapter1 dxgiSurfaceAdapter = _Factory.GetAdapter1(i)) { try { Device1.CreateWithSwapChain( dxgiSurfaceAdapter, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug, chainDescription, out _Device, out _SwapChain); } catch(SharpDXException) { continue; } _Device2D = new Device2D(dxgiSurfaceAdapter); } #else using (Adapter1 dxgiSurfaceAdapter = _Factory.GetAdapter1(i)) { try { Device1.CreateWithSwapChain( dxgiSurfaceAdapter, DeviceCreationFlags.BgraSupport, chainDescription, out _Device, out _SwapChain); } catch(SharpDXException) { continue; } _Device2D = new Device2D(dxgiSurfaceAdapter); } #endif } _Device2D.Diagnostics.Query("Composition", "FrameBatchCount", out _CompositionFrameBatchCount); _Device2D.Diagnostics.Query("Composition", "FrameDuration", out _CompositionFrameDuration); _Device2D.Diagnostics.Query("Painting", "FrameDuration", out _PaintingFrameDuration); _Timer.Start(); _Renderer = new D3D10Renderer(_Device); HandleClientSizeChanged(null, null); _IsResetQueued = true; }
public WinformsEye() { factory = new Factory1(); adapters = Enumerable.Range(0, factory.GetAdapterCount1()).Select(i => new CAdapter(factory.GetAdapter1(i), i)).ToArray(); windows = new List<ControlWindow>(); }
public void Setup(MfVideoArgs inputArgs) { logger.Debug("MfH264Decoder::Setup(...)"); var frameRate = inputArgs.FrameRate; frameDuration = MfTool.TicksPerSecond / frameRate; var width = inputArgs.Width; var height = inputArgs.Height; var bufSize = width * height * 4; var inputFormat = VideoFormatGuids.H264; try { //device = new Device(adapter, DeviceCreationFlags.BgraSupport); if (device == null) { using (var dxgiFactory = new SharpDX.DXGI.Factory1()) { using (var adapter = dxgiFactory.GetAdapter1(0)) { device = new Device(adapter, //DeviceCreationFlags.Debug | DeviceCreationFlags.VideoSupport | DeviceCreationFlags.BgraSupport); using (var multiThread = device.QueryInterface <SharpDX.Direct3D11.Multithread>()) { multiThread.SetMultithreadProtected(true); } } } } var transformFlags = //TransformEnumFlag.Hardware | TransformEnumFlag.SortAndFilter; var inputType = new TRegisterTypeInformation { GuidMajorType = MediaTypeGuids.Video, GuidSubtype = VideoFormatGuids.H264 }; var transformActivators = MediaFactory.FindTransform(TransformCategoryGuids.VideoDecoder, transformFlags, inputType, null); try { foreach (var activator in transformActivators) { //bool isHardware = flags.HasFlag(TransformEnumFlag.Hardware); //bool isAsync = flags.HasFlag(TransformEnumFlag.Asyncmft); string name = activator.Get(TransformAttributeKeys.MftFriendlyNameAttribute); Guid clsid = activator.Get(TransformAttributeKeys.MftTransformClsidAttribute); TransformEnumFlag flags = (TransformEnumFlag)activator.Get(TransformAttributeKeys.TransformFlagsAttribute); bool isAsync = !(flags.HasFlag(TransformEnumFlag.Syncmft)); isAsync |= !!(flags.HasFlag(TransformEnumFlag.Asyncmft)); bool isHardware = !!(flags.HasFlag(TransformEnumFlag.Hardware)); var _flags = Enum.GetValues(typeof(TransformEnumFlag)) .Cast <TransformEnumFlag>() .Where(m => (m != TransformEnumFlag.None && flags.HasFlag(m))); var transformInfo = name + " " + clsid.ToString() + " " + string.Join("|", _flags); logger.Info(transformInfo); //encoder = activator.ActivateObject<Transform>(); //break; //var HardwareUrl = activator.Get(TransformAttributeKeys.MftEnumHardwareUrlAttribute); //logger.Info(HardwareUrl); //var TransformAsync = activator.Get(TransformAttributeKeys.TransformAsync); //logger.Info(TransformAsync); //logger.Info("-------------------------------------"); } } finally { decoder = transformActivators[0].ActivateObject <Transform>(); foreach (var activator in transformActivators) { activator.Dispose(); } } using (var attr = decoder.Attributes) { bool d3dAware = attr.Get(TransformAttributeKeys.D3DAware); bool d3d11Aware = attr.Get(TransformAttributeKeys.D3D11Aware); if (d3d11Aware) { using (DXGIDeviceManager devMan = new DXGIDeviceManager()) { devMan.ResetDevice(device); decoder.ProcessMessage(TMessageType.SetD3DManager, devMan.NativePointer); } } attr.Set(SinkWriterAttributeKeys.LowLatency, true); //attr.Set(MFAttributeKeys.MF_SA_MINIMUM_OUTPUT_SAMPLE_COUNT, 1); } int inputStreamCount = -1; int outputStreamsCount = -1; decoder.GetStreamCount(out inputStreamCount, out outputStreamsCount); int[] inputStreamIDs = new int[inputStreamCount]; int[] outputStreamIDs = new int[outputStreamsCount]; bool res = decoder.TryGetStreamIDs(inputStreamIDs, outputStreamIDs); if (res) { inputStreamId = inputStreamIDs[0]; outputStreamId = outputStreamIDs[0]; } else { inputStreamId = 0; outputStreamId = 0; } for (int i = 0; ; i++) { try { decoder.GetInputAvailableType(0, i, out MediaType mediaType); if (mediaType == null) { logger.Warn("NoMoreType"); break; } var formatId = mediaType.Get(MediaTypeAttributeKeys.Subtype); if (formatId == inputFormat) { logger.Debug("inputFormat " + inputFormat); InputMediaType = mediaType; break; } mediaType.Dispose(); mediaType = null; } catch (SharpDX.SharpDXException ex) { if (ex.ResultCode != SharpDX.MediaFoundation.ResultCode.NoMoreTypes) { throw; } } } if (InputMediaType == null) { logger.Warn("Unsuported format: " + MfTool.GetMediaTypeName(inputFormat)); return; } InputMediaType.Set(MediaTypeAttributeKeys.MajorType, MediaTypeGuids.Video); InputMediaType.Set(MediaTypeAttributeKeys.Subtype, VideoFormatGuids.H264); InputMediaType.Set(MediaTypeAttributeKeys.FrameSize, MfTool.PackToLong(width, height)); InputMediaType.Set(MediaTypeAttributeKeys.FrameRate, frameRate); // InputMediaType.Set(MediaTypeAttributeKeys.PixelAspectRatio, MfTool.PackToLong(1, 1)); InputMediaType.Set(MediaTypeAttributeKeys.InterlaceMode, (int)VideoInterlaceMode.Progressive); InputMediaType.Set(MediaTypeAttributeKeys.AllSamplesIndependent, 1); decoder.SetInputType(inputStreamId, InputMediaType, 0); logger.Info("============== INPUT TYPE=================="); logger.Info(MfTool.LogMediaType(InputMediaType)); //MediaType outputMediaType = null; //for (int i = 0; ; i++) //{ // res = decoder.TryGetOutputAvailableType(outputStreamId, i, out outputMediaType); // if (!res) // { // break; // } // //outputMediaType.Set(MediaTypeAttributeKeys.AvgBitrate, 30000000); // outputMediaType.Set(MediaTypeAttributeKeys.FrameSize, MfTool.PackToLong(width, height)); // outputMediaType.Set(MediaTypeAttributeKeys.FrameRate, MfTool.PackToLong(frameRate, 1)); // //outputMediaType.Set(MediaTypeAttributeKeys.InterlaceMode, (int)VideoInterlaceMode.Progressive); // //outputMediaType.Set(MediaTypeAttributeKeys.AllSamplesIndependent, 1); // decoder.SetOutputType(outputStreamId, outputMediaType, 0); // outputMediaType.Dispose(); // outputMediaType = null; // break; //} OutputMediaType = new MediaType(); OutputMediaType.Set(MediaTypeAttributeKeys.MajorType, MediaTypeGuids.Video); OutputMediaType.Set(MediaTypeAttributeKeys.Subtype, VideoFormatGuids.NV12); //OutputMediaType.Set(MediaTypeAttributeKeys.AvgBitrate, 30000000); OutputMediaType.Set(MediaTypeAttributeKeys.InterlaceMode, (int)VideoInterlaceMode.Progressive); OutputMediaType.Set(MediaTypeAttributeKeys.FrameSize, MfTool.PackToLong(width, height)); OutputMediaType.Set(MediaTypeAttributeKeys.FrameRate, frameRate); OutputMediaType.Set(MediaTypeAttributeKeys.AllSamplesIndependent, 1); decoder.SetOutputType(outputStreamId, OutputMediaType, 0); logger.Info("============== OUTPUT TYPE=================="); logger.Info(MfTool.LogMediaType(OutputMediaType)); } catch (Exception ex) { logger.Error(ex); Close(); throw; } }
private Adapter1 InitializeAdapter(int adapterIndex) { try { using (var factory = new Factory1()) { return factory.GetAdapter1(adapterIndex); } } catch (SharpDXException) { throw new ScreenException("Unable to initialize the adapter."); } }
public RLocalDesktopCapture(int outputDeviceIndex) { // # of graphics card adapter const int numAdapter = 0; // # of output device (i.e. monitor) int numOutput = outputDeviceIndex; // Create DXGI Factory1 var factory = new SharpDX.DXGI.Factory1(); var adapter = factory.GetAdapter1(numAdapter); // Create device from Adapter device = new Device(adapter); // Get DXGI.Output var output = adapter.GetOutput(numOutput); var output1 = output.QueryInterface <Output1>(); // Width/Height of desktop to capture DisplayWidth = ((SharpDX.Rectangle)output.Description.DesktopBounds).Width; DisplayHeight = ((SharpDX.Rectangle)output.Description.DesktopBounds).Height; int stride = 4 * DisplayWidth; int size = stride * DisplayHeight; FrameBytes = new byte[size]; GCHandle pinned = GCHandle.Alloc(outBytes, GCHandleType.Pinned); outBytesPtr = pinned.AddrOfPinnedObject(); //pinned.Free(); GCHandle pinned2 = GCHandle.Alloc(transcoderOptions, GCHandleType.Pinned); transcoderOptionsPtr = pinned2.AddrOfPinnedObject(); GCHandle pinned3 = GCHandle.Alloc(FrameBytes, GCHandleType.Pinned); frameBytesPtr = pinned3.AddrOfPinnedObject(); // Create Staging texture CPU-accessible var textureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = DisplayWidth, Height = DisplayHeight, 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); StartWorkTimer(); }
public void Run() { var form = new RenderForm("2d and 3d combined...it's like magic"); form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) form.Close(); }; // DirectX DXGI 1.1 factory var factory1 = new Factory1(); // The 1st graphics adapter var adapter1 = factory1.GetAdapter1(0); // --------------------------------------------------------------------------------------------- // Setup direct 3d version 11. It's context will be used to combine the two elements // --------------------------------------------------------------------------------------------- var description = new SwapChainDescription { BufferCount = 1, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, Flags = SwapChainFlags.AllowModeSwitch }; Device11 device11; SwapChain swapChain; Device11.CreateWithSwapChain(adapter1, DeviceCreationFlags.None, description, out device11, out swapChain); // create a view of our render target, which is the backbuffer of the swap chain we just created RenderTargetView renderTargetView; using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0)) renderTargetView = new RenderTargetView(device11, resource); // setting a viewport is required if you want to actually see anything var context = device11.ImmediateContext; var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height); context.OutputMerger.SetTargets(renderTargetView); context.Rasterizer.SetViewports(viewport); // // Create the DirectX11 texture2D. This texture will be shared with the DirectX10 device. // // The DirectX10 device will be used to render text onto this texture. // DirectX11 will then draw this texture (blended) onto the screen. // The KeyedMutex flag is required in order to share this resource between the two devices. var textureD3D11 = new Texture2D(device11, new Texture2DDescription { Width = form.ClientSize.Width, Height = form.ClientSize.Height, MipLevels = 1, ArraySize = 1, Format = Format.B8G8R8A8_UNorm, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.SharedKeyedmutex }); // --------------------------------------------------------------------------------------------- // Setup a direct 3d version 10.1 adapter // --------------------------------------------------------------------------------------------- var device10 = new Device10(adapter1, SharpDX.Direct3D10.DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0); // --------------------------------------------------------------------------------------------- // Setup Direct 2d // --------------------------------------------------------------------------------------------- // Direct2D Factory var factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded, DebugLevel.Information); // Here we bind the texture we've created on our direct3d11 device through the direct3d10 // to the direct 2d render target.... var sharedResource = textureD3D11.QueryInterface<SharpDX.DXGI.Resource>(); var textureD3D10 = device10.OpenSharedResource<SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle); var surface = textureD3D10.AsSurface(); var rtp = new RenderTargetProperties { MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_10, Type = RenderTargetType.Hardware, PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied) }; var renderTarget2D = new RenderTarget(factory2D, surface, rtp); var solidColorBrush = new SolidColorBrush(renderTarget2D, Colors.Red); // --------------------------------------------------------------------------------------------------- // Setup the rendering data // --------------------------------------------------------------------------------------------------- // Load Effect. This includes both the vertex and pixel shaders. // Also can include more than one technique. ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile( "effectDx11.fx", "fx_5_0", ShaderFlags.EnableStrictness); var effect = new Effect(device11, shaderByteCode); // create triangle vertex data, making sure to rewind the stream afterward var verticesTriangle = new DataStream(VertexPositionColor.SizeInBytes * 3, true, true); verticesTriangle.Write(new VertexPositionColor(new Vector3(0.0f, 0.5f, 0.5f),new Color4(1.0f, 0.0f, 0.0f, 1.0f))); verticesTriangle.Write(new VertexPositionColor(new Vector3(0.5f, -0.5f, 0.5f),new Color4(0.0f, 1.0f, 0.0f, 1.0f))); verticesTriangle.Write(new VertexPositionColor(new Vector3(-0.5f, -0.5f, 0.5f),new Color4(0.0f, 0.0f, 1.0f, 1.0f))); verticesTriangle.Position = 0; // create the triangle vertex layout and buffer var layoutColor = new InputLayout(device11, effect.GetTechniqueByName("Color").GetPassByIndex(0).Description.Signature, VertexPositionColor.inputElements); var vertexBufferColor = new Buffer(device11, verticesTriangle, (int)verticesTriangle.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); verticesTriangle.Close(); // create overlay vertex data, making sure to rewind the stream afterward // Top Left of screen is -1, +1 // Bottom Right of screen is +1, -1 var verticesText = new DataStream(VertexPositionTexture.SizeInBytes * 4, true, true); verticesText.Write(new VertexPositionTexture(new Vector3(-1, 1, 0),new Vector2(0, 0f))); verticesText.Write(new VertexPositionTexture(new Vector3(1, 1, 0),new Vector2(1, 0))); verticesText.Write(new VertexPositionTexture(new Vector3(-1, -1, 0),new Vector2(0, 1))); verticesText.Write(new VertexPositionTexture(new Vector3(1, -1, 0),new Vector2(1, 1))); verticesText.Position = 0; // create the overlay vertex layout and buffer var layoutOverlay = new InputLayout(device11, effect.GetTechniqueByName("Overlay").GetPassByIndex(0).Description.Signature, VertexPositionTexture.inputElements); var vertexBufferOverlay = new Buffer(device11, verticesText, (int)verticesText.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); verticesText.Close(); // Think of the shared textureD3D10 as an overlay. // The overlay needs to show the 2d content but let the underlying triangle (or whatever) // show thru, which is accomplished by blending. var bsd = new BlendStateDescription(); bsd.RenderTarget[0].IsBlendEnabled = true; bsd.RenderTarget[0].SourceBlend = BlendOption.SourceColor; bsd.RenderTarget[0].DestinationBlend = BlendOption.BlendFactor; bsd.RenderTarget[0].BlendOperation = BlendOperation.Add; bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.One; bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; var blendStateTransparent = new BlendState(device11, bsd); // --------------------------------------------------------------------------------------------------- // Create and tesselate an ellipse // --------------------------------------------------------------------------------------------------- var center = new DrawingPointF(form.ClientSize.Width/2.0f, form.ClientSize.Height/2.0f); var ellipse = new EllipseGeometry(factory2D, new Ellipse(center, form.ClientSize.Width / 2.0f, form.ClientSize.Height / 2.0f)); // Populate a PathGeometry from Ellipse tessellation var tesselatedGeometry = new PathGeometry(factory2D); _geometrySink = tesselatedGeometry.Open(); // Force RoundLineJoin otherwise the tesselated looks buggy at line joins _geometrySink.SetSegmentFlags(PathSegment.ForceRoundLineJoin); // Tesselate the ellipse to our TessellationSink ellipse.Tessellate(1, this); _geometrySink.Close(); // --------------------------------------------------------------------------------------------------- // Acquire the mutexes. These are needed to assure the device in use has exclusive access to the surface // --------------------------------------------------------------------------------------------------- var device10Mutex = textureD3D10.QueryInterface<KeyedMutex>(); var device11Mutex = textureD3D11.QueryInterface<KeyedMutex>(); // --------------------------------------------------------------------------------------------------- // Main rendering loop // --------------------------------------------------------------------------------------------------- bool first = true; RenderLoop .Run(form, () => { if(first) { form.Activate(); first = false; } // clear the render target to black context.ClearRenderTargetView(renderTargetView, Colors.DarkSlateGray); // Draw the triangle context.InputAssembler.InputLayout = layoutColor; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferColor, VertexPositionColor.SizeInBytes, 0)); context.OutputMerger.BlendState = null; var currentTechnique = effect.GetTechniqueByName("Color"); for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass) { using (var effectPass = currentTechnique.GetPassByIndex(pass)) { System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass"); effectPass.Apply(context); } context.Draw(3, 0); }; // Draw Ellipse on the shared Texture2D device10Mutex.Acquire(0, 100); renderTarget2D.BeginDraw(); renderTarget2D.Clear(Colors.Black); renderTarget2D.DrawGeometry(tesselatedGeometry, solidColorBrush); renderTarget2D.DrawEllipse(new Ellipse(center, 200, 200), solidColorBrush, 20, null); renderTarget2D.EndDraw(); device10Mutex.Release(0); // Draw the shared texture2D onto the screen, blending the 2d content in device11Mutex.Acquire(0, 100); var srv = new ShaderResourceView(device11, textureD3D11); effect.GetVariableByName("g_Overlay").AsShaderResource().SetResource(srv); context.InputAssembler.InputLayout = layoutOverlay; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferOverlay, VertexPositionTexture.SizeInBytes, 0)); context.OutputMerger.BlendState = blendStateTransparent; currentTechnique = effect.GetTechniqueByName("Overlay"); for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass) { using (var effectPass = currentTechnique.GetPassByIndex(pass)) { System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass"); effectPass.Apply(context); } context.Draw(4, 0); } srv.Dispose(); device11Mutex.Release(0); swapChain.Present(0, PresentFlags.None); }); // dispose everything vertexBufferColor.Dispose(); vertexBufferOverlay.Dispose(); layoutColor.Dispose(); layoutOverlay.Dispose(); effect.Dispose(); shaderByteCode.Dispose(); renderTarget2D.Dispose(); swapChain.Dispose(); device11.Dispose(); device10.Dispose(); textureD3D10.Dispose(); textureD3D11.Dispose(); factory1.Dispose(); adapter1.Dispose(); sharedResource.Dispose(); factory2D.Dispose(); surface.Dispose(); solidColorBrush.Dispose(); blendStateTransparent.Dispose(); device10Mutex.Dispose(); device11Mutex.Dispose(); }
/*private void CaptureFrame(object sender, DoWorkEventArgs e) * { * //Bitmap bmp = GetFrame(); * //e.Result = bmp; * }*/ private void Init() { captureWorker = new BackgroundWorker(); captureWorker.DoWork += new DoWorkEventHandler(CaptureFrame); captureWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(HandleCapturedFrame); EncoderWorker = new BackgroundWorker(); EncoderWorker.DoWork += new DoWorkEventHandler(EncodeFrameTask); EncoderWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(HandleEncodedFrame); DecoderWorker = new BackgroundWorker(); DecoderWorker.DoWork += new DoWorkEventHandler(DecodeFrameTask); DecoderWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(HandleDecodedFrame); // # of graphics card adapter const int numAdapter = 0; // # of output device (i.e. monitor) const int numOutput = 0; // Create DXGI Factory1 var factory = new SharpDX.DXGI.Factory1(); var adapter = factory.GetAdapter1(numAdapter); // Create device from Adapter device = new Device(adapter); // Get DXGI.Output var output = adapter.GetOutput(numOutput); var output1 = output.QueryInterface <Output1>(); // Width/Height of desktop to capture transcoderOptions.InputWidth = ((SharpDX.Rectangle)output.Description.DesktopBounds).Width; transcoderOptions.InputHeight = ((SharpDX.Rectangle)output.Description.DesktopBounds).Height; outBytes = new byte[GetNumBytesRender()]; GCHandle pinned = GCHandle.Alloc(outBytes, GCHandleType.Pinned); outBytesPtr = pinned.AddrOfPinnedObject(); //pinned.Free(); GCHandle pinned2 = GCHandle.Alloc(transcoderOptions, GCHandleType.Pinned); transcoderOptionsPtr = pinned2.AddrOfPinnedObject(); GCHandle pinned3 = GCHandle.Alloc(frameBytes, GCHandleType.Pinned); frameBytesPtr = pinned3.AddrOfPinnedObject(); this.ClientSize = new Size(1600, 900); // Create Staging texture CPU-accessible var textureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = DisplayWidth(), Height = DisplayHeight(), 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); InitializeDeviceResources(); }