public void Setup(object pars) { logger.Debug("VideoCaptureSource::Setup()"); if (State != CaptureState.Closed) { throw new InvalidOperationException("Invalid capture state " + State); } UvcDevice captureParams = pars as UvcDevice; var deviceId = captureParams.DeviceId; try { int adapterIndex = 0; using (var dxgiFactory = new SharpDX.DXGI.Factory1()) { using (var adapter = dxgiFactory.GetAdapter1(adapterIndex)) { var deviceCreationFlags = //DeviceCreationFlags.Debug | DeviceCreationFlags.VideoSupport | DeviceCreationFlags.BgraSupport; device = new Device(adapter, deviceCreationFlags); using (var multiThread = device.QueryInterface <SharpDX.Direct3D11.Multithread>()) { multiThread.SetMultithreadProtected(true); } } } sourceReader = CreateSourceReaderByDeviceId(deviceId); if (sourceReader == null) { throw new Exception("Unable to create media source reader " + deviceId); } var mediaType = sourceReader.GetCurrentMediaType(SourceReaderIndex.FirstVideoStream); logger.Debug("------------------CurrentMediaType-------------------"); logger.Debug(MfTool.LogMediaType(mediaType)); srcSize = MfTool.GetFrameSize(mediaType); var destSize = captureParams.Resolution; if (destSize.IsEmpty) { destSize = srcSize; } var subtype = mediaType.Get(MediaTypeAttributeKeys.Subtype); mediaType?.Dispose(); SharedTexture = new Texture2D(device, new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.None, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, Width = destSize.Width, Height = destSize.Height, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.Shared, }); stagingTexture = new Texture2D(device, new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, //BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, BindFlags = BindFlags.None, Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, Width = destSize.Width, Height = destSize.Height, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging, OptionFlags = ResourceOptionFlags.None, }); processor = new MfVideoProcessor(null); var intupArgs = new MfVideoArgs { Width = srcSize.Width, Height = srcSize.Height, Format = subtype,//VideoFormatGuids.NV12, }; var outputArgs = new MfVideoArgs { Width = destSize.Width, Height = destSize.Height, Format = VideoFormatGuids.Argb32, }; processor.Setup(intupArgs, outputArgs); processor.SetMirror(VideoProcessorMirror.MirrorVertical); state = CaptureState.Initialized; } catch (Exception ex) { logger.Error(ex); LastError = ex; errorCode = (int)SharedTypes.ErrorCode.NotInitialized; CleanUp(); throw; } }
private StreamSession CreateSession() { var session = StreamSession.Default(); var transport = TransportMode.Udp; if (PropertyNetwork.UnicastProtocol == ProtocolKind.TCP) { transport = TransportMode.Tcp; } session.StreamName = Name; session.NetworkIpAddress = PropertyNetwork.Network ?? "0.0.0.0"; session.CommunicationPort = PropertyNetwork.Port; if (PropertyNetwork.Port > 0) { session.CommunicationPort = PropertyNetwork.Port; } else if (PropertyNetwork.CommunicationPort > 0) { session.CommunicationPort = PropertyNetwork.CommunicationPort; } else { session.CommunicationPort = Helpers.NetworkHelper.FindAvailableTcpPort(); } //if(PropertyNetwork.CommunicationPort <=0) //{ // session.CommunicationPort = PropertyNetwork.Port; //} //else //{ // session.CommunicationPort = PropertyNetwork.CommunicationPort; //} //int communicationPort = PropertyNetwork.Port; //if (communicationPort <= 0) //{// если порт не задан - ищем свободный начиная с 808 // //communicationPort = GetRandomTcpPort(); // var freeTcpPorts = MediaToolkit.Utils.NetTools.GetFreePortRange(System.Net.Sockets.ProtocolType.Tcp, 1, 808); // if (freeTcpPorts != null && freeTcpPorts.Count() > 0) // { // communicationPort = freeTcpPorts.FirstOrDefault(); // } //} ////PropertyNetwork.CommunicationPort = communicationPort; //session.CommunicationPort = communicationPort; session.TransportMode = transport; bool isMulticast = !PropertyNetwork.IsUnicast; session.IsMulticast = isMulticast; if (isMulticast) { //VAlidate.... session.MutlicastAddress = PropertyNetwork.MulticastIp; session.MutlicastPort1 = PropertyNetwork.MulticasVideoPort; session.MutlicastPort2 = PropertyNetwork.MulticasAudioPort; } var videoSettings = session.VideoSettings; var encoderResolution = new Size(PropertyVideo.ResolutionWidth, PropertyVideo.ResolutionHeight); videoSettings.StreamFlags &= ~VideoStreamFlags.UseEncoderResoulutionFromSource; if (AdvancedSettings.UseResolutionFromCaptureSource) { videoSettings.StreamFlags |= VideoStreamFlags.UseEncoderResoulutionFromSource; } else { encoderResolution = new Size(AdvancedSettings.Width, AdvancedSettings.Height); } var videoEncoderSettings = videoSettings.EncoderSettings; videoEncoderSettings.EncoderId = AdvancedSettings.EncoderId; videoEncoderSettings.Bitrate = AdvancedSettings.Bitrate; videoEncoderSettings.MaxBitrate = AdvancedSettings.MaxBitrate; videoEncoderSettings.Width = encoderResolution.Width; videoEncoderSettings.Height = encoderResolution.Height; videoEncoderSettings.FrameRate = new MediaRatio(AdvancedSettings.Fps, 1); videoEncoderSettings.Profile = AdvancedSettings.H264Profile; videoEncoderSettings.LowLatency = AdvancedSettings.LowLatency; var captureRegion = PropertyVideo.VideoRect; var captureType = PropertyVideo.CaptType; //var captureFps = PropertyVideo.CaptFps; var captureFps = AdvancedSettings.Fps; var useHardware = PropertyVideo.CaptUseHardware; var screenCaptureProperties = new ScreenCaptureProperties { CaptureMouse = PropertyVideo.CaptureMouse, CaptureType = captureType, // VideoCaptureType.DXGIDeskDupl, UseHardware = useHardware, Fps = captureFps, ShowDebugInfo = false, ShowDebugBorder = PropertyVideo.ShowCaptureBorder, AspectRatio = AdvancedSettings.KeepAspectRatio, }; VideoCaptureDevice captureDevice = null; //var videoSourceItem = PropertyVideo.Display; if (PropertyVideo.IsUvcDevice) { captureDevice = new UvcDevice { Name = PropertyVideo.DeviceName, Resolution = captureRegion.Size, DeviceId = PropertyVideo.DeviceId, }; } else { captureDevice = new ScreenCaptureDevice { CaptureRegion = captureRegion, DisplayRegion = captureRegion, Name = PropertyVideo.DeviceName, Resolution = captureRegion.Size, Properties = screenCaptureProperties, DeviceId = PropertyVideo.DeviceId, }; } if (PropertyAudio.IsEnabled) { var deviceId = PropertyAudio.DeviceId; var audioDevice = MediaToolkit.AudioTool.GetAudioCaptureDevices().FirstOrDefault(d => d.DeviceId == deviceId); if (audioDevice != null) { session.AudioSettings.Enabled = true; audioDevice.Properties = new WasapiCaptureProperties(); session.AudioSettings.CaptureDevice = audioDevice; } } else { session.AudioSettings.Enabled = false; } logger.Info("CaptureDevice: " + captureRegion); session.VideoSettings.CaptureDevice = captureDevice; return(session); }
static void Main(string[] args) { Console.WriteLine("==============START============="); try { MediaToolkitManager.Startup(); //SharpDX.MediaFoundation.DirectX.VideoProcessorService videoProcessorService = new SharpDX.MediaFoundation.DirectX.VideoProcessorService(IntPtr.Zero); //videoProcessorService.GetVideoProcessorCaps() //EnumerateCaptureSources(); //Console.ReadKey(); //return; var device = GetVideoCaptureDevices(); var d = device[0]; VideoCaptureSource videoCaptureSource = new VideoCaptureSource(); UvcDevice captureParams = new UvcDevice { Resolution = new GDI.Size(1920, 1080), DeviceId = d.SymLink, }; videoCaptureSource.Setup(captureParams); PreviewForm previewForm = null; D3DImageRenderer provider = null; var uiThread = new Thread(() => { provider = new D3DImageRenderer(); provider.Setup(videoCaptureSource.SharedTexture); previewForm = new PreviewForm(); previewForm.d3DImageControl1.DataContext = provider; previewForm.Show(); provider.Start(); Application.Run(); }); uiThread.IsBackground = true; uiThread.SetApartmentState(ApartmentState.STA); Console.WriteLine("Any key to start..."); Console.ReadKey(); uiThread.Start(); videoCaptureSource.BufferUpdated += () => { provider?.Update(); }; videoCaptureSource.Start(); Console.ReadKey(); Console.WriteLine("Any key to stop..."); videoCaptureSource.Stop(); videoCaptureSource.Close(); Console.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects()); MediaToolkitManager.Shutdown(); //MediaManager.Shutdown(); //previewForm?.Close(); } catch (Exception ex) { Console.WriteLine(ex); } Console.WriteLine("==============THE END============="); Console.WriteLine("Any key to quit..."); Console.ReadKey(); }