/// <summary> build the capture graph for grabber. </summary> private void SetupGraph(string destFilename, string encoderName) { int hr; // Get the graphbuilder object captureGraphBuilder = new DirectShowLib.CaptureGraphBuilder2() as DirectShowLib.ICaptureGraphBuilder2; IFilterGraph2 filterGraph = new DirectShowLib.FilterGraph() as DirectShowLib.IFilterGraph2; mediaCtrl = filterGraph as DirectShowLib.IMediaControl; IMediaFilter mediaFilt = filterGraph as IMediaFilter; mediaEvent = filterGraph as IMediaEvent; captureGraphBuilder.SetFiltergraph(filterGraph); IBaseFilter aviMux; IFileSinkFilter fileSink = null; hr = captureGraphBuilder.SetOutputFileName(MediaSubType.Avi, destFilename, out aviMux, out fileSink); DsError.ThrowExceptionForHR(hr); DirectShowLib.IBaseFilter compressor = DirectShowUtils.GetVideoCompressor(encoderName); if (compressor == null) { throw new InvalidCodecException(encoderName); } hr = filterGraph.AddFilter(compressor, "compressor"); DsError.ThrowExceptionForHR(hr); // Our data source IBaseFilter source = (IBaseFilter) new GenericSampleSourceFilter(); // Get the pin from the filter so we can configure it IPin ipin = DsFindPin.ByDirection(source, PinDirection.Output, 0); try { // Configure the pin using the provided BitmapInfo ConfigurePusher((IGenericSampleConfig)ipin); } finally { Marshal.ReleaseComObject(ipin); } // Add the filter to the graph hr = filterGraph.AddFilter(source, "GenericSampleSourceFilter"); Marshal.ThrowExceptionForHR(hr); hr = filterGraph.AddFilter(source, "source"); DsError.ThrowExceptionForHR(hr); hr = captureGraphBuilder.RenderStream(null, null, source, compressor, aviMux); DsError.ThrowExceptionForHR(hr); IMediaPosition mediaPos = filterGraph as IMediaPosition; hr = mediaCtrl.Run(); DsError.ThrowExceptionForHR(hr); }
/// <summary> Shut down capture </summary> private void CloseInterfaces() { int hr; try { if (mediaCtrl != null) { // Stop the graph hr = mediaCtrl.Stop(); mediaCtrl = null; } } catch (Exception ex) { Debug.WriteLine(ex); } if (captureGraphBuilder != null) { Marshal.ReleaseComObject(captureGraphBuilder); captureGraphBuilder = null; } GC.Collect(); }