public void Stop() { if (_cancelToken != null) { _cancelToken.Cancel(); capGrabber = null; } }
public void Start() { //creates new instance of the cancellationtoken _cancelToken = new CancellationTokenSource(); Task.Factory.StartNew(() => { // Create new grabber capGrabber = new CapGrabber(); capGrabber.PropertyChanged += capGrabber_PropertyChanged; capGrabber.NewFrameArrived += capGrabber_NewFrameArrived; var graph = Activator.CreateInstance(Type.GetTypeFromCLSID(FilterGraph)) as IGraphBuilder; var sourceObject = FilterInfo.CreateFilter(deviceMoniker); var grabber = Activator.CreateInstance(Type.GetTypeFromCLSID(SampleGrabber)) as ISampleGrabber; var grabberObject = grabber as IBaseFilter; if (graph == null) { return; } graph.AddFilter(sourceObject, "source"); graph.AddFilter(grabberObject, "grabber"); using (var mediaType = new AMMediaType()) { mediaType.MajorType = MediaTypes.Video; mediaType.SubType = MediaSubTypes.RGB32; if (grabber != null) { grabber.SetMediaType(mediaType); if (graph.Connect(sourceObject.GetPin(PinDirection.Output, 0), grabberObject.GetPin(PinDirection.Input, 0)) >= 0) { if (grabber.GetConnectedMediaType(mediaType) == 0) { VideoInfoHeader header = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.FormatPtr, typeof(VideoInfoHeader)); capGrabber.Width = header.BmiHeader.Width; capGrabber.Height = header.BmiHeader.Height; } } graph.Render(grabberObject.GetPin(PinDirection.Output, 0)); grabber.SetBufferSamples(false); grabber.SetOneShot(false); grabber.SetCallback(capGrabber, 1); } // Get the video window var wnd = (IVideoWindow)graph; wnd.put_AutoShow(false); // Create the control and run var control = (IMediaControl)graph; control.Run(); // Wait for the stop signal var stopSignal = new ManualResetEventSlim(false); using (_cancelToken.Token.Register(stopSignal.Set)) stopSignal.Wait(); // Stop when ready control.StopWhenReady(); capGrabber = null; } }, _cancelToken.Token); }