void GetInterfaces() { Type comType = null; object comObj = null; try { //ICaptureGraphBuilder2 pBuilder = null; // Initiate Capture Graph Builder Guid clsid = typeof(CaptureGraphBuilder2).GUID; comType = Type.GetTypeFromCLSID(clsid); comObj = Activator.CreateInstance(comType); m_bCapGraph = (ICaptureGraphBuilder2)comObj; // Initiate Graph Builder Guid clsfg = typeof(FilterGraph).GUID; comType = Type.GetTypeFromCLSID(clsfg); //Clsid.FilterGraph); comObj = Activator.CreateInstance(comType); m_bGraph = (IGraphBuilder)comObj; // Initiate Video Configuration Interface DsGuid cat = PinCategory.Capture; DsGuid type = MediaType.Interleaved; Guid iid = typeof(IAMVideoProcAmp).GUID; m_bCapGraph.FindInterface(cat, type, capFilter, iid, out comObj); m_iVidConfig = (IAMVideoProcAmp)comObj; // test //m_iVidConfig.Set(VideoProcAmpProperty.WhiteBalance, 0, VideoProcAmpFlags.Manual); // Initiate Camera Configuration Interface cat = PinCategory.Capture; type = MediaType.Interleaved; iid = typeof(IAMCameraControl).GUID; m_bCapGraph.FindInterface(cat, type, capFilter, iid, out comObj); m_iCamConfig = (IAMCameraControl)comObj; } catch (Exception ee) { if (comObj != null) Marshal.ReleaseComObject(comObj); throw new Exception("Could not get interfaces\r\n" + ee.Message); } }
private PTZDevice(string name, PTZType type) { var devices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice); var device = devices.Where(d => d.Name == name).FirstOrDefault(); _device = device; _type = type; if (_device == null) throw new ApplicationException(String.Format("Couldn't find device named {0}!", name)); IFilterGraph2 graphBuilder = new FilterGraph() as IFilterGraph2; IBaseFilter filter = null; IMoniker i = _device.Mon as IMoniker; graphBuilder.AddSourceFilterForMoniker(i, null, _device.Name, out filter); _camControl = filter as IAMCameraControl; _ksPropertySet = filter as IKsPropertySet; if (_camControl == null) throw new ApplicationException("Couldn't get ICamControl!"); if (_ksPropertySet == null) throw new ApplicationException("Couldn't get IKsPropertySet!"); //TODO: Add Absolute if (type == PTZType.Relative && !(SupportFor(KSProperties.CameraControlFeature.KSPROPERTY_CAMERACONTROL_PAN_RELATIVE) && SupportFor(KSProperties.CameraControlFeature.KSPROPERTY_CAMERACONTROL_TILT_RELATIVE))) { throw new NotSupportedException("This camera doesn't appear to support Relative Pan and Tilt"); } //TODO: Do I through NotSupported when methods are called or throw them now? //TODO: Do I check for Zoom or ignore if it's not there? InitZoomRanges(); }
private void checkBoxFocus_CheckedChanged(object sender, EventArgs e) { CheckBox cb = ( CheckBox )sender; Button forceButton = ( Button )cb.Tag; TrackBar tBar = ( TrackBar )cb.Parent.Controls.Find("TrackBarFocus", false)[0]; IAMCameraControl pCameraControl = ( IAMCameraControl )forceButton.Tag; forceButton.Enabled = cb.Checked; tBar.Enabled = !cb.Checked; if (cb.Checked) { // todo pCameraControl.Set(CameraControlProperty.Focus, tBar.Minimum, CameraControlFlags.Manual); pCameraControl.Set(CameraControlProperty.Focus, 0, CameraControlFlags.Auto); if (mulTimer != null) { mulTimer.Close(); } } else { pCameraControl.Set(CameraControlProperty.Focus, (tBar.Maximum - tBar.Value + tBar.Minimum), CameraControlFlags.Manual); if (device != null) { device.ReadReport(OnReport); mulTimer = new System.Timers.Timer(); mulTimer.Interval = 300; mulTimer.Elapsed += OnTimedEvent; mulTimer.AutoReset = true; mulTimer.Enabled = true; } } }
private IAMCameraControl GetIAMCameraControl(DsDevice device) { IGraphBuilder m_graph; /* Create a new graph */ m_graph = (IGraphBuilder) new FilterGraphNoThread(); #if DEBUG m_rotEntry = new DsROTEntry(m_graph); #endif /* Create a capture graph builder to help * with rendering a capture graph */ var graphBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); /* Set our filter graph to the capture graph */ int hr = graphBuilder.SetFiltergraph(m_graph); DsError.ThrowExceptionForHR(hr); m_captureDevice = AddFilterByDevice(m_graph, device); object ampControl; int hr11 = graphBuilder.FindInterface(PinCategory.Capture, MediaType.Video, m_captureDevice , typeof(IAMCameraControl).GUID, out ampControl); DsError.ThrowExceptionForHR(hr11); iAMCameraControl = ampControl as IAMCameraControl; return(iAMCameraControl); }
public bool GetCameraPropertyRange(CameraControlProperty property, out int minValue, out int maxValue, out int stepSize, out int defaultValue, out CameraControlFlags controlFlags) { bool flag = true; if (deviceMoniker == null || string.IsNullOrEmpty(deviceMoniker)) { throw new ArgumentException("Video source is not specified."); } lock (sync) { object obj = null; try { obj = FilterInfo.CreateFilter(deviceMoniker); } catch { throw new ApplicationException("Failed creating device object for moniker."); } if (!(obj is IAMCameraControl)) { throw new NotSupportedException("The video source does not support camera control."); } IAMCameraControl iAMCameraControl = (IAMCameraControl)obj; int range = iAMCameraControl.GetRange(property, out minValue, out maxValue, out stepSize, out defaultValue, out controlFlags); flag = (range >= 0); Marshal.ReleaseComObject(obj); return(flag); } }
internal WebcamProperty GetControlProperties(CameraControlProperty property) { HResult result = HResult.ERROR_NOT_READY; WebcamProperty settings = new WebcamProperty { _name = property.ToString(), _controlProp = property }; if (_base._webcamMode) { IAMCameraControl control = _base.mf_MediaSource as IAMCameraControl; result = control.GetRange(property, out settings._min, out settings._max, out settings._step, out settings._default, out CameraControlFlags flags); if (result == Player.NO_ERROR) { settings._supported = (flags & CameraControlFlags.Manual) != 0; settings._autoSupport = (flags & CameraControlFlags.Auto) != 0; control.Get(property, out settings._value, out flags); settings._auto = (flags & CameraControlFlags.Auto) != 0; } } _base._lastError = result; return(settings); }
/// <summary> /// Dispose interface information /// </summary> private void disposeInterfaces() { m_graph = null; m_mediaControl = null; m_videoWindow = null; m_camControl = null; }
static void SetCameraFlag(DsDevice[] devs, string cameraName, CameraControlProperty camProperty, CameraControlFlags flagVal) { IAMCameraControl camera = GetCamera(devs.Where(d => d.Name.Contains(cameraName)).FirstOrDefault()); if (camera != null) { // Get the current settings from the webcam camera.Get(camProperty, out int v, out CameraControlFlags f); // If the camera property differs from the desired value, adjust it leaving value the same. if (f != flagVal) { camera.Set(camProperty, v, flagVal); Console.WriteLine($"{cameraName} {camProperty} set to {flagVal}"); } else { Console.WriteLine($"{cameraName} {camProperty} already {flagVal}"); } } else { Console.WriteLine($"No camera matching \"{cameraName}\" found"); } }
static void Main(string[] args) { // Get the list of connected video cameras DsDevice[] devs = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice); // Filter that list down to the one with hyper-aggressive focus var dev = devs.Where(d => d.Name.Equals("Microsoft® LifeCam HD-5000")).FirstOrDefault(); if (dev != null) { // DirectShow uses a module system called filters to exposure the functionality // We create a new object that implements the IFilterGraph2 interface so that we can // new filters to exposure the functionality that we need. if (new FilterGraph() is IFilterGraph2 graphBuilder) { // Create a video capture filter for the device graphBuilder.AddSourceFilterForMoniker(dev.Mon, null, dev.Name, out IBaseFilter capFilter); // Cast that filter to IAMCameraControl from the DirectShowLib IAMCameraControl _camera = capFilter as IAMCameraControl; // Get the current focus settings from the webcam _camera.Get(CameraControlProperty.Focus, out int v, out CameraControlFlags f); // If the camera was not in manual focus mode, lock it into manual at the current focus setting if (f != CameraControlFlags.Manual) { _camera.Set(CameraControlProperty.Focus, v, CameraControlFlags.Manual); } // _camera.Set(CameraControlProperty.Exposure, 20, CameraControlFlags.Auto); } } }
/// <summary> /// /// </summary> /// <param name="dsDevice"></param> /// <param name="prop"></param> /// <returns></returns> public int GetCameraControl(DsDevice dsDevice, CameraControlProperty prop) { IFilterGraph2 filterGraph = new FilterGraph() as IFilterGraph2; IBaseFilter capFilter = null; int retVal = 0; try { // add the video input device int hr = filterGraph.AddSourceFilterForMoniker(dsDevice.Mon, null, "Source Filter", out capFilter); DsError.ThrowExceptionForHR(hr); IAMCameraControl cameraControl = capFilter as IAMCameraControl; int min, max, step, default_val; CameraControlFlags flag = 0; cameraControl.GetRange(prop, out min, out max, out step, out default_val, out flag); cameraControl.Get(prop, out retVal, out flag); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(retVal); }
/// <summary> /// /// </summary> /// <param name="dsDevice"></param> /// <param name="bEnable"></param> public void AutoFocus(DsDevice dsDevice, bool bEnable) { IFilterGraph2 filterGraph = new FilterGraph() as IFilterGraph2; IBaseFilter capFilter = null; try { // add the video input device int hr = filterGraph.AddSourceFilterForMoniker(dsDevice.Mon, null, "Source Filter", out capFilter); DsError.ThrowExceptionForHR(hr); IAMCameraControl cameraControl = capFilter as IAMCameraControl; if (bEnable) { cameraControl.Set(CameraControlProperty.Focus, 250, CameraControlFlags.Auto); } else { cameraControl.Set(CameraControlProperty.Focus, 250, CameraControlFlags.Manual); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private void CloseInterfaces() { try { if (graphBuilder != null) { IMediaControl mediaCtrl = graphBuilder as IMediaControl; mediaCtrl.Stop(); } } catch {} if (graphBuilder != null) { Marshal.ReleaseComObject(graphBuilder); graphBuilder = null; } if (m_VideoControl != null) { Marshal.ReleaseComObject(m_VideoControl); m_VideoControl = null; } if (m_CameraControl != null) { Marshal.ReleaseComObject(m_CameraControl); m_CameraControl = null; } bgrData = null; }
public CamControlProperty(CameraPropertyDescriptor descriptor, IAMCameraControl cameraControl, CameraControlProperty cameraProperty) { Descriptor = descriptor; _cameraControl = cameraControl; _cameraProperty = cameraProperty; UpdateRange(); }
public LifeCamCamera(string name) { _name = name; String moniker = null; FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); // Match specified camera name to device for (int i = 0, n = videoDevices.Count; i < n; i++) { if (name == videoDevices[i].Name) { moniker = videoDevices[i].MonikerString; break; } } if (moniker == null) { return; } //throw new Exception("Video device with name '" + name + "' not found."); Source = new VideoCaptureDevice(moniker); Source.DesiredFrameRate = 30; cameraControls = (IAMCameraControl)Source.SourceObject; videoProcAmp = (IAMVideoProcAmp)Source.SourceObject; }
static void SetCameraValue(DsDevice[] devs, string cameraName, CameraControlProperty camProperty, int val) { IAMCameraControl camera = GetCamera(devs.Where(d => d.Name.ToLower().Contains(cameraName.ToLower())).FirstOrDefault()); if (camera != null) { // Get the current settings from the webcam camera.Get(camProperty, out int v, out CameraControlFlags f); // If the camera value differs from the desired value, adjust it leaving flag the same. if (v != val) { camera.Set(camProperty, val, f); Console.WriteLine($"{cameraName} {camProperty} value set to {val}"); } else { Console.WriteLine($"{cameraName} {camProperty} value already {val}"); } } else { Console.WriteLine($"No physical camera matching \"{cameraName}\" found"); } }
public CameraPropertySettings GetVideoPropertySettings(VideoProcAmpProperty property) { int filterHandle; IBaseFilter captureFilter = null; filterHandle = filterGraph.FindFilterByName("Video input", out captureFilter); if (captureFilter != null) { int min = 0; int max = 0; int stepDelta = 1; int defaultValue = 0; VideoProcAmpFlags videoFlags; IAMCameraControl iC = captureFilter as IAMCameraControl; ((IAMVideoProcAmp)iC).GetRange(property, out min, out max, out stepDelta, out defaultValue, out videoFlags); CameraPropertySettings videoPropertySettings = new CameraPropertySettings(); videoPropertySettings.Minimum = min; videoPropertySettings.Maximum = max; videoPropertySettings.Step = stepDelta; videoPropertySettings.DefaultValue = defaultValue; return(videoPropertySettings); } else { return(null); } }
public ViewModel() { if (devs.Length > 0) { RequestedCameraName = (string)Application.Current.Resources["CameraName"]; CameraNames = new List <String>(devs.Select(d => d.Name)); DsDevice cam = (DsDevice)devs.Where(d => d.Name.ToLower().Contains(RequestedCameraName.ToLower())).FirstOrDefault(); if (cam != null) { NoCameraFound = false; camera = GetCamera(cam); FocusProperties = CameraGetRange(camera, CameraControlProperty.Focus); Tuple <int, CameraControlFlags> focusSetting = CameraGetSettings(camera, CameraControlProperty.Focus); this.FocusValue = focusSetting.Item1; this.AutoFocusEnabled = focusSetting.Item2 == CameraControlFlags.Auto; ExposureProperties = CameraGetRange(camera, CameraControlProperty.Exposure); Tuple <int, CameraControlFlags> exposureSetting = CameraGetSettings(camera, CameraControlProperty.Exposure); this.ExposureValue = exposureSetting.Item1; this.AutoExposureEnabled = exposureSetting.Item2 == CameraControlFlags.Auto; } else { // No matching camera found //throw new ArgumentException("Matching camera not found - check the camera name in App Resources"); NoCameraFound = true; } } else { throw new NotSupportedException("No cameras found"); } }
public SelectedProperties(DsDevice dev) { InitializeComponent(); webcam = dev; HIDConnectEvent = new EventHandler(HIDConnected); HIDDisconnectEvent = new EventHandler(HIDDisconnected); Guid iid = typeof(IBaseFilter).GUID; webcam.Mon.BindToObject(null, null, ref iid, out object camDevice); IBaseFilter camFilter = camDevice as IBaseFilter; pCameraControl = camFilter as IAMCameraControl; pVideoProcAmp = camFilter as IAMVideoProcAmp; webcamName = INI.KeyExists("Name", webcam.DevicePath) ? INI.ReadINI(webcam.DevicePath, "Name") : webcam.Name; Anchor = AnchorStyles.Left | AnchorStyles.Right; Padding = new Padding(0); gBox = new GroupBox { AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top, Dock = DockStyle.Top, Text = webcamName, Margin = new Padding(0) }; mainLayout = new TableLayoutPanel { Name = "TableLayout", AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, Location = new Point(gBox.Padding.Left, gBox.Padding.Top + 20), Dock = DockStyle.Top, }; gBox.Controls.Add(mainLayout); Controls.Add(gBox); InitProperties(); InitHID(); if (hid == null) { HIDConnectEvent = new EventHandler(HIDConnected); Globals._USBControl.HIDConnected += HIDConnectEvent; } alertTimer = new System.Timers.Timer { Interval = 600, AutoReset = true, Enabled = false, }; alertTimer.Elapsed += AlertTimedEvent; }
private void ButtonForce_Click(object sender, EventArgs e) { Button btn = ( Button )sender; IAMCameraControl pCameraControl = ( IAMCameraControl )btn.Tag; pCameraControl.Set(CameraControlProperty.Focus, 0, CameraControlFlags.Manual); pCameraControl.Set(CameraControlProperty.Focus, 0, CameraControlFlags.Auto); }
public CamSetting(IAMCameraControl filter, CameraControlProperty property) { _CamFilter = filter; _CamProperty = property; _Name = property.ToString(); // Update all defaults min max, etc... Read(); }
protected override void FreeResources() { /* We run the StopInternal() to avoid any * Dispatcher VeryifyAccess() issues */ StopInternal(); /* Let's clean up the base * class's stuff first */ base.FreeResources(); #if DEBUG if (m_rotEntry != null) { m_rotEntry.Dispose(); } m_rotEntry = null; #endif if (m_videoFrame != null) { m_videoFrame.Dispose(); m_videoFrame = null; } if (m_renderer != null) { Marshal.FinalReleaseComObject(m_renderer); m_renderer = null; } if (m_captureDevice != null) { Marshal.FinalReleaseComObject(m_captureDevice); m_captureDevice = null; } if (m_sampleGrabber != null) { Marshal.FinalReleaseComObject(m_sampleGrabber); m_sampleGrabber = null; } if (m_graph != null) { Marshal.FinalReleaseComObject(m_graph); m_graph = null; InvokeMediaClosed(new EventArgs()); } if (m_cameraControl != null) { Marshal.FinalReleaseComObject(m_cameraControl); m_cameraControl = null; } if (m_videoProcAmp != null) { Marshal.FinalReleaseComObject(m_videoProcAmp); m_videoProcAmp = null; } }
private void Focus_change(TrackBar trackBar) { int Value = trackBar.Value - trackBar.Value % trackBar.TickFrequency; trackBar.Value = Value; int inverceValue = trackBar.Maximum - Value + trackBar.Minimum; IAMCameraControl pCameraControl = ( IAMCameraControl )trackBar.Tag; pCameraControl.Set(CameraControlProperty.Focus, inverceValue, CameraControlFlags.Manual); }
private Tuple <int, CameraControlFlags> CameraGetSettings(IAMCameraControl camera, CameraControlProperty cameraProperty) { int _value; CameraControlFlags _setting; camera.Get(cameraProperty, out _value, out _setting); return(new Tuple <int, CameraControlFlags>(_value, _setting)); }
private void TrackBarExposure_Scroll(object sender, EventArgs e) { TrackBar trackBar = ( TrackBar )sender; int Value = trackBar.Value - trackBar.Value % trackBar.TickFrequency; int inverceValue = trackBar.Maximum - Value + trackBar.Minimum; trackBar.Value = Value; IAMCameraControl pCameraControl = ( IAMCameraControl )trackBar.Tag; pCameraControl.Set(CameraControlProperty.Exposure, inverceValue, CameraControlFlags.Manual); ggghhh.Set(VideoProcAmpProperty.WhiteBalance, Value, VideoProcAmpFlags.Manual); }
public void SetVideoProperty(VideoProcAmpProperty property, int propertyValue) { int filterHandle; IBaseFilter captureFilter = null; filterHandle = filterGraph.FindFilterByName("Video input", out captureFilter); if (captureFilter != null) { IAMCameraControl iC = captureFilter as IAMCameraControl; ((IAMVideoProcAmp)iC).Set(property, propertyValue, VideoProcAmpFlags.Manual); } }
public void reloadCamera(int index = 0) { lock (_locker) { camIndex = index; try { // // Get the camera devices // TODO:: Provide the control system with a list of cameras to select from // TODO:: Provide a right click menu for selecting the camera to be controlled // TODO:: Event for sending out-of-turn status information to the control system // DsDevice[] capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice); // // Get the graphbuilder object // IFilterGraph2 graphBuilder = new FilterGraph() as IFilterGraph2; // // add the video input device // IBaseFilter camFilter = null; int hr = graphBuilder.AddSourceFilterForMoniker(capDevices[camIndex].Mon, null, capDevices[camIndex].Name, out camFilter); DsError.ThrowExceptionForHR(hr); // // Camera control object // theCamera = camFilter as IAMCameraControl; getProperties(); updateStatus("Camera", "Selected: " + capDevices[camIndex].Name, false); if (!cameraReady) { cameraReady = true; string[] lstCameras = new string[capDevices.Length]; for (int i = 0; i < capDevices.Length; i++) { lstCameras[i] = capDevices[i].Name; } updateCamList(lstCameras, camIndex); } } catch { cameraReady = false; updateStatus("Camera", "Error: unable to bind controls", false); } } }
public void InitDevice(DsDevice device, int iWidth, int iHeight) { int hr; object camDevice; Guid iid = typeof(IBaseFilter).GUID; device.Mon.BindToObject(null, null, ref iid, out camDevice); IBaseFilter camFilter = camDevice as IBaseFilter; m_CameraControl = camFilter as IAMCameraControl; m_VideoControl = camFilter as IAMVideoProcAmp; ISampleGrabber sampGrabber = null; graphBuilder = (IGraphBuilder) new FilterGraph(); //Create the Capture Graph Builder ICaptureGraphBuilder2 captureGraphBuilder = null; captureGraphBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); // Attach the filter graph to the capture graph hr = captureGraphBuilder.SetFiltergraph(this.graphBuilder); DsError.ThrowExceptionForHR(hr); //Add the Video input device to the graph hr = graphBuilder.AddFilter(camFilter, "WebCam" + deviceNumber); DsError.ThrowExceptionForHR(hr); // Configure the sample grabber sampGrabber = new SampleGrabber() as ISampleGrabber; ConfigureSampleGrabber(sampGrabber); IBaseFilter sampGrabberBF = sampGrabber as IBaseFilter; //Add the Video compressor filter to the graph hr = graphBuilder.AddFilter(sampGrabberBF, "SampleGrabber" + deviceNumber); DsError.ThrowExceptionForHR(hr); IBaseFilter nullRender = new NullRenderer() as IBaseFilter; graphBuilder.AddFilter(nullRender, "NullRenderer" + deviceNumber); InitResolution(captureGraphBuilder, camFilter, iWidth, iHeight); hr = captureGraphBuilder.RenderStream(PinCategory.Capture, MediaType.Video, camDevice, sampGrabberBF, nullRender); DsError.ThrowExceptionForHR(hr); SaveSizeInfo(sampGrabber); Marshal.ReleaseComObject(sampGrabber); Marshal.ReleaseComObject(captureGraphBuilder); }
public LifeCamCamera(string name, string nameContains, int cameraNumber) { _name = ""; String moniker = null; FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); Console.WriteLine(""); if (!string.IsNullOrEmpty(name)) { Console.WriteLine("Searching for camera name = '" + name + "'"); } if (!string.IsNullOrEmpty(nameContains)) { Console.WriteLine("Searching for camera name contains = '" + nameContains + "'"); } if (cameraNumber > 0) { Console.WriteLine("Searching for camera number = " + cameraNumber); } // Match specified camera name to device for (int i = 0, n = videoDevices.Count; i < n; i++) { Console.WriteLine("Camera " + (i + 1) + ": '" + videoDevices[i].Name + "'"); if ((name == videoDevices[i].Name) || (!string.IsNullOrEmpty(nameContains) && videoDevices[i].Name.IndexOf(nameContains) >= 0) || (cameraNumber == i + 1)) { moniker = videoDevices[i].MonikerString; _name = videoDevices[i].Name; cameraNumberFound = i + 1; break; } } if (moniker == null) { return; } //throw new Exception("Video device with name '" + name + "' not found."); Source = new VideoCaptureDevice(moniker); Source.DesiredFrameRate = 30; cameraControls = (IAMCameraControl)Source.SourceObject; videoProcAmp = (IAMVideoProcAmp)Source.SourceObject; }
void GetInterfaces() { Type comType = null; object comObj = null; try { //ICaptureGraphBuilder2 pBuilder = null; // Initiate Capture Graph Builder Guid clsid = typeof(CaptureGraphBuilder2).GUID; comType = Type.GetTypeFromCLSID(clsid); comObj = Activator.CreateInstance(comType); m_bCapGraph = (ICaptureGraphBuilder2)comObj; // Initiate Graph Builder Guid clsfg = typeof(FilterGraph).GUID; comType = Type.GetTypeFromCLSID(clsfg); //Clsid.FilterGraph); comObj = Activator.CreateInstance(comType); m_bGraph = (IGraphBuilder)comObj; // Initiate Video Configuration Interface DsGuid cat = PinCategory.Capture; DsGuid type = MediaType.Interleaved; Guid iid = typeof(IAMVideoProcAmp).GUID; m_bCapGraph.FindInterface(cat, type, capFilter, iid, out comObj); m_iVidConfig = (IAMVideoProcAmp)comObj; // test //m_iVidConfig.Set(VideoProcAmpProperty.WhiteBalance, 0, VideoProcAmpFlags.Manual); // Initiate Camera Configuration Interface cat = PinCategory.Capture; type = MediaType.Interleaved; iid = typeof(IAMCameraControl).GUID; m_bCapGraph.FindInterface(cat, type, capFilter, iid, out comObj); m_iCamConfig = (IAMCameraControl)comObj; } catch (Exception ee) { if (comObj != null) { Marshal.ReleaseComObject(comObj); } throw new Exception("Could not get interfaces\r\n" + ee.Message); } }
/// <summary> /// カメラの切断 /// </summary> private void Camera_Disconnect() { if (Camera_IsRunning) { Camera_Stop(); } // 同期用: サンプルグラバーのイベント登録解除: VideoGrabberCB.Enable = false; VideoGrabberCB.Notify -= VideoGrabberCB_Notify; #region 解放: if (CameraControl != null) { Marshal.ReleaseComObject(CameraControl); } CameraControl = null; if (VideoSource != null) { Marshal.ReleaseComObject(VideoSource); } VideoSource = null; if (VideoGrabber != null) { Marshal.ReleaseComObject(VideoGrabber); } VideoGrabber = null; if (VideoRenderer != null) { Marshal.ReleaseComObject(VideoRenderer); } VideoRenderer = null; if (Builder != null) { Marshal.ReleaseComObject(Builder); } Builder = null; if (Graph != null) { Marshal.ReleaseComObject(Graph); } Graph = null; #endregion }
public int GetVideoProperty(VideoProcAmpProperty property) { int filterHandle; IBaseFilter captureFilter = null; filterHandle = filterGraph.FindFilterByName("Video input", out captureFilter); int propertyValue = 0; VideoProcAmpFlags videoProcAmpFlags; if (captureFilter != null) { IAMCameraControl iC = captureFilter as IAMCameraControl; ((IAMVideoProcAmp)iC).Get(property, out propertyValue, out videoProcAmpFlags); } return(propertyValue); }
private void checkBoxExposure_CheckedChanged(object sender, EventArgs e) { CheckBox cb = ( CheckBox )sender; Button btn = ( Button )cb.Tag; TrackBar tBar = ( TrackBar )cb.Parent.Controls.Find("TrackBarExposure", false)[0]; IAMCameraControl pCameraControl = ( IAMCameraControl )btn.Tag; tBar.Enabled = !cb.Checked; if (cb.Checked) { pCameraControl.Set(CameraControlProperty.Exposure, tBar.Minimum, CameraControlFlags.Auto); } else { pCameraControl.Set(CameraControlProperty.Exposure, (tBar.Maximum - tBar.Value + tBar.Minimum), CameraControlFlags.Manual); } }
public CameraControl(VideoCaptureDevice vidDevice) { m_BaseFilter = vidDevice.BaseFilter; m_CameraControlInterface = (IAMCameraControl)m_BaseFilter; int valMin = 0; int valMax = 0; int valDefault = 0; int valStepping = 0; CameraControlFlags valFlags = CameraControlFlags.None; Controller.GetRange(CameraControlProperty.Pan, out valMin, out valMax, out valStepping, out valDefault, out valFlags); m_PanRange = new CamControlRange{Min = valMin, Max = valMax, Stepping = valStepping, Default = valDefault}; Controller.GetRange(CameraControlProperty.Tilt, out valMin, out valMax, out valStepping, out valDefault, out valFlags); m_TiltRange = new CamControlRange { Min = valMin, Max = valMax, Stepping = valStepping, Default = valDefault }; Controller.GetRange(CameraControlProperty.Roll, out valMin, out valMax, out valStepping, out valDefault, out valFlags); m_RollRange = new CamControlRange { Min = valMin, Max = valMax, Stepping = valStepping, Default = valDefault }; Controller.GetRange(CameraControlProperty.Zoom, out valMin, out valMax, out valStepping, out valDefault, out valFlags); m_ZoomRange = new CamControlRange { Min = valMin, Max = valMax, Stepping = valStepping, Default = valDefault }; }
private void CloseInterfaces() { try { if (graphBuilder != null) { IMediaControl mediaCtrl = graphBuilder as IMediaControl; mediaCtrl.Stop(); } } catch {} if (graphBuilder != null) { Marshal.ReleaseComObject(graphBuilder); graphBuilder = null; } if (m_VideoControl != null) { Marshal.ReleaseComObject(m_VideoControl); m_VideoControl = null; } if (m_CameraControl != null) { Marshal.ReleaseComObject(m_CameraControl); m_CameraControl = null; } bgrData = null; }
protected override void FreeResources() { /* We run the StopInternal() to avoid any * Dispatcher VeryifyAccess() issues */ StopInternal(); /* Let's clean up the base * class's stuff first */ base.FreeResources(); #if DEBUG if (m_rotEntry != null) m_rotEntry.Dispose(); m_rotEntry = null; #endif if (m_videoFrame != null) { m_videoFrame.Dispose(); m_videoFrame = null; } if (m_renderer != null) { Marshal.FinalReleaseComObject(m_renderer); m_renderer = null; } if (m_captureDevice != null) { Marshal.FinalReleaseComObject(m_captureDevice); m_captureDevice = null; } if (m_sampleGrabber != null) { Marshal.FinalReleaseComObject(m_sampleGrabber); m_sampleGrabber = null; } if (m_cameraControl != null) { Marshal.FinalReleaseComObject(m_cameraControl); m_cameraControl = null; } if (m_graph != null) { Marshal.FinalReleaseComObject(m_graph); m_graph = null; InvokeMediaClosed(new EventArgs()); } }
public void InitDevice(DsDevice device, int iWidth, int iHeight) { int hr; object camDevice; Guid iid = typeof(IBaseFilter).GUID; device.Mon.BindToObject(null, null, ref iid, out camDevice); IBaseFilter camFilter = camDevice as IBaseFilter; m_CameraControl = camFilter as IAMCameraControl; m_VideoControl = camFilter as IAMVideoProcAmp; ISampleGrabber sampGrabber = null; graphBuilder = (IGraphBuilder)new FilterGraph(); //Create the Capture Graph Builder ICaptureGraphBuilder2 captureGraphBuilder = null; captureGraphBuilder = (ICaptureGraphBuilder2)new CaptureGraphBuilder2(); // Attach the filter graph to the capture graph hr = captureGraphBuilder.SetFiltergraph(this.graphBuilder); DsError.ThrowExceptionForHR(hr); //Add the Video input device to the graph hr = graphBuilder.AddFilter(camFilter, "WebCam" + deviceNumber); DsError.ThrowExceptionForHR(hr); // Configure the sample grabber sampGrabber = new SampleGrabber() as ISampleGrabber; ConfigureSampleGrabber(sampGrabber); IBaseFilter sampGrabberBF = sampGrabber as IBaseFilter; //Add the Video compressor filter to the graph hr = graphBuilder.AddFilter(sampGrabberBF, "SampleGrabber" + deviceNumber); DsError.ThrowExceptionForHR(hr); IBaseFilter nullRender = new NullRenderer() as IBaseFilter; graphBuilder.AddFilter(nullRender, "NullRenderer" + deviceNumber); InitResolution(captureGraphBuilder, camFilter, iWidth, iHeight); hr = captureGraphBuilder.RenderStream(PinCategory.Capture, MediaType.Video, camDevice, sampGrabberBF, nullRender); DsError.ThrowExceptionForHR(hr); SaveSizeInfo(sampGrabber); Marshal.ReleaseComObject(sampGrabber); Marshal.ReleaseComObject(captureGraphBuilder); }
/// <summary> /// Sets the capture parameters for the video capture device /// </summary> private bool SetVideoCaptureParameters(ICaptureGraphBuilder2 capGraph, IBaseFilter captureFilter, Guid mediaSubType) { /* The stream config interface */ object streamConfig; /* Get the stream's configuration interface */ int hr = capGraph.FindInterface(PinCategory.Capture, MediaType.Video, captureFilter, typeof(IAMStreamConfig).GUID, out streamConfig); DsError.ThrowExceptionForHR(hr); var videoStreamConfig = streamConfig as IAMStreamConfig; /* If QueryInterface fails... */ if (videoStreamConfig == null) { throw new Exception("Failed to get IAMStreamConfig"); } object cameraControl; hr = capGraph.FindInterface(PinCategory.Capture, MediaType.Video, captureFilter, typeof(IAMCameraControl).GUID, out cameraControl); //not all camera support this interface, so don't throw exception if (hr >= 0) { m_cameraControl = cameraControl as IAMCameraControl; TryRetrieveExposureDatas(); TryRetrieveFocusDatas(); } /* The media type of the video */ AMMediaType media; /* Get the AMMediaType for the video out pin */ hr = videoStreamConfig.GetFormat(out media); DsError.ThrowExceptionForHR(hr); /* Make the VIDEOINFOHEADER 'readable' */ var videoInfo = new VideoInfoHeader(); Marshal.PtrToStructure(media.formatPtr, videoInfo); /* Setup the VIDEOINFOHEADER with the parameters we want */ videoInfo.AvgTimePerFrame = DSHOW_ONE_SECOND_UNIT / FPS; videoInfo.BmiHeader.Width = DesiredWidth; videoInfo.BmiHeader.Height = DesiredHeight; if (mediaSubType != Guid.Empty) { int fourCC = 0; byte[] b = mediaSubType.ToByteArray(); fourCC = b[0]; fourCC |= b[1] << 8; fourCC |= b[2] << 16; fourCC |= b[3] << 24; videoInfo.BmiHeader.Compression = fourCC; media.subType = mediaSubType; } /* Copy the data back to unmanaged memory */ Marshal.StructureToPtr(videoInfo, media.formatPtr, false); /* Set the format */ hr = videoStreamConfig.SetFormat(media); /* We don't want any memory leaks, do we? */ DsUtils.FreeAMMediaType(media); if (hr < 0) return false; return true; }
public override void Cleanup() { try { // To stop the capture filter before stopping the media control // seems to solve the problem described in the next comment. // sancta simplicitas... if (capFilter != null) { capFilter.Stop(); } // The stop or stopwhenready methods sometimes hang ... // This is a multithreading issue but I don´t solved it yet // But stopping is needed, otherwise the video device // is not disposed fast enough (due to GC) so at next initialization // with other params the video device seems to be in // use and the GraphBuilder render mehtod fails. if (mediaControl != null) { // This hangs when closing the GT int hr = mediaControl.Stop(); } isRunning = false; } catch (Exception) { //ErrorLogger.ProcessException(ex, false); } if (capFilter != null) { Marshal.ReleaseComObject(capFilter); capFilter = null; cameraControl = null; videoControl = null; videoStreamConfig = null; } if (videoProcAmp != null) { Marshal.ReleaseComObject(videoProcAmp); videoProcAmp = null; } if (sampGrabber != null) { Marshal.ReleaseComObject(sampGrabber); sampGrabber = null; } if (graphBuilder != null) { Marshal.ReleaseComObject(graphBuilder); graphBuilder = null; mediaControl = null; hasValidGraph = false; } if (capGraph != null) { Marshal.ReleaseComObject(capGraph); capGraph = null; } if (map != IntPtr.Zero) { UnmapViewOfFile(map); map = IntPtr.Zero; } if (section != IntPtr.Zero) { CloseHandle(section); section = IntPtr.Zero; } #if DEBUG if (this.rotEntry != null) { // This hangs when closing the GT this.rotEntry.Dispose(); } #endif }
/// <summary> /// Connects to the property changed events of the camera settings. /// </summary> //private void Initialize() //{ // //Settings.Instance.Camera.OnCameraControlPropertyChanged += OnCameraControlPropertyChanged; // //Settings.Instance.Camera.OnVideoProcAmpPropertyChanged += OnVideoProcAmpPropertyChanged; // //Settings.Instance.Camera.OnVideoControlFlagsChanged += OnVideoControlFlagsChanged; // //stopwatch = new Stopwatch(); //} /// <summary> /// Build the capture graph for grabber. /// </summary> /// <param name="dev">The index of the new capture device.</param> /// <param name="frameRate">The framerate to use.</param> /// <param name="width">The width to use.</param> /// <param name="height">The height to use.</param> /// <returns>True, if successful, otherwise false.</returns> private bool SetupGraph(DsDevice dev, int frameRate, int width, int height) { int hr; fps = frameRate; // Not measured, only to expose FPS externally cameraControl = null; capFilter = null; // Get the graphbuilder object graphBuilder = (IFilterGraph2)new FilterGraph(); mediaControl = graphBuilder as IMediaControl; try { // Create the ICaptureGraphBuilder2 capGraph = (ICaptureGraphBuilder2)new CaptureGraphBuilder2(); // Create the SampleGrabber interface sampGrabber = (ISampleGrabber)new SampleGrabber(); // Start building the graph hr = capGraph.SetFiltergraph(graphBuilder); //if (hr != 0) // ErrorLogger.WriteLine("Error in capGraph.SetFiltergraph. Could not build graph. Message: " + // DsError.GetErrorText(hr)); #if DEBUG this.rotEntry = new DsROTEntry(this.graphBuilder); #endif this.capFilter = CreateFilter( FilterCategory.VideoInputDevice, dev.Name); if (this.capFilter != null) { hr = graphBuilder.AddFilter(this.capFilter, "Video Source"); DsError.ThrowExceptionForHR(hr); } //// Add the video device //hr = graphBuilder.AddSourceFilterForMoniker(dev.Mon, null, "Video input", out capFilter); //if (hr != 0) // ErrorLogger.WriteLine( // "Error in m_graphBuilder.AddSourceFilterForMoniker(). Could not add source filter. Message: " + // DsError.GetErrorText(hr)); var baseGrabFlt = (IBaseFilter)sampGrabber; ConfigureSampleGrabber(sampGrabber); // Add the frame grabber to the graph hr = graphBuilder.AddFilter(baseGrabFlt, "Ds.NET Grabber"); //if (hr != 0) // ErrorLogger.WriteLine("Error in m_graphBuilder.AddFilter(). Could not add filter. Message: " + // DsError.GetErrorText(hr)); // turn on the infrared leds ONLY FOR THE GENIUS WEBCAM /* if (!defaultMode) { m_icc = capFilter as IAMCameraControl; CameraControlFlags CamFlags = new CameraControlFlags(); int pMin, pMax, pStep, pDefault; hr = m_icc.GetRange(CameraControlProperty.Focus, out pMin, out pMax, out pStep, out pDefault, out CamFlags); m_icc.Set(CameraControlProperty.Focus, pMax, CameraControlFlags.None); } */ //IBaseFilter smartTee = new SmartTee() as IBaseFilter; //// Add the smart tee filter to the graph //hr = this.graphBuilder.AddFilter(smartTee, "Smart Tee"); //Marshal.ThrowExceptionForHR(hr); // Connect the video source output to the smart tee //hr = capGraph.RenderStream(null, null, capFilter, null, smartTee); hr = capGraph.RenderStream(PinCategory.Capture, MediaType.Video, capFilter, null, baseGrabFlt); var errorText = DsError.GetErrorText(hr); cameraControl = capFilter as IAMCameraControl; // Set videoProcAmp object obj; var iid_IBaseFilter = new Guid("56a86895-0ad4-11ce-b03a-0020af0ba770"); DirectShowDevices.Instance.Cameras[deviceNumber].DirectshowDevice.Mon.BindToObject( null, null, ref iid_IBaseFilter, out obj); videoProcAmp = obj as IAMVideoProcAmp; // If any of the default config items are set if (frameRate + height + width > 0) SetConfigParms(capGraph, capFilter, frameRate, width, height); // Check for successful rendering, if this failed the class cannot be used, so dispose the resources and return false. if (hr < 0) { Cleanup(); return false; } else { // Otherwise update the SampleGrabber. SaveSizeInfo(sampGrabber); hr = sampGrabber.SetBufferSamples(false); if (hr == 0) { hr = sampGrabber.SetOneShot(false); hr = sampGrabber.SetCallback(this, 1); } //if (hr < 0) // ErrorLogger.WriteLine("Could not set callback function (SetupGraph) in Camera.Capture()"); } } catch (Exception) { //ErrorLogger.ProcessException(ex, false); Cleanup(); return false; } return true; }
/// <summary> /// カメラの接続 /// </summary> /// <param name="filterInfo"></param> /// <param name="pinno"></param> /// <param name="frameSize"></param> private void Camera_Connect(CxFilterInfo filterInfo, int pinno, Size frameSize) { #region グラフビルダーの生成: { Graph = (IGraphBuilder)Axi.CoCreateInstance(GUID.CLSID_FilterGraph); if (Graph == null) throw new System.IO.IOException("Failed to create a GraphBuilder."); Builder = (ICaptureGraphBuilder2)Axi.CoCreateInstance(GUID.CLSID_CaptureGraphBuilder2); if (Builder == null) throw new System.IO.IOException("Failed to create a GraphBuilder."); Builder.SetFiltergraph(Graph); } #endregion #region 映像入力用: ソースフィルタを生成します. { VideoSource = Axi.CreateFilter(GUID.CLSID_VideoInputDeviceCategory, filterInfo.CLSID, filterInfo.Index); if (VideoSource == null) throw new System.IO.IOException("Failed to create a VideoSource."); Graph.AddFilter(VideoSource, "VideoSource"); // フレームサイズを設定します. // ※注) この操作は、ピンを接続する前に行う必要があります. IPin pin = Axi.FindPin(VideoSource, pinno, PIN_DIRECTION.PINDIR_OUTPUT); Axi.SetFormatSize(pin, frameSize.Width, frameSize.Height); } #endregion #region 映像捕獲用: サンプルグラバーを生成します. { VideoGrabber = (IBaseFilter)Axi.CoCreateInstance(GUID.CLSID_SampleGrabber); if (VideoGrabber == null) throw new System.IO.IOException("Failed to create a VideoGrabber."); Graph.AddFilter(VideoGrabber, "VideoGrabber"); // サンプルグラバフィルタの入力形式設定. // SetMediaType で必要なメディア タイプを指定します。 // http://msdn.microsoft.com/ja-jp/library/cc369546.aspx // ※AM_MEDIA_TYPE 構造体のメンバをすべて設定する必要はない。 // ※デフォルトでは、サンプル グラバに優先メディア タイプはない。 // ※サンプル グラバを正しいフィルタに確実に接続するには、フィルタ グラフを作成する前にこのメソッドを呼び出す。 // majortype: http://msdn.microsoft.com/ja-jp/library/cc370108.aspx // subtype : http://msdn.microsoft.com/ja-jp/library/cc371040.aspx { var grabber = (ISampleGrabber)VideoGrabber; var mt = new AM_MEDIA_TYPE(); mt.majortype = new Guid(GUID.MEDIATYPE_Video); mt.subtype = new Guid(GUID.MEDIASUBTYPE_RGB24); mt.formattype = new Guid(GUID.FORMAT_VideoInfo); grabber.SetMediaType(mt); grabber.SetBufferSamples(false); // サンプルコピー 無効. grabber.SetOneShot(false); // One Shot 無効. //grabber.SetCallback(VideoGrabberCB, 0); // 0:SampleCB メソッドを呼び出すよう指示する. grabber.SetCallback(VideoGrabberCB, 1); // 1:BufferCB メソッドを呼び出すよう指示する. } } #endregion #region 映像出力用: レンダラーを生成します. { VideoRenderer = (IBaseFilter)Axi.CoCreateInstance(GUID.CLSID_NullRenderer); if (VideoRenderer == null) throw new System.IO.IOException("Failed to create a VideoRenderer."); Graph.AddFilter(VideoRenderer, "VideoRenderer"); } #endregion #region フィルタの接続: unsafe { var mediatype = new Guid(GUID.MEDIATYPE_Video); var hr = (HRESULT)Builder.RenderStream(IntPtr.Zero, new IntPtr(&mediatype), VideoSource, VideoGrabber, VideoRenderer); if (hr < HRESULT.S_OK) throw new CxDSException(hr); } #endregion // 同期用: サンプルグラバーのイベント登録: VideoGrabberCB.Enable = true; VideoGrabberCB.Notify += VideoGrabberCB_Notify; VideoInfoHeader = Axi.GetVideoInfo((ISampleGrabber)VideoGrabber); // カメラ制御インターフェースの抽出. CameraControl = Axi.GetInterface<IAMCameraControl>(this.Graph); }
/// <summary> /// カメラの切断 /// </summary> private void Camera_Disconnect() { if (Camera_IsRunning) Camera_Stop(); // 同期用: サンプルグラバーのイベント登録解除: VideoGrabberCB.Enable = false; VideoGrabberCB.Notify -= VideoGrabberCB_Notify; #region 解放: if (CameraControl != null) Marshal.ReleaseComObject(CameraControl); CameraControl = null; if (VideoSource != null) Marshal.ReleaseComObject(VideoSource); VideoSource = null; if (VideoGrabber != null) Marshal.ReleaseComObject(VideoGrabber); VideoGrabber = null; if (VideoRenderer != null) Marshal.ReleaseComObject(VideoRenderer); VideoRenderer = null; if (Builder != null) Marshal.ReleaseComObject(Builder); Builder = null; if (Graph != null) Marshal.ReleaseComObject(Graph); Graph = null; #endregion }